-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrain_singularity.py
More file actions
429 lines (346 loc) Β· 15.9 KB
/
brain_singularity.py
File metadata and controls
429 lines (346 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/env python3
"""Brain Atypical Structure Statistical Simulator - Statistical Singularity Detection"""
import argparse
import os
from datetime import datetime
import numpy as np
from scipy import stats
from scipy.signal import argrelextrema
RESULTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "results")
LOG_FILE = os.path.join(RESULTS_DIR, "log.md")
SINGULARITY_FILE = os.path.join(RESULTS_DIR, "singularities.md")
def genius_score(deficit, plasticity, inhibition):
"""Genius = Deficit Γ Plasticity / Inhibition"""
return deficit * plasticity / inhibition
def simulate_population(n_samples, seed=42):
"""Generate population based on normal distribution"""
rng = np.random.default_rng(seed)
deficits = rng.beta(2, 5, n_samples).clip(0.01, 0.99)
plasticities = rng.beta(5, 2, n_samples).clip(0.01, 0.99)
inhibitions = rng.beta(5, 2, n_samples).clip(0.05, 0.99)
scores = genius_score(deficits, plasticities, inhibitions)
return scores
def find_critical_points(n_points=1000):
"""Deficit continuous change β critical point (2nd derivative peak) detection"""
deficits = np.linspace(0.01, 0.99, n_points)
plasticity_mean = 0.7
inhibition_base = 0.8
inhibitions = inhibition_base * np.exp(-3 * deficits**2)
scores = genius_score(deficits, plasticity_mean, inhibitions)
d1 = np.gradient(scores, deficits)
d2 = np.gradient(d1, deficits)
peaks = argrelextrema(np.abs(d2), np.greater, order=20)[0]
return deficits, scores, d2, peaks
def ascii_chart(deficits, scores, user_deficit, user_score, critical_indices, width=60, height=20):
"""Terminal ASCII chart"""
min_s, max_s = scores.min(), scores.max()
if max_s == min_s:
max_s = min_s + 1
chart = [[' ' for _ in range(width)] for _ in range(height)]
for i in range(width):
idx = int(i / width * len(scores))
y = int((scores[idx] - min_s) / (max_s - min_s) * (height - 1))
y = height - 1 - y
chart[y][i] = 'Β·'
for ci in critical_indices:
x = int(ci / len(deficits) * width)
x = min(x, width - 1)
for row in range(height):
if chart[row][x] == ' ':
chart[row][x] = 'β'
ux = int(user_deficit / 0.99 * (width - 1))
ux = min(ux, width - 1)
uy = int((user_score - min_s) / (max_s - min_s) * (height - 1))
uy = height - 1 - uy
uy = max(0, min(uy, height - 1))
chart[uy][ux] = 'β
'
lines = []
for i, row in enumerate(chart):
if i == 0:
label = f" {max_s:6.2f} β€"
elif i == height - 1:
label = f" {min_s:6.2f} β€"
elif i == height // 2:
mid = (max_s + min_s) / 2
label = f" {mid:6.2f} β€"
else:
label = " β"
lines.append(label + ''.join(row))
lines.append(" β" + "β" * width)
lines.append(f" Deficit: 0.0{' ' * (width - 10)}1.0")
lines.append("")
lines.append(" Β· Ability Curve β Critical Point β
Input Value Position")
return '\n'.join(lines)
def ensure_results_dir():
os.makedirs(RESULTS_DIR, exist_ok=True)
if not os.path.exists(LOG_FILE):
with open(LOG_FILE, 'w', encoding='utf-8') as f:
f.write("# Simulation Log\n\n")
f.write("All execution results are accumulated in chronological order.\n\n")
f.write("---\n\n")
if not os.path.exists(SINGULARITY_FILE):
with open(SINGULARITY_FILE, 'w', encoding='utf-8') as f:
f.write("# β‘ Statistical Singularity Log\n\n")
f.write("Only singularities with Z-Score > 2.0Ο are recorded separately.\n\n")
f.write("---\n\n")
def append_to_log(d, p, i, score, z, percentile, phase, phase_icon, crit_low, crit_high, is_singular, chart_text, pop_mean, pop_std, n_samples):
"""Append each execution result to log.md"""
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
singular_tag = " `β‘ Singularity`" if is_singular else ""
entry = f"""## [{now}]{singular_tag}
| Parameter | Value |
|---|---|
| Deficit | {d:.2f} |
| Plasticity | {p:.2f} |
| Inhibition | {i:.2f} |
| Result | Value |
|---|---|
| Genius Score | {score:.2f} |
| Z-Score | {z:.2f}Ο |
| Percentile | Top {percentile:.2f}% |
| Phase | {phase_icon} {phase} |
| Critical Point Range | Deficit {crit_low:.2f} ~ {crit_high:.2f} |
<details>
<summary>Ability Curve</summary>
```
{chart_text}
```
</details>
Population: n={n_samples:,} / Mean={pop_mean:.2f} / Ο={pop_std:.2f}
---
"""
with open(LOG_FILE, 'a', encoding='utf-8') as f:
f.write(entry)
def append_to_singularities(d, p, i, score, z, percentile, phase):
"""Record singularities separately in singularities.md"""
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Singularity grade determination
if abs(z) > 5:
grade = "π΄ Extreme Singularity"
elif abs(z) > 3:
grade = "π Strong Singularity"
else:
grade = "π‘ Singularity"
entry = f"""## {grade} [{now}]
- **Genius Score: {score:.2f}** | **Z-Score: {z:.2f}Ο** | Top {percentile:.4f}%
- Deficit={d:.2f} / Plasticity={p:.2f} / Inhibition={i:.2f}
- Phase: {phase}
---
"""
with open(SINGULARITY_FILE, 'a', encoding='utf-8') as f:
f.write(entry)
def run_single(d, p, i, pop_scores, curve_d, curve_s, critical_idx, crit_low, crit_high, verbose=True):
"""Single parameter analysis + recording. Returns result dict."""
score = genius_score(d, p, i)
z = (score - pop_scores.mean()) / pop_scores.std()
percentile = (1 - stats.norm.cdf(z)) * 100
if d < crit_low:
phase = "Normal Range (Insufficient Compensation Motivation)"
phase_icon = "β"
elif d > crit_high + 0.1:
phase = "Excessive Deficit (Beyond Compensation Limit)"
phase_icon = "βΌ"
else:
phase = "Within Critical Point (Compensatory Genius Zone)"
phase_icon = "β‘"
is_singular = abs(z) > 2.0
if verbose:
chart_text = ascii_chart(curve_d, curve_s, d, score, critical_idx)
print()
print("β" * 50)
print(" Brain Atypical Structure Singularity Analysis")
print("β" * 50)
print()
print(f" Input Parameters:")
print(f" Deficit = {d:.2f}")
print(f" Plasticity = {p:.2f}")
print(f" Inhibition = {i:.2f}")
print()
print("β" * 50)
print(f" Genius Score: {score:.2f}")
print(f" Z-Score: {z:.2f}Ο {'β‘ Statistical Singularity!' if is_singular else 'β Normal Range'}")
print(f" Percentile: Top {percentile:.2f}%")
print("β" * 50)
print(f" Critical Point Range: Deficit {crit_low:.2f} ~ {crit_high:.2f}")
print(f" Phase Determination: {phase_icon} {phase}")
print("β" * 50)
print()
print(" [ Ability Curve (Deficit vs Genius Score) ]")
print()
print(chart_text)
print()
print("β" * 50)
print(f" Population Statistics (n={len(pop_scores):,})")
print(f" Mean: {pop_scores.mean():.2f}")
print(f" Standard Deviation: {pop_scores.std():.2f}")
print(f" Min/Max: {pop_scores.min():.2f} / {pop_scores.max():.2f}")
print("β" * 50)
append_to_log(d, p, i, score, z, percentile, phase, phase_icon,
crit_low, crit_high, is_singular, chart_text,
pop_scores.mean(), pop_scores.std(), len(pop_scores))
return {
'd': d, 'p': p, 'i': i,
'score': score, 'z': z, 'percentile': percentile,
'phase': phase, 'phase_icon': phase_icon,
'is_singular': is_singular,
}
def run_grid_scan(d_steps, p_steps, i_steps, n_samples):
"""3D parameter grid scan"""
deficits = np.linspace(0.05, 0.95, d_steps)
plasticities = np.linspace(0.1, 0.95, p_steps)
inhibitions = np.linspace(0.05, 0.95, i_steps)
total = d_steps * p_steps * i_steps
print()
print("β" * 60)
print(" Mass Grid Scan")
print("β" * 60)
print(f" D: {d_steps} steps Γ P: {p_steps} steps Γ I: {i_steps} steps = {total:,} combinations")
print(f" Population Sample: {n_samples:,}")
print("β" * 60)
pop_scores = simulate_population(n_samples)
pop_mean = pop_scores.mean()
pop_std = pop_scores.std()
curve_d, curve_s, d2, critical_idx = find_critical_points()
if len(critical_idx) > 0:
crit_low = curve_d[critical_idx[0]]
crit_high = curve_d[critical_idx[-1]] if len(critical_idx) > 1 else crit_low + 0.15
else:
crit_low, crit_high = 0.5, 0.7
# Calculate entire grid at once with vectorized operations
D, P, I = np.meshgrid(deficits, plasticities, inhibitions, indexing='ij')
scores = genius_score(D, P, I)
z_scores = (scores - pop_mean) / pop_std
# Singularity mask
singular_mask = np.abs(z_scores) > 2.0
n_singular = singular_mask.sum()
n_strong = (np.abs(z_scores) > 3.0).sum()
n_extreme = (np.abs(z_scores) > 5.0).sum()
print(f"\n Scan Complete!")
print(f" βββββββββββββββββββββββββββββββββ")
print(f" Total Combinations: {total:>8,}")
print(f" π‘ Singularities (>2Ο): {n_singular:>8,} ({n_singular/total*100:.1f}%)")
print(f" π Strong (>3Ο): {n_strong:>8,} ({n_strong/total*100:.1f}%)")
print(f" π΄ Extreme (>5Ο): {n_extreme:>8,} ({n_extreme/total*100:.1f}%)")
print(f" βββββββββββββββββββββββββββββββββ")
# Singularity boundary analysis: threshold values per axis
print(f"\n [ Singularity Boundary Analysis ]")
print()
# Deficit axis: singularity ratio change
print(f" Singularity Ratio by Deficit:")
for di, dv in enumerate(deficits):
slice_singular = singular_mask[di, :, :].sum()
slice_total = p_steps * i_steps
ratio = slice_singular / slice_total * 100
bar = "β" * int(ratio / 2) + "β" * (50 - int(ratio / 2))
print(f" D={dv:.2f} β{bar}β {ratio:5.1f}%")
# Inhibition axis: singularity ratio change
print(f"\n Singularity Ratio by Inhibition:")
for ii, iv in enumerate(inhibitions):
slice_singular = singular_mask[:, :, ii].sum()
slice_total = d_steps * p_steps
ratio = slice_singular / slice_total * 100
bar = "β" * int(ratio / 2) + "β" * (50 - int(ratio / 2))
print(f" I={iv:.2f} β{bar}β {ratio:5.1f}%")
# Top 10 singularities
print(f"\n [ Top 10 Extreme Singularities ]")
print(f" {'Rank':>4} β {'Deficit':>7} β {'Plastic':>7} β {'Inhibit':>7} β {'Score':>8} β {'Z-Score':>8} β Grade")
print(f" {'β'*4}ββΌβ{'β'*7}ββΌβ{'β'*7}ββΌβ{'β'*7}ββΌβ{'β'*8}ββΌβ{'β'*8}ββΌβ{'β'*10}")
flat_idx = np.argsort(z_scores.ravel())[::-1][:10]
for rank, fi in enumerate(flat_idx, 1):
di, pi, ii = np.unravel_index(fi, z_scores.shape)
dv, pv, iv = deficits[di], plasticities[pi], inhibitions[ii]
sv = scores[di, pi, ii]
zv = z_scores[di, pi, ii]
if abs(zv) > 5:
grade = "π΄ Extreme"
elif abs(zv) > 3:
grade = "π Strong"
else:
grade = "π‘"
print(f" {rank:>4} β {dv:>7.2f} β {pv:>7.2f} β {iv:>7.2f} β {sv:>8.2f} β {zv:>7.2f}Ο β {grade}")
print()
print("β" * 60)
# Save results to scan_report.md
ensure_results_dir()
scan_file = os.path.join(RESULTS_DIR, "scan_report.md")
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(scan_file, 'a', encoding='utf-8') as f:
f.write(f"# Grid Scan Report [{now}]\n\n")
f.write(f"- Grid: D={d_steps} Γ P={p_steps} Γ I={i_steps} = **{total:,}** combinations\n")
f.write(f"- Population: n={n_samples:,} / Mean={pop_mean:.2f} / Ο={pop_std:.2f}\n\n")
f.write(f"## Singularity Statistics\n\n")
f.write(f"| Grade | Criterion | Count | Ratio |\n")
f.write(f"|---|---|---|---|\n")
f.write(f"| π‘ Singularity | >2Ο | {n_singular:,} | {n_singular/total*100:.1f}% |\n")
f.write(f"| π Strong Singularity | >3Ο | {n_strong:,} | {n_strong/total*100:.1f}% |\n")
f.write(f"| π΄ Extreme Singularity | >5Ο | {n_extreme:,} | {n_extreme/total*100:.1f}% |\n\n")
f.write(f"## Top 10 Extreme Singularities\n\n")
f.write(f"| Rank | Deficit | Plasticity | Inhibition | Score | Z-Score | Grade |\n")
f.write(f"|---|---|---|---|---|---|---|\n")
for rank, fi in enumerate(flat_idx, 1):
di, pi, ii = np.unravel_index(fi, z_scores.shape)
dv, pv, iv = deficits[di], plasticities[pi], inhibitions[ii]
sv = scores[di, pi, ii]
zv = z_scores[di, pi, ii]
grade = "π΄" if abs(zv) > 5 else ("π " if abs(zv) > 3 else "π‘")
f.write(f"| {rank} | {dv:.2f} | {pv:.2f} | {iv:.2f} | {sv:.2f} | {zv:.2f}Ο | {grade} |\n")
f.write(f"\n## Singularity Ratio by Deficit\n\n")
f.write(f"| Deficit | Singularity Count | Ratio |\n")
f.write(f"|---|---|---|\n")
for di, dv in enumerate(deficits):
cnt = singular_mask[di, :, :].sum()
f.write(f"| {dv:.2f} | {cnt} | {cnt/(p_steps*i_steps)*100:.1f}% |\n")
f.write(f"\n## Singularity Ratio by Inhibition\n\n")
f.write(f"| Inhibition | Singularity Count | Ratio |\n")
f.write(f"|---|---|---|\n")
for ii, iv in enumerate(inhibitions):
cnt = singular_mask[:, :, ii].sum()
f.write(f"| {iv:.2f} | {cnt} | {cnt/(d_steps*p_steps)*100:.1f}% |\n")
f.write(f"\n---\n\n")
print(f" π Scan Report β results/scan_report.md")
print()
# Also record singularities in singularities.md (Top 10 only)
for fi in flat_idx:
di, pi, ii = np.unravel_index(fi, z_scores.shape)
dv, pv, iv = deficits[di], plasticities[pi], inhibitions[ii]
sv = scores[di, pi, ii]
zv = z_scores[di, pi, ii]
pctile = (1 - stats.norm.cdf(zv)) * 100
if dv < crit_low:
phase = "Normal Range"
elif dv > crit_high + 0.1:
phase = "Excessive Deficit"
else:
phase = "Within Critical Point"
append_to_singularities(dv, pv, iv, sv, zv, pctile, phase)
def main():
parser = argparse.ArgumentParser(description="Brain Atypical Structure Statistical Simulator")
parser.add_argument('--deficit', type=float, default=0.7, help="Structural deficit degree (0.0~1.0)")
parser.add_argument('--plasticity', type=float, default=0.8, help="Neuroplasticity coefficient (0.0~1.0)")
parser.add_argument('--inhibition', type=float, default=0.15, help="Frontal lobe inhibition level (0.01~1.0)")
parser.add_argument('--samples', type=int, default=10000, help="Simulation sample count")
parser.add_argument('--scan', action='store_true', help="Grid scan mode")
parser.add_argument('--grid', type=int, default=20, help="Grid resolution (steps per axis, default 20)")
args = parser.parse_args()
ensure_results_dir()
if args.scan:
run_grid_scan(args.grid, args.grid, args.grid, args.samples)
return
d = np.clip(args.deficit, 0.0, 1.0)
p = np.clip(args.plasticity, 0.0, 1.0)
i = np.clip(args.inhibition, 0.01, 1.0)
pop_scores = simulate_population(args.samples)
curve_d, curve_s, d2, critical_idx = find_critical_points()
if len(critical_idx) > 0:
crit_low = curve_d[critical_idx[0]]
crit_high = curve_d[critical_idx[-1]] if len(critical_idx) > 1 else crit_low + 0.15
else:
crit_low, crit_high = 0.5, 0.7
result = run_single(d, p, i, pop_scores, curve_d, curve_s, critical_idx, crit_low, crit_high)
if result['is_singular']:
append_to_singularities(d, p, i, result['score'], result['z'], result['percentile'], result['phase'])
print(f"\n π Singularity Record β results/singularities.md")
print(f" π Full Log β results/log.md")
print()
if __name__ == '__main__':
main()