import numpy as np from scipy.integrate import solve_ivp class UDPModel: """ Recursive Universal Derivative Principle model. Features -------- - Third-order closure of the Cognitive Inertial Field (CIF) - Derivative hierarchy: awareness, emotion, affectance - Integrative duals: knowledge, learning, insight manifold - Admissible insight detection using: * threshold crossing (Theta) * collapse rate (Xi) * energy release (Lambda) * coherence functional (kappa) - Recursive reorganisation: validated insight feeds into K_n and updates CIF state - Multiple insight events over one simulation """ def __init__( self, k0=1.0, k1=0.3, k2=0.8, k3=0.3, mu=0.1, rho=0.05, gamma=0.2, delta=0.01, dt=0.01, T=20.0, tau=0.5, theta=0.2, # Θ collapse_threshold=0.01, # Ξ energy_release_threshold=0.05, # Λ coherence_threshold=0.85, # κ coherence_window=0.4, gamma_overflow=0.25, overflow_min_duration=0.2, insight_refractory=2.0, min_insight_dwell=0.3, prepressure_window=0.5, eta_insight_to_kn=0.25, # η_I alpha_cf=0.20, # α beta_dcf=0.08, # β₁ beta_ddcf=0.03, # β₂ coherence_weights=(0.6, 0.2, 0.2), seed=42, ): # Gains / damping self.k0 = k0 self.k1 = k1 self.k2 = k2 self.k3 = max(k3, 1e-6) self.mu = mu self.rho = rho self.gamma = gamma self.delta = delta # Time self.dt = dt self.T = T self.t = np.arange(0, T, dt) self.n = len(self.t) # Thresholds self.tau = tau self.theta = theta self.collapse_threshold = collapse_threshold self.energy_release_threshold = energy_release_threshold self.coherence_threshold = coherence_threshold # Regime settings self.gamma_overflow = gamma_overflow self.overflow_min_duration = overflow_min_duration self.insight_refractory = insight_refractory self.min_insight_dwell = min_insight_dwell self.prepressure_window = prepressure_window self.coherence_window = coherence_window # Reorganisation parameters self.eta_insight_to_kn = eta_insight_to_kn self.alpha_cf = alpha_cf self.beta_dcf = beta_dcf self.beta_ddcf = beta_ddcf # Coherence weights self.w_af, self.w_aw, self.w_em = coherence_weights # RNG self.rng = np.random.default_rng(seed) self.seed = seed # State arrays self.reset() # ------------------------------------------------------------------ # Reset # ------------------------------------------------------------------ def reset(self): n = self.n # Field state self.CF = np.zeros(n) self.dCF = np.zeros(n) self.ddCF = np.zeros(n) self.dddCF = np.zeros(n) # Derivative hierarchy self.Aw = np.zeros(n) self.Em = np.zeros(n) self.Af = np.zeros(n) # Integrative duals self.Kn = np.zeros(n) self.Ln = np.zeros(n) self.In = np.zeros(n) self.dIn = np.zeros(n) # Diagnostics self.pressure = np.zeros(n) self.dPressure = np.zeros(n) self.energy = np.zeros(n) self.dEnergy = np.zeros(n) self.coherence_trace = np.full(n, np.nan) # Input self.S = np.zeros(n) # Regime masks self.insight_mask = np.zeros(n, dtype=bool) self.insight_reconfigurations = np.zeros(n, dtype=bool) self.overflow_mask = np.zeros(n, dtype=bool) # Bookkeeping self.insight_event_indices = [] self.reorganisation_log = [] # ------------------------------------------------------------------ # Stimulus generation # ------------------------------------------------------------------ def build_stimulus( self, input_type="sine", input_freq=0.5, input_amp=1.0, noise=0.03, pulse_count=3, pulse_duty=0.2, ): n = self.n t = self.t if input_type == "sine": base = input_amp * np.sin(2 * np.pi * input_freq * t) elif input_type == "step": base = np.full_like(t, input_amp) elif input_type == "pulse": base = np.zeros_like(t) period = n / max(1, pulse_count) width = int(period * pulse_duty) for i in range(pulse_count): start = int(i * period) base[start:start + width] = input_amp elif input_type == "non-linear": base = np.cumsum(self.rng.standard_normal(n) * 0.05) base += input_amp * np.sin(2 * np.pi * input_freq * t) jumps = self.rng.random(n) < 0.02 base[jumps] += self.rng.standard_normal(jumps.sum()) * input_amp * 2 else: base = np.zeros_like(t) self.S = base + noise * self.rng.standard_normal(n) return self.S # ------------------------------------------------------------------ # Core closure # ------------------------------------------------------------------ def _closure(self, t, x): CF, dCF, ddCF = x idx = int(t / self.dt) idx = np.clip(idx, 0, self.n - 1) S = self.S[idx] dddCF = ( S - self.k0 * CF - self.k1 * dCF - self.k2 * ddCF ) / self.k3 return [dCF, ddCF, dddCF] # ------------------------------------------------------------------ # Segment simulation # ------------------------------------------------------------------ def _simulate_segment(self, start_idx, x0): """ Simulate from start_idx to end using current x0. """ if start_idx >= self.n - 1: return t_eval = self.t[start_idx:] sol = solve_ivp( self._closure, [float(t_eval[0]), float(t_eval[-1])], x0, t_eval=t_eval, method="RK45" ) self.CF[start_idx:] = sol.y[0] self.dCF[start_idx:] = sol.y[1] self.ddCF[start_idx:] = sol.y[2] self.dddCF[start_idx:] = ( self.S[start_idx:] - self.k0 * self.CF[start_idx:] - self.k1 * self.dCF[start_idx:] - self.k2 * self.ddCF[start_idx:] ) / self.k3 self.Aw[start_idx:] = self.k1 * self.dCF[start_idx:] self.Em[start_idx:] = self.k2 * self.ddCF[start_idx:] self.Af[start_idx:] = self.k3 * self.dddCF[start_idx:] # Recompute integrators globally for consistency self._recompute_integrators_and_diagnostics() # ------------------------------------------------------------------ # Integrators / diagnostics # ------------------------------------------------------------------ def _bounded_running_integral(self, signal, window_steps): kernel = np.ones(window_steps) * self.dt return np.convolve(signal, kernel, mode="same") def _recompute_integrators_and_diagnostics(self): self.Kn[:] = 0.0 self.Ln[:] = 0.0 for i in range(1, self.n): self.Kn[i] = self.Kn[i - 1] + self.dt * ( self.mu * (self.Aw[i] - self.rho * self.Kn[i - 1]) ) self.Ln[i] = self.Ln[i - 1] + self.dt * ( self.gamma * (self.Em[i] - self.delta * self.Ln[i - 1]) ) window_steps = max(3, int(self.tau / self.dt)) self.In[:] = self._bounded_running_integral(self.Af, window_steps) self.dIn[:] = np.gradient(np.abs(self.In), self.dt) self.pressure[:] = self._bounded_running_integral(np.abs(self.Af), window_steps) self.dPressure[:] = np.gradient(self.pressure, self.dt) self.energy[:] = self.CF**2 + self.dCF**2 + self.ddCF**2 self.dEnergy[:] = np.gradient(self.energy, self.dt) self.insight_mask[:] = np.abs(self.In) > self.theta # ------------------------------------------------------------------ # Energy / coherence # ------------------------------------------------------------------ def energy_drop(self, idx, window=0.25): steps = max(1, int(window / self.dt)) left = max(0, idx - steps) right = min(self.n - 1, idx + steps) # Negative = energy release return self.energy[right] - self.energy[left] def coherence(self, idx): """ Relative post-collapse coherence functional: Q(idx) = [w1 Var_post(Af) + w2 Var_post(Aw) + w3 Var_post(Em)] ----------------------------------------------------- [w1 Var_pre(Af) + w2 Var_pre(Aw) + w3 Var_pre(Em) + eps] """ steps = max(2, int(self.coherence_window / self.dt)) pre_left = max(0, idx - steps) pre_right = idx post_left = idx post_right = min(self.n, idx + steps) if (pre_right - pre_left) < 2 or (post_right - post_left) < 2: return np.inf pre_af = np.var(self.Af[pre_left:pre_right]) pre_aw = np.var(self.Aw[pre_left:pre_right]) pre_em = np.var(self.Em[pre_left:pre_right]) post_af = np.var(self.Af[post_left:post_right]) post_aw = np.var(self.Aw[post_left:post_right]) post_em = np.var(self.Em[post_left:post_right]) num = ( self.w_af * post_af + self.w_aw * post_aw + self.w_em * post_em ) den = ( self.w_af * pre_af + self.w_aw * pre_aw + self.w_em * pre_em + 1e-8 ) q = num / den self.coherence_trace[idx] = q return q def response_signal(self): """ Simple operational response measure: change in field velocity relative to signal magnitude. """ eps = 1e-8 return np.abs(self.dCF) / (np.abs(self.S) + eps) def dynamical_shift(self, idx): """ Compare pre/post variability of the CIF state around an event. """ steps = max(2, int(self.coherence_window / self.dt)) pre_left = max(0, idx - steps) pre_right = idx post_left = idx post_right = min(self.n, idx + steps) if (pre_right - pre_left) < 2 or (post_right - post_left) < 2: return 0.0 pre_var = ( np.var(self.CF[pre_left:pre_right]) + np.var(self.dCF[pre_left:pre_right]) + np.var(self.ddCF[pre_left:pre_right]) ) post_var = ( np.var(self.CF[post_left:post_right]) + np.var(self.dCF[post_left:post_right]) + np.var(self.ddCF[post_left:post_right]) ) return abs(post_var - pre_var) def response_shift(self, idx): """ Compare pre/post responsiveness to signal around an event. """ steps = max(2, int(self.coherence_window / self.dt)) pre_left = max(0, idx - steps) pre_right = idx post_left = idx post_right = min(self.n, idx + steps) if (pre_right - pre_left) < 2 or (post_right - post_left) < 2: return 0.0 response = self.response_signal() pre_resp = np.mean(response[pre_left:pre_right]) post_resp = np.mean(response[post_left:post_right]) return abs(post_resp - pre_resp) # ------------------------------------------------------------------ # Overflow # ------------------------------------------------------------------ def _compute_overflow_mask(self): high_af = np.abs(self.Af) > self.gamma_overflow subthreshold_in = np.abs(self.In) < self.theta candidate = high_af & subthreshold_in min_steps = max(1, int(self.overflow_min_duration / self.dt)) overflow = np.zeros_like(candidate, dtype=bool) start = None for i, flag in enumerate(candidate): if flag and start is None: start = i elif not flag and start is not None: if (i - start) >= min_steps: overflow[start:i] = True start = None if start is not None and (len(candidate) - start) >= min_steps: overflow[start:] = True return overflow # ------------------------------------------------------------------ # Insight type classification # ------------------------------------------------------------------ def classify_insight(self, delta_kn, q_value, dyn_shift, resp_shift): """ Multi-criterion insight classification. incremental: retained adjustment with little dynamical or response change structural: meaningful reorganisation of trajectory geometry / field organisation substrate: altered response mode; same class of signal may now be processed differently """ # Normalised components nk = min(delta_kn / 0.25, 1.0) nq = min(max(1.0 - q_value, 0.0), 1.0) nd = min(dyn_shift / 1.0, 1.0) nr = min(resp_shift / 1.0, 1.0) depth_score = ( 0.35 * nk + 0.20 * nq + 0.20 * nd + 0.25 * nr ) if nr >= 0.35 and depth_score >= 0.66: insight_type = "substrate" elif nd >= 0.15 and depth_score >= 0.33: insight_type = "structural" else: insight_type = "incremental" return insight_type, { "nk": float(nk), "nq": float(nq), "nd": float(nd), "nr": float(nr), "depth_score": float(depth_score), } # ------------------------------------------------------------------ # Event detection # ------------------------------------------------------------------ def _find_first_validated_insight(self, start_idx=0): min_dwell_steps = max(1, int(self.min_insight_dwell / self.dt)) refractory_steps = max(1, int(self.insight_refractory / self.dt)) pre_steps = max(1, int(self.prepressure_window / self.dt)) i = max(0, start_idx) while i < self.n: if self.insight_mask[i]: onset = i while i < self.n and self.insight_mask[i]: i += 1 end = i dwell = end - onset if dwell < min_dwell_steps: continue pre_start = max(0, onset - pre_steps) prepressure = ( np.mean(np.abs(self.Af[pre_start:onset])) if onset > pre_start else 0.0 ) current_pressure = ( np.mean(np.abs(self.pressure[pre_start:onset])) if onset > pre_start else 0.0 ) min_slope = np.min(self.dIn[onset:end]) if onset < end else 0.0 delta_E = self.energy_drop(onset) q_value = self.coherence(onset) valid = ( np.abs(self.In[onset]) > self.theta and prepressure >= self.gamma_overflow and current_pressure >= self.gamma_overflow and min_slope < -self.collapse_threshold and delta_E < -self.energy_release_threshold and q_value < self.coherence_threshold ) if valid: refractory_end = min(self.n, onset + refractory_steps) return { "idx": onset, "segment_end": end, "refractory_end": refractory_end, "prepressure": prepressure, "current_pressure": current_pressure, "min_slope": min_slope, "delta_E": delta_E, "Q": q_value, } else: i += 1 return None # ------------------------------------------------------------------ # Reorganisation # ------------------------------------------------------------------ def _apply_reorganisation(self, event): idx = event["idx"] post_idx = min(self.n - 1, event["refractory_end"]) # Resolved component of insight resolved = max(0.0, np.abs(self.In[idx]) - np.abs(self.In[post_idx])) delta_kn = self.eta_insight_to_kn * resolved # Compute reorganisation diagnostics BEFORE writing back dyn_shift = self.dynamical_shift(idx) resp_shift = self.response_shift(idx) insight_type, score_dict = self.classify_insight( delta_kn=delta_kn, q_value=event["Q"], dyn_shift=dyn_shift, resp_shift=resp_shift, ) # Update K_n from event onward self.Kn[idx:] += delta_kn # Reorganise CIF state at event self.CF[idx] += self.alpha_cf * delta_kn # Direction-sensitive derivative updates self.dCF[idx] -= self.beta_dcf * np.sign(self.dIn[idx]) * delta_kn self.ddCF[idx] -= self.beta_ddcf * np.sign(self.Af[idx]) * delta_kn self.reorganisation_log.append({ "idx": int(idx), "time": float(self.t[idx]), "resolved_insight": float(resolved), "delta_kn": float(delta_kn), "delta_E": float(event["delta_E"]), "min_slope": float(event["min_slope"]), "Q": float(event["Q"]), "prepressure": float(event["prepressure"]), "current_pressure": float(event["current_pressure"]), "dyn_shift": float(dyn_shift), "resp_shift": float(resp_shift), "type": insight_type, "depth_score": float(score_dict["depth_score"]), "nk": float(score_dict["nk"]), "nq": float(score_dict["nq"]), "nd": float(score_dict["nd"]), "nr": float(score_dict["nr"]), }) return delta_kn # ------------------------------------------------------------------ # Main simulation # ------------------------------------------------------------------ def simulate( self, input_type="sine", input_freq=0.5, input_amp=1.0, noise=0.03, pulse_count=3, pulse_duty=0.2, max_events=100, ): self.reset() self.build_stimulus( input_type=input_type, input_freq=input_freq, input_amp=input_amp, noise=noise, pulse_count=pulse_count, pulse_duty=pulse_duty, ) start_idx = 0 x0 = [0.0, 0.0, 0.0] event_count = 0 while start_idx < self.n - 1 and event_count < max_events: self._simulate_segment(start_idx, x0) event = self._find_first_validated_insight(start_idx=start_idx) if event is None: break idx = event["idx"] self.insight_reconfigurations[idx] = True self.insight_event_indices.append(idx) self._apply_reorganisation(event) # Continue from reorganised state x0 = [ float(self.CF[idx]), float(self.dCF[idx]), float(self.ddCF[idx]), ] start_idx = min(self.n - 1, event["refractory_end"]) event_count += 1 # Final global recomputation for consistency self._simulate_segment(0, [self.CF[0], self.dCF[0], self.ddCF[0]]) # Restore exact event markers after recomputation self.insight_reconfigurations[:] = False if self.insight_event_indices: self.insight_reconfigurations[self.insight_event_indices] = True self.overflow_mask[:] = self._compute_overflow_mask() return self # ------------------------------------------------------------------ # Convenience summary # ------------------------------------------------------------------ def summary(self): return { "num_insight_events": int(np.sum(self.insight_reconfigurations)), "insight_times": self.t[self.insight_reconfigurations].tolist(), "overflow_fraction": float(np.mean(self.overflow_mask)), "max_affectance": float(np.max(np.abs(self.Af))) if len(self.Af) else 0.0, "max_pressure": float(np.max(self.pressure)) if len(self.pressure) else 0.0, "max_energy": float(np.max(self.energy)) if len(self.energy) else 0.0, "reorganisation_log": self.reorganisation_log, }