-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbsp.py
More file actions
302 lines (261 loc) · 10.8 KB
/
bsp.py
File metadata and controls
302 lines (261 loc) · 10.8 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
#!/usr/bin/env python3
"""
bsp.py — pure-form BSP for pscale JSON blocks.
No tree wrapper, no tuning field, no metadata. The block IS the tree.
Floor derived from the underscore chain. Digit 0 maps to key '_'.
Modes:
bsp(block) → dir: full tree (depth-1 survey)
bsp(block, number) → spindle: root-to-target chain
bsp(block, number, 'ring') → ring: siblings at terminal
bsp(block, number, 'dir') → dir: subtree from target down
bsp(block, number, pscale, 'point') → point: single node at pscale
bsp(block, _, depth, 'disc') → disc: all nodes at a depth
CLI:
python bsp.py pscale-touchstone # dir
python bsp.py pscale-touchstone 0.21 # spindle
python bsp.py pscale-touchstone 0.21 ring # ring
python bsp.py pscale-touchstone 0.21 dir # subtree
python bsp.py pscale-touchstone 0.3 -2 point # point at pscale -2
python bsp.py pscale-touchstone _ 3 disc # disc at depth 3
Address conventions:
0.x Delineation (floor 1). Leading 0 is notation, not a key.
100 Accumulation (floor 3). Digit 1 at top level, zeros = no branch taken.
001.1 Floor 3. Two zeros walk underscore chain to floor, then digits below.
Digit 0 always maps to key '_' — walking the underscore spine.
"""
import json, sys, os
def floor_depth(block):
"""Follow the underscore chain until a string. Count = floor."""
node = block
depth = 0
while isinstance(node, dict) and '_' in node:
depth += 1
node = node['_']
if isinstance(node, str):
return depth
return depth
def parse_address(number):
"""Parse a pscale number into a list of digit characters to walk.
Leading 0 before decimal is notation (delineation marker), not a key."""
s = f'{number:.10f}' if isinstance(number, (int, float)) else str(number)
parts = s.split('.')
integer = parts[0] or '0'
frac = (parts[1] if len(parts) > 1 else '').rstrip('0')
if integer == '0':
return list(frac)
return list(integer + frac)
def walk(block, digits):
"""Walk the tree collecting texts. Digit 0 maps to key '_'.
Returns (chain, terminal_node, parent_node, terminal_key)
where chain is list of {'text': str, 'depth': int}."""
chain = []
node = block
parent = None
last_key = None
depth = 0
# Collect root text: follow underscore chain to the floor string.
# Floor 1: root._ is the string directly.
# Floor N: root._._._ ... N deep to hit the string.
if isinstance(node, dict) and '_' in node:
inner = node['_']
while isinstance(inner, dict) and '_' in inner:
inner = inner['_']
if isinstance(inner, str):
chain.append({'text': inner, 'depth': depth})
for d in digits:
key = '_' if d == '0' else d
if not isinstance(node, dict) or key not in node:
break
target = node[key]
# Walking '0' into a string '_' means we've hit the floor spine —
# this text was already collected when we arrived at this node.
if d == '0' and isinstance(target, str):
break
parent = node
last_key = key
node = target
depth += 1
if isinstance(node, str):
chain.append({'text': node, 'depth': depth})
break
elif isinstance(node, dict) and isinstance(node.get('_'), str):
chain.append({'text': node['_'], 'depth': depth})
return chain, node, parent, last_key
def bsp(block, number=None, point=None, mode=None):
"""Pure-form BSP. Block is the tree — no wrapper."""
fl = floor_depth(block)
# Dir (full) — no args
if number is None and point is None and mode is None:
return {'mode': 'dir', 'tree': block}
# Disc — bsp(block, None, depth, 'disc')
if mode == 'disc' and point is not None:
target = int(point) if isinstance(point, str) else point
nodes = []
def collect(node, depth, path):
if depth == target:
if isinstance(node, str):
text = node
elif isinstance(node, dict):
# Resolve underscore chain to floor string
inner = node.get('_')
while isinstance(inner, dict) and '_' in inner:
inner = inner['_']
text = inner if isinstance(inner, str) else None
else:
text = None
nodes.append({'path': path, 'text': text})
return
if not isinstance(node, dict):
return
# Walk both underscore and digit children
if '_' in node and isinstance(node['_'], dict):
collect(node['_'], depth + 1, f'{path}.0' if path else '0')
for d in '123456789':
if d in node:
collect(node[d], depth + 1, f'{path}.{d}' if path else d)
collect(block, 0, '')
return {'mode': 'disc', 'depth': target, 'nodes': nodes}
# Parse address and walk
digits = parse_address(number)
chain, terminal, parent, last_key = walk(block, digits)
# Ring — siblings at terminal
if point == 'ring':
if parent is None or not isinstance(parent, dict):
return {'mode': 'ring', 'siblings': []}
siblings = []
# Include '_' as a navigable sibling (digit 0) if it's an object
if last_key != '_' and '_' in parent and isinstance(parent['_'], dict):
v = parent['_']
text = v.get('_') if isinstance(v, dict) else (v if isinstance(v, str) else None)
# Resolve nested underscore objects to their eventual string
inner = v
while isinstance(inner, dict) and '_' in inner and isinstance(inner['_'], dict):
inner = inner['_']
if isinstance(inner, dict) and isinstance(inner.get('_'), str):
text = inner['_']
siblings.append({'digit': '0', 'text': text, 'branch': True})
for d in '123456789':
if d == last_key or d not in parent:
continue
v = parent[d]
text = v if isinstance(v, str) else (v.get('_') if isinstance(v, dict) else None)
siblings.append({'digit': d, 'text': text, 'branch': isinstance(v, dict)})
return {'mode': 'ring', 'siblings': siblings}
# Dir (subtree)
if point == 'dir':
return {'mode': 'dir', 'subtree': terminal}
# Annotate chain with pscale: pscale = (floor - 1) - depth
def pscale_at(depth):
return (fl - 1) - depth
# Point — content at a specific pscale
if mode == 'point' and point is not None:
ps = int(point) if isinstance(point, str) else point
for entry in chain:
if pscale_at(entry['depth']) == ps:
return {'mode': 'point', 'pscale': ps, 'text': entry['text']}
last = chain[-1] if chain else None
return {'mode': 'point', 'pscale': ps, 'text': last['text'] if last else None}
# Spindle (default) — annotate with pscale
nodes = []
for entry in chain:
nodes.append({'pscale': pscale_at(entry['depth']), 'text': entry['text']})
return {'mode': 'spindle', 'nodes': nodes}
# ---- CLI ----
def fmt_spindle(r):
return '\n'.join(f" [{n['pscale']:>3}] {n['text'][:200]}{'...' if len(n['text']) > 200 else ''}" for n in r['nodes'])
def fmt_ring(r):
if not r.get('siblings'):
return ' (no siblings)'
return '\n'.join(f" {s['digit']}: {(s.get('text') or '(branch)')[:120]}{'...' if len(s.get('text','')) > 120 else ''}{' +' if s.get('branch') else ''}" for s in r['siblings'])
def fmt_disc(r):
if not r.get('nodes'):
return ' (no nodes at this depth)'
return '\n'.join(f" [{n['path']}] {(n.get('text') or '(no text)')[:150]}" for n in r['nodes'])
def fmt_dir(r):
tree = r.get('subtree') or r.get('tree', {})
if 'subtree' in r:
return json.dumps(tree, indent=2, ensure_ascii=False)
lines = []
def show_underscore(node, prefix=''):
"""Show underscore chain for floor > 1 blocks."""
if isinstance(node, str):
return node
if isinstance(node, dict):
inner = node.get('_')
if isinstance(inner, str):
return inner
if isinstance(inner, dict):
return f"(floor chain) → {show_underscore(inner)}"
return str(node)
root = tree.get('_', '')
if isinstance(root, str) and root:
lines.append(f" _: {root[:200]}{'...' if len(root) > 200 else ''}")
elif isinstance(root, dict):
lines.append(f" _: {show_underscore(root)[:200]}")
for k in sorted(k for k in tree if k != '_'):
v = tree[k]
text = v if isinstance(v, str) else (v.get('_', '(branch)') if isinstance(v, dict) else str(v))
lines.append(f" {k}: {text[:120]}{'...' if len(text) > 120 else ''}")
return '\n'.join(lines)
def main():
if len(sys.argv) < 2:
print("Usage: python tidy-up/bsp.py <block> [number|_] [ring|dir|pscale] [point|disc]")
sys.exit(1)
script_dir = os.path.dirname(os.path.abspath(__file__))
block_name = sys.argv[1]
path = os.path.join(script_dir, f'{block_name}.json')
if not os.path.exists(path):
print(f"Block not found: {path}")
sys.exit(1)
with open(path) as f:
block = json.load(f)
args = sys.argv[2:]
number = None
point = None
mode = None
if args:
if args[0] == '_':
number = None
else:
try:
number = float(args[0])
except ValueError:
print(f"Invalid number: {args[0]}")
sys.exit(1)
if len(args) > 1:
a = args[1]
if a in ('ring', 'dir'):
point = a
elif a == 'disc':
mode = 'disc'
else:
try:
point = int(a)
except ValueError:
point = a
if len(args) > 2:
a = args[2]
if a in ('point', 'disc'):
mode = a
result = bsp(block, number, point, mode)
m = result.get('mode')
if m == 'spindle':
print(f"[{block_name} {number}] spindle")
print(fmt_spindle(result))
elif m == 'ring':
print(f"[{block_name} {number} ring]")
print(fmt_ring(result))
elif m == 'dir':
label = f"{block_name} {number} dir" if number else f"{block_name} dir"
print(f"[{label}]")
print(fmt_dir(result))
elif m == 'point':
print(f"[{block_name} {number} point @ pscale {result.get('pscale')}]")
print(f" {result.get('text')}")
elif m == 'disc':
print(f"[{block_name} disc @ depth {result.get('depth')}]")
print(fmt_disc(result))
else:
print(json.dumps(result, indent=2))
if __name__ == '__main__':
main()