import numpy as np from scipy.integrate import solve_ivp class UDPModel: """ Recursive Universal Derivative Principle model with soft suppression. 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, dynamically softened by suppression) * collapse rate (Xi) * energy release (Lambda) * coherence functional (kappa) - Recursive reorganisation: validated insight feeds into K_n and updates CIF state - Soft suppression: after insight, the effective threshold rises and then decays - 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, 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), suppression_decay=1.5, # λ suppression_gain=2.0, # gain of suppression kick suppression_floor=0.0, 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.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 # Soft suppression self.suppression_decay = suppression_decay self.suppression_gain = suppression_gain self.suppression_floor = suppression_floor # RNG self.rng = np.random.default_rng(seed) self.seed = seed 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) # Soft suppression self.sigma = np.zeros(n) self.theta_eff = 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) # Effective threshold under soft suppression self.theta_eff[:] = self.theta * (1.0 + self.sigma) self.insight_mask[:] = np.abs(self.In) > self.theta_eff # ------------------------------------------------------------------ # Suppression # ------------------------------------------------------------------ def _decay_suppression_from(self, start_idx=1): """ Recompute sigma forward using exponential-like discrete decay, preserving any kicks already written into sigma. """ if start_idx < 1: start_idx = 1 for i in range(start_idx, self.n): decayed_prev = self.sigma[i - 1] - self.suppression_decay * self.sigma[i - 1] * self.dt self.sigma[i] = max(self.suppression_floor, self.sigma[i] + decayed_prev) def _apply_suppression_kick(self, idx, strength): """ Add a suppression kick from idx onward, then decay it forward. """ if idx < self.n: self.sigma[idx] += self.suppression_gain * max(0.0, strength) self._decay_suppression_from(idx + 1) # ------------------------------------------------------------------ # Energy / coherence / diagnostics # ------------------------------------------------------------------ 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_eff 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. """ 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): pre_steps = max(1, int(self.prepressure_window / self.dt)) i = max(0, start_idx) while i < self.n: # threshold under current suppression if np.abs(self.In[i]) > self.theta_eff[i]: pre_start = max(0, i - pre_steps) prepressure = ( np.mean(np.abs(self.Af[pre_start:i])) if i > pre_start else 0.0 ) current_pressure = ( np.mean(np.abs(self.pressure[pre_start:i])) if i > pre_start else 0.0 ) min_slope = self.dIn[i] delta_E = self.energy_drop(i) q_value = self.coherence(i) valid = ( np.abs(self.In[i]) > self.theta_eff[i] 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: # For resolved-insight search window, use coherence window settle_steps = max(2, int(self.coherence_window / self.dt)) post_idx = min(self.n - 1, i + settle_steps) return { "idx": i, "post_idx": post_idx, "prepressure": prepressure, "current_pressure": current_pressure, "min_slope": min_slope, "delta_E": delta_E, "Q": q_value, } i += 1 return None # ------------------------------------------------------------------ # Reorganisation # ------------------------------------------------------------------ def _apply_reorganisation(self, event): idx = event["idx"] post_idx = event["post_idx"] # -------------------------------------------------------------- # Resolved component of insight: # use the first post-collapse local minimum of |I_n| before rebound. # If no local rebound is found, fall back to the absolute minimum. # -------------------------------------------------------------- pre_abs_in = float(np.abs(self.In[idx])) post_abs_slice = np.abs(self.In[idx:post_idx + 1]) local_min_abs_in = pre_abs_in local_min_offset = 0 if post_abs_slice.size > 1: dpost = np.diff(post_abs_slice) turning_found = False for j in range(1, len(dpost)): if dpost[j - 1] <= 0 and dpost[j] > 0: local_min_offset = j local_min_abs_in = float(post_abs_slice[j]) turning_found = True break if not turning_found: local_min_offset = int(np.argmin(post_abs_slice)) local_min_abs_in = float(post_abs_slice[local_min_offset]) local_min_idx = idx + local_min_offset resolved = max(0.0, pre_abs_in - local_min_abs_in) delta_kn = self.eta_insight_to_kn * resolved # -------------------------------------------------------------- # 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 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 # -------------------------------------------------------------- # Soft suppression kick: # stronger events raise future threshold more. # -------------------------------------------------------------- suppression_strength = max(pre_abs_in, resolved, np.abs(event["delta_E"])) self._apply_suppression_kick(idx, suppression_strength) # -------------------------------------------------------------- # Event log # -------------------------------------------------------------- self.reorganisation_log.append({ "idx": int(idx), "time": float(self.t[idx]), "pre_abs_in": pre_abs_in, "local_min_abs_in": local_min_abs_in, "local_min_idx": int(local_min_idx), "local_min_time": float(self.t[local_min_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), "sigma": float(self.sigma[idx]), "theta_eff": float(self.theta_eff[idx]) if idx < len(self.theta_eff) else float(self.theta), "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 with zero suppression self.sigma[:] = 0.0 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) # Recompute effective threshold under current suppression self.theta_eff[:] = self.theta * (1.0 + self.sigma) self.insight_mask[:] = np.abs(self.In) > self.theta_eff 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]), ] # Move forward minimally; suppression handles relapse resistance start_idx = min(self.n - 1, idx + 1) event_count += 1 # Final global recomputation for consistency self._simulate_segment(0, [self.CF[0], self.dCF[0], self.ddCF[0]]) # Rebuild theta_eff after final pass self.theta_eff[:] = self.theta * (1.0 + self.sigma) # 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, "max_sigma": float(np.max(self.sigma)) if len(self.sigma) else 0.0, "reorganisation_log": self.reorganisation_log, } if __name__ == "__main__": model = UDPModel() model.simulate( input_type="non-linear", input_freq=0.5, input_amp=1.0, noise=0.03, ) summary = model.summary() print("\nUDPModel standalone run") print("-----------------------") print(f"Insight events: {summary['num_insight_events']}") print(f"Max pressure: {summary['max_pressure']:.3f}") print(f"Max energy: {summary['max_energy']:.3f}") print(f"Max suppression: {summary['max_sigma']:.3f}") if summary["reorganisation_log"]: print("\nFirst event:") ev = summary["reorganisation_log"][0] print(f" time: {ev['time']:.3f}") print(f" type: {ev['type']}") print(f" ΔKₙ: {ev['delta_kn']:.4f}") print(f" Q: {ev['Q']:.4f}") print(f" σ: {ev['sigma']:.4f}")