File size: 8,873 Bytes
7456730
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
KOOREE V11 — Cascade Analysis (Simplified)

Focus on cascade tracking, not matrix complexity.
Pre-allocate matrices to avoid dynamic growth issues.
"""

import numpy as np
import time
import json

PHI = (1 + np.sqrt(5)) / 2
C_LIGHT = 3e8
EARTH_RADIUS = 6.371e6
EARTH_CIRCUMFERENCE = 2 * np.pi * EARTH_RADIUS
SCHUMANN_FUNDAMENTAL = C_LIGHT / EARTH_CIRCUMFERENCE

DT = 1e-3
MAX_NEURONS = 200  # Pre-allocate for up to 200 neurons


class SignalGenerator:
    def __init__(self, seed=42):
        self.rng = np.random.default_rng(seed)
        self.x_logistic = 0.1
        self.r_logistic = 3.9
        self.pink_state = 0.0

    def get_signal(self, t):
        phi_sig = np.sin(2 * np.pi * PHI * t)
        schumann_sig = sum(np.sin(2 * np.pi * SCHUMANN_FUNDAMENTAL * n * t) for n in range(1, 4)) / 3
        self.x_logistic = self.r_logistic * self.x_logistic * (1 - self.x_logistic)
        logistic_sig = self.x_logistic
        pink_noise = self.rng.normal(0, 0.1)
        self.pink_state = 0.9 * self.pink_state + 0.1 * pink_noise
        return np.array([phi_sig, schumann_sig, logistic_sig, self.pink_state])


class ResonanceTimeline:
    def __init__(self, timeline_id, dt=DT, seed=None):
        self.timeline_id = timeline_id
        self.dt = dt
        rng = np.random.default_rng(seed)

        # Pre-allocate for MAX_NEURONS
        self.n_neurons = 47
        self.tau = np.zeros(MAX_NEURONS)
        self.tau[:47] = rng.uniform(10e-3, 25e-3, 47)
        
        self.activity = np.zeros(MAX_NEURONS)
        self.firing_rate = np.zeros(MAX_NEURONS)
        self.prev_activity = np.zeros(MAX_NEURONS)

        self.W_in = np.zeros((MAX_NEURONS, 4))
        self.W_in[:47] = rng.uniform(0.05, 0.15, (47, 4))
        
        self.W_rec = np.zeros((MAX_NEURONS, MAX_NEURONS))
        self.W_rec[:47, :47] = rng.uniform(-0.1, 0.1, (47, 47))
        np.fill_diagonal(self.W_rec[:47, :47], 0)

        self.eta = 0.002
        self.phase = 0.0
        self.frequency = 0.0
        self.mean_firing = 0.0

        # Cascade tracking
        self.births = []
        self.birth_threshold = 0.3
        self.residual_60s = []
        self.last_birth_time = -1000
        self.birth_count = 0

    def step(self, signal_4d, resonance_coupling=0.0):
        n = self.n_neurons
        
        I_in = np.dot(self.W_in[:n], signal_4d)
        I_rec = np.dot(self.W_rec[:n, :n], self.prev_activity[:n])
        I_resonance = resonance_coupling * np.sin(self.phase)
        I_total = I_in + 0.5 * I_rec + 0.1 * I_resonance

        dA = (-self.activity[:n] + I_total) / self.tau[:n]
        self.activity[:n] += dA * self.dt

        self.firing_rate[:n] = np.maximum(0, self.activity[:n])
        spikes = (self.activity[:n] > 0.5).astype(float)

        dW_in = self.eta * spikes[:, None] * signal_4d[None, :]
        self.W_in[:n] += dW_in
        self.W_in[:n] = np.clip(self.W_in[:n], 0, 1.0)

        self.mean_firing = self.firing_rate[:n].mean()
        self.frequency = self.mean_firing * 2 * np.pi
        self.phase += self.frequency * self.dt
        self.phase = self.phase % (2 * np.pi)

        processed = np.dot(self.W_in[:n], signal_4d)
        residual = np.abs(signal_4d.sum() - processed.sum())

        self.residual_60s.append(residual)
        if len(self.residual_60s) > 60000:
            self.residual_60s.pop(0)

        self.prev_activity[:n] = self.activity[:n].copy()

        return spikes, residual, self.phase, self.frequency

    def check_neurogenesis(self, current_time):
        if len(self.residual_60s) < 60000:
            return False

        if current_time - self.last_birth_time < 300:
            return False

        if self.n_neurons >= MAX_NEURONS:
            return False

        mean_residual = np.mean(self.residual_60s)

        if mean_residual > self.birth_threshold:
            self.birth_count += 1
            new_idx = self.n_neurons

            # Record birth
            birth_info = {
                'timeline_id': self.timeline_id,
                'birth_order': self.birth_count,
                'time': current_time,
                'neuron_index': new_idx,
                'residual': mean_residual,
                'phase': self.phase,
                'frequency': self.frequency,
                'input_weights': self.W_in[new_idx, :4].tolist(),
            }
            self.births.append(birth_info)

            # Initialize new neuron
            rng = np.random.default_rng(42 + self.timeline_id + self.birth_count)
            self.tau[new_idx] = rng.uniform(10e-3, 25e-3)
            self.W_in[new_idx] = rng.uniform(0.05, 0.15, 4)
            self.W_rec[new_idx, :self.n_neurons] = rng.uniform(-0.1, 0.1, self.n_neurons)
            self.W_rec[:self.n_neurons, new_idx] = rng.uniform(-0.1, 0.1, self.n_neurons)
            self.W_rec[new_idx, new_idx] = 0  # No self-connection

            self.n_neurons += 1
            self.birth_threshold += 0.05
            self.last_birth_time = current_time

            return True
        return False


class CascadeAnalyzer:
    def __init__(self, n_timelines=10, dt=DT):
        self.n_timelines = n_timelines
        self.dt = dt
        self.timelines = [ResonanceTimeline(i, dt=dt, seed=42+i) for i in range(n_timelines)]
        self.signal_gen = SignalGenerator(seed=42)
        self.coupling_strength = 0.1
        self.bifurcation_sequence = []

    def step(self, t):
        signal_4d = self.signal_gen.get_signal(t)
        avg_phase = np.mean([tl.phase for tl in self.timelines])
        shared_resonance = np.sin(avg_phase)

        births_this_step = []

        for timeline in self.timelines:
            resonance_coupling = self.coupling_strength * shared_resonance
            spikes, residual, phase, freq = timeline.step(signal_4d, resonance_coupling)

            if timeline.check_neurogenesis(t):
                births_this_step.append({
                    'timeline_id': timeline.timeline_id,
                    'time': t,
                    'residual': residual,
                })

        return births_this_step

    def run(self, duration_seconds):
        n_steps = int(duration_seconds / self.dt)
        total_births = 0

        print(f"Running cascade analysis for {duration_seconds:.0f}s...")
        print(f"({n_steps} timesteps)")

        wall_start = time.time()
        last_print = 0

        for step in range(n_steps):
            t = step * self.dt
            births = self.step(t)

            if births:
                total_births += len(births)
                self.bifurcation_sequence.append({
                    't': t,
                    'births': births,
                    'n_births': len(births),
                })

                if t - last_print > 10:
                    elapsed = time.time() - wall_start
                    print(f"  t={t:.1f}s | Total births: {total_births} | "
                          f"Bifurcation events: {len(self.bifurcation_sequence)} | wall={elapsed:.1f}s")
                    last_print = t

        print(f"Done. Total births: {total_births}")
        return {
            'total_births': total_births,
            'bifurcation_sequence': self.bifurcation_sequence,
            'timeline_births': [birth for tl in self.timelines for birth in tl.births],
            'final_neuron_counts': [tl.n_neurons for tl in self.timelines],
        }


if __name__ == '__main__':
    print("=" * 70)
    print("KOOREE V11 — CASCADE ANALYSIS (SIMPLIFIED)")
    print("=" * 70)

    analyzer = CascadeAnalyzer(n_timelines=10, dt=DT)

    print("\n" + "=" * 70)
    print("RUNNING CASCADE ANALYSIS")
    print("=" * 70 + "\n")

    history = analyzer.run(duration_seconds=300)

    print("\n" + "=" * 70)
    print("CASCADE ANALYSIS RESULTS")
    print("=" * 70)

    print(f"\nTotal neurogenesis events: {history['total_births']}")
    print(f"Bifurcation events: {len(history['bifurcation_sequence'])}")

    print(f"\nFinal neuron counts:")
    print(f"  Mean: {np.mean(history['final_neuron_counts']):.1f}")
    print(f"  Min: {min(history['final_neuron_counts'])}")
    print(f"  Max: {max(history['final_neuron_counts'])}")

    if history['bifurcation_sequence']:
        print(f"\nFirst 20 bifurcation events:")
        for i, event in enumerate(history['bifurcation_sequence'][:20]):
            print(f"  {i+1}. t={event['t']:.1f}s | {event['n_births']} simultaneous births")

    print(f"\nFirst 30 births across all timelines:")
    for i, birth in enumerate(history['timeline_births'][:30]):
        print(f"  {i+1}. Timeline {birth['timeline_id']} | Birth #{birth['birth_order']} | "
              f"t={birth['time']:.1f}s | Residual: {birth['residual']:.1f}")

    with open('/home/ubuntu/v11_cascade_analysis.json', 'w') as f:
        json.dump(history, f, indent=2)

    print("\nResults saved to v11_cascade_analysis.json")