-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.py
More file actions
403 lines (336 loc) · 15.9 KB
/
node.py
File metadata and controls
403 lines (336 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# Copyright 2026 R Quincy Robinson. Licensed under PolyForm Noncommercial 1.0.0 — see LICENSE.
"""
node.py
Single Cn node (quincunx) construction for the Beaucephas hypercube model.
Each node consists of:
- Four cardinal 8x8 matrices (north, south, east, west) with dual headers
- One center 8x8 matrix (cellwise average of the four cardinals)
- A summary table (sum, mean, high, low per cardinal)
- lohi pairs per cardinal (used to populate Console node_grid AA2:AI10)
Fully verified against Cn5 ground truth from refactor_beaucephas_web_v0_2.xlsx.
"""
from gua import (
get_liangyi_vals, stack_position_offset,
compute_upper_liangyi, compute_lower_liangyi,
compute_gua_lookup, build_cardinal_headers,
build_body_8x8, cellwise_average,
annotate_matrix, COL_LOOKUP_SYMBOLS,
center_node_level,
)
from constants import CARDINALS, PLANES_31, PLANE_BY_LEVEL
# ── CARDINAL GUA SYMBOL CONFIGURATIONS ───────────────────────────────────────
# Col and row symbol sequences for each cardinal's 8x8 matrix headers.
#
# Both col and row sequences are permutations of COL_LOOKUP_SYMBOLS ordering
# (the binary gua order: ☰,☴,☲,☱,☶,☵,☳,☷ = indices 1..8).
#
# Forward cardinals (N/E) use each sequence directly.
# Anti-symmetric cardinals (S/W) use the bitwise-complement reverse —
# a structural consequence of the anti-symmetric binary encoding, not
# an independent choice.
#
# User-facing parameters: col_seq and row_seq — permutations of [1..8]
# where 1=☰ ... 8=☷ (COL_LOOKUP_SYMBOLS indexing).
#
# Default sequences (verified from Cn5 ground truth):
# col_seq = [1,2,3,4,5,6,7,8] — identity, N/E col = COL_LOOKUP order
# row_seq = [1,4,3,7,2,6,5,8] — N/E row = [☰,☱,☲,☳,☴,☵,☶,☷]
#
# Test ordering "col=12345678, row=87654321" in spreadsheet notation:
# col_seq = [8,7,6,5,4,3,2,1] — reversed, N/E col = anti-symmetric order
# row_seq = [1,2,3,4,5,6,7,8] — identity, N/E row = COL_LOOKUP order
DEFAULT_COL_SEQ = [1, 2, 3, 4, 5, 6, 7, 8] # identity on COL_LOOKUP_SYMBOLS
DEFAULT_ROW_SEQ = [1, 4, 3, 2, 7, 6, 5, 8] # gives [☰,☱,☲,☳,☴,☵,☶,☷] for N/E
def resolve_sym_seq(seq_1based):
"""Convert 1-based COL_LOOKUP_SYMBOLS index sequence to symbol list."""
return [COL_LOOKUP_SYMBOLS[i - 1] for i in seq_1based]
def cardinal_col_syms(col_seq=None):
"""
Build per-cardinal col symbol sequences from a user index sequence.
Forward cardinals (N/E) use col_seq resolved through COL_LOOKUP_SYMBOLS.
Anti-symmetric cardinals (S/W) use the reverse, preserving the bitwise
complement anti-symmetry of the binary encoding.
col_seq : list[int] — 1-based indices into COL_LOOKUP_SYMBOLS (default: [1..8])
"""
if col_seq is None:
col_seq = DEFAULT_COL_SEQ
syms = resolve_sym_seq(col_seq)
rev = list(reversed(syms))
return {
'north': syms, # forward
'south': rev, # anti-symmetric
'east': syms, # forward
'west': rev, # anti-symmetric
}
def cardinal_row_syms(row_seq=None):
"""
Build per-cardinal row symbol sequences from a user index sequence.
Forward cardinals (N/E) use row_seq resolved through COL_LOOKUP_SYMBOLS.
Anti-symmetric cardinals (S/W) use the reverse.
row_seq : list[int] — 1-based indices into COL_LOOKUP_SYMBOLS (default: [1,4,3,7,2,6,5,8])
"""
if row_seq is None:
row_seq = DEFAULT_ROW_SEQ
syms = resolve_sym_seq(row_seq)
rev = list(reversed(syms))
return {
'north': syms, # forward
'south': rev, # anti-symmetric
'east': syms, # forward
'west': rev, # anti-symmetric
}
# Default symbol mappings (verified from Cn5 ground truth)
CARDINAL_COL_SYMS = cardinal_col_syms(DEFAULT_COL_SEQ)
CARDINAL_ROW_SYMS = cardinal_row_syms(DEFAULT_ROW_SEQ)
# ── PLANE SELECTION ───────────────────────────────────────────────────────────
def compute_lohi(cardinal, body_8x8, col_syms, row_syms, plane_level):
"""
Compute the lohi pair (low, high) for a cardinal matrix under a given plane.
Mirrors the AJ3:AK7 formulas on each Cn sheet.
Column mapping from 31 Planes (verified from actual spreadsheet formulas):
N/E lohi_low uses cols 6,7 (pair_high_lower, pair_high_upper)
N/E lohi_high uses cols 3,4 (pair_low_lower, pair_low_upper)
S/W lohi_low uses cols 3,4 (pair_low_lower, pair_low_upper)
S/W lohi_high uses cols 6,7 (pair_high_lower, pair_high_upper)
Parameters
----------
cardinal : str — 'north','south','east','west'
body_8x8 : list[list[int]] — 8x8 body matrix
col_syms : list[str] — 8 column gua symbols for this cardinal
row_syms : list[str] — 8 row gua symbols for this cardinal
plane_level : int — active plane (1-32)
Returns
-------
tuple(int, int) — (low_value, high_value)
"""
plane = PLANE_BY_LEVEL[plane_level]
# plane tuple: (level, kws_low, low_lower, low_upper,
# kws_high, high_lower, high_upper, ...)
# 0-based indices: 2=low_lower, 3=low_upper, 5=high_lower, 6=high_upper
if cardinal in ('north', 'east'):
# AJ (low) uses cols 6,7 = high_lower, high_upper
# AK (high) uses cols 3,4 = low_lower, low_upper
low_row_sym, low_col_sym = plane[5], plane[6]
high_row_sym, high_col_sym = plane[2], plane[3]
else: # south, west
# AJ (low) uses cols 3,4 = low_lower, low_upper
# AK (high) uses cols 6,7 = high_lower, high_upper
low_row_sym, low_col_sym = plane[2], plane[3]
high_row_sym, high_col_sym = plane[5], plane[6]
def lookup(row_sym, col_sym):
if row_sym not in row_syms:
raise ValueError(f"plane symbol {row_sym!r} not in row_syms for {cardinal}")
if col_sym not in col_syms:
raise ValueError(f"plane symbol {col_sym!r} not in col_syms for {cardinal}")
return body_8x8[row_syms.index(row_sym)][col_syms.index(col_sym)]
return (lookup(low_row_sym, low_col_sym),
lookup(high_row_sym, high_col_sym))
# ── CARDINAL SUMMARY ──────────────────────────────────────────────────────────
# Central 2×2 cell positions excluded from the canonical 60-cell active sum.
# Verified from spreadsheet formula at Cn5!AI:
# =SUM(Y28:AF35) - SUM(AB31:AC32)
# = full 8×8 sum − central 2×2 sum = 60-cell active sum
# The 4 central cells equal the body mean and are the invariant pivot;
# the 60 active cells form 30 antipodal pairs each summing to the same constant.
CENTRAL_4_CELLS = {(3, 3), (3, 4), (4, 3), (4, 4)}
def cardinal_summary(body_8x8):
"""
Compute summary statistics for a single cardinal 8x8 body.
Mirrors AH2:AL7 summary table on each Cn sheet.
Canonical sum uses 60 active cells only, excluding the central 2×2
(positions [3][3],[3][4],[4][3],[4][4]), per verified spreadsheet formula:
=SUM(full_8x8) - SUM(central_2x2)
The mean is computed over all 64 cells (central 4 = body mean, so
mean is identical whether computed on 60 or 64 cells).
low/high are taken from the 60 active cells only.
Parameters
----------
body_8x8 : list[list[int]] — 8x8 body matrix
Returns
-------
dict: 'sum' (60-cell), 'mean' (64-cell), 'low' (60-cell), 'high' (60-cell),
'sum_64' (full 64-cell sum for reference)
"""
flat_64 = [body_8x8[i][j] for i in range(8) for j in range(8)]
flat_60 = [body_8x8[i][j] for i in range(8) for j in range(8)
if (i, j) not in CENTRAL_4_CELLS]
return {
'sum': sum(flat_60),
'sum_64': sum(flat_64),
'mean': sum(flat_64) / 64,
'low': min(flat_60),
'high': max(flat_60),
}
# ── NODE CONSTRUCTION ─────────────────────────────────────────────────────────
class CnNode:
"""
A single node (Cn5–Cn13) of the hypercube.
Encapsulates the full quincunx structure: 4 cardinal bodies + center.
Parameters
----------
node_level : int — Cn level number (5-13)
basis_top : list[int] — top gua basis vector [pos3,pos2,pos1] (sheet order)
basis_low : list[int] — low gua basis vector [pos1,pos2,pos3] (sheet order)
plane_level : int — active plane selector (1-32, default=1)
col_seq : list[int] — 1-based BAGUA_SYMBOLS index sequence for columns
(default: [1,2,3,4,5,6,7,8] — identity on COL_LOOKUP_SYMBOLS)
row_seq : list[int] — 1-based BAGUA_SYMBOLS index sequence for rows
(default: [1,4,3,7,2,6,5,8] — gives [☰,☱,☲,☳,☴,☵,☶,☷] for N/E)
Symbol ordering note: col_seq and row_seq are applied uniformly across all
cardinals. Forward cardinals (N/E) and anti-symmetric cardinals (S/W) receive
reverse-of-each-other sequences automatically, preserving the bitwise complement
anti-symmetry of the encoding.
"""
def __init__(self, node_level, basis_top, basis_low, plane_level=1,
col_seq=None, row_seq=None, center_level=9):
self.node_level = node_level
self.center_level = center_level
self.basis_top = basis_top
self.basis_low = basis_low
self.plane_level = plane_level
self.col_seq = col_seq if col_seq is not None else list(DEFAULT_COL_SEQ)
self.row_seq = row_seq if row_seq is not None else list(DEFAULT_ROW_SEQ)
self._compute()
def _compute(self):
"""Run the full computation chain for this node."""
lv = get_liangyi_vals(self.node_level)
offset = stack_position_offset(self.node_level, self.center_level)
self.liangyi_vals = lv
self.stack_offset = offset
# Upper and lower liangyi tables
self.upper_liangyi = compute_upper_liangyi(self.basis_top, lv, offset)
self.lower_liangyi = compute_lower_liangyi(self.basis_low, lv, offset)
# Resolve per-cardinal symbol sequences from user index sequences
col_syms_map = cardinal_col_syms(self.col_seq)
row_syms_map = cardinal_row_syms(self.row_seq)
# Build four cardinal matrices
self.cardinals = {}
for card in CARDINALS:
col_syms = col_syms_map[card]
row_syms = row_syms_map[card]
hdrs = build_cardinal_headers(
card,
self.basis_top, self.basis_low, lv,
col_syms, row_syms, offset
)
body = build_body_8x8(hdrs['col_headers'], hdrs['row_headers'])
summ = cardinal_summary(body)
lohi = compute_lohi(card, body, col_syms, row_syms, self.plane_level)
self.cardinals[card] = {
'col_syms': col_syms,
'row_syms': row_syms,
'col_headers': hdrs['col_headers'],
'row_headers': hdrs['row_headers'],
'body': body,
'summary': summ,
'lohi': lohi,
}
# Center: cellwise average of four cardinal bodies
self.center = cellwise_average([
self.cardinals[c]['body'] for c in CARDINALS
])
def get_body(self, cardinal):
"""Return raw 8x8 body for a cardinal direction."""
return self.cardinals[cardinal]['body']
def get_center(self):
"""Return raw 8x8 center body."""
return self.center
def get_lohi(self, cardinal):
"""Return (low, high) plane-selected value pair for a cardinal."""
return self.cardinals[cardinal]['lohi']
def get_summary(self, cardinal):
"""Return summary stats for a cardinal."""
return self.cardinals[cardinal]['summary']
def annotated_body(self, cardinal):
"""Return annotated 8x8 body with digital root metadata."""
return annotate_matrix(self.cardinals[cardinal]['body'], include_dr10=False)
def annotated_center(self):
"""Return annotated center body with both dr9 and dr10 metadata."""
return annotate_matrix(self.center, include_dr10=True)
def set_plane(self, plane_level):
"""Update plane selector and recompute lohi pairs."""
self.plane_level = plane_level
for card in CARDINALS:
c = self.cardinals[card]
c['lohi'] = compute_lohi(
card, c['body'], c['col_syms'], c['row_syms'], plane_level
)
def set_symbol_order(self, col_seq=None, row_seq=None):
"""
Update col and/or row index sequences and recompute all bodies.
col_seq : list[int] — 1-based BAGUA_SYMBOLS indices for columns
row_seq : list[int] — 1-based BAGUA_SYMBOLS indices for rows
Example — reverse the row sequence:
node.set_symbol_order(row_seq=[8,7,6,5,4,3,2,1])
"""
if col_seq is not None:
self.col_seq = col_seq
if row_seq is not None:
self.row_seq = row_seq
self._compute()
def summary_table(self):
"""
Return full summary table (mirrors AH2:AL7 on Cn sheet).
Returns dict of cardinal -> {sum, mean, low, high, lohi}.
"""
return {
card: {**self.cardinals[card]['summary'],
'lohi': self.cardinals[card]['lohi']}
for card in CARDINALS
}
def __repr__(self):
return (f"CnNode(level={self.node_level}, "
f"offset={self.stack_offset}, plane={self.plane_level})")
# ── VERIFICATION ──────────────────────────────────────────────────────────────
def verify_cn5_node():
"""
Verify CnNode construction against Cn5 ground truth.
Default: basis_top=[3,2,1], basis_low=[1,2,3], plane=1.
"""
details = []
passed = True
def check(label, computed, expected):
nonlocal passed
ok = computed == expected
details.append(f"{'OK' if ok else 'FAIL'} {label}")
if not ok:
details.append(f" computed: {computed}")
details.append(f" expected: {expected}")
passed = False
node = CnNode(
node_level = 5,
basis_top = [3, 2, 1],
basis_low = [1, 2, 3],
plane_level = 1,
center_level = 9,
)
# South body corners
sb = node.get_body('south')
check("south_body[0][0]", sb[0][0], 24)
check("south_body[7][7]", sb[7][7], 84)
# North body corners
nb = node.get_body('north')
check("north_body[0][0]", nb[0][0], 12)
check("north_body[7][7]", nb[7][7], 72)
# East body corners
eb = node.get_body('east')
check("east_body[0][0]", eb[0][0], 36)
check("east_body[7][7]", eb[7][7], 96)
# West body corners
wb = node.get_body('west')
check("west_body[0][0]", wb[0][0], 48)
check("west_body[7][7]", wb[7][7], 108)
# Center body corners (average of 4 cardinals)
cb = node.get_center()
check("center_body[0][0]", cb[0][0], 30.0) # (24+12+36+48)/4
check("center_body[7][7]", cb[7][7], 90.0) # (84+72+96+108)/4
# lohi pairs (plane=1, default)
check("lohi_north", node.get_lohi('north'), (12, 72))
check("lohi_south", node.get_lohi('south'), (24, 84))
check("lohi_east", node.get_lohi('east'), (36, 96))
check("lohi_west", node.get_lohi('west'), (48, 108))
# Summary stats for south
ss = node.get_summary('south')
check("south_summary_low", ss['low'], 24)
check("south_summary_high", ss['high'], 84)
return {'passed': passed, 'details': details}