# IO Simulation v2.2 Code (1D, P_target Adapt v3 - Modulated Stability)
## 1. Objective
This node provides the updated Python code (v2.2) for the 1D Information Dynamics (IO) simulation. This version implements the significantly revised `P_target` update logic based on **Mechanism v3 (Contextual Adaptation with Modulated Stability Influence)** as specified in [[releases/archive/Information Ontology 1/0115_P_target_Dynamics_v3]]. It aims to address the potentiality collapse issue observed in simulations using code v2.1 ([[releases/archive/Information Ontology 1/0112_IO_Simulation_v2.1_Code]]). The core logic for Η, Θ, K, M influencing `P_change` and target selection remains based on [[releases/archive/Information Ontology 1/0104_IO_Formalism_v2_Summary]].
## 2. Key Changes from v2.1 Code ([[0112]])
* The `P_target` update logic (previously in Phase 3b/6b combined) is completely replaced with the new v3 mechanism from [[releases/archive/Information Ontology 1/0115_P_target_Dynamics_v3]].
* Introduces new parameters: `lambda_base_adapt` and `beta_adapt`.
* Removes the parameter `delta_p_inc` (direct reinforcement is removed).
* The calculation of `P_intermediate` is removed as it's no longer needed in the same way.
## 3. Python Code (v2.2)
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import io
import base64
# --- Parameters ---
# These will be set specifically in execution nodes (e.g., 0117)
# Example placeholder values:
N = 200
S_max = 500
h = 0.5
alpha = 0.1
gamma = 1.0
p_M = 0.25
delta_theta_inc = 0.05
theta_max = 5.0
theta_base = 0.0
# delta_p_inc REMOVED
lambda_base_adapt = 0.05 # NEW: Base adaptation rate for P_target
beta_adapt = 0.1 # NEW: How strongly Theta modulates adaptation rate
p_min = 1e-9
# --- Helper Functions (Identical to 0112) ---
def normalize_p_target(p_target_array):
"""Normalizes P_target rows and applies p_min floor."""
if p_target_array.ndim == 1: p_target_array = p_target_array.reshape(1, -1)
p_target_array = np.maximum(p_target_array, p_min)
row_sums = p_target_array.sum(axis=1)
row_sums[row_sums == 0] = 1
p_target_array = p_target_array / row_sums[:, np.newaxis]
return p_target_array
def calculate_k_local(epsilon_state):
"""Calculates local contrast K based on immediate neighbors."""
neighbors_left = np.roll(epsilon_state, 1)
neighbors_right = np.roll(epsilon_state, -1)
k_local = 0.5 * (np.abs(epsilon_state - neighbors_left) +
np.abs(epsilon_state - neighbors_right))
return k_local
def f_H(h_param, p_leave_array):
"""Η drive function."""
return np.clip(h_param * p_leave_array, 0.0, 1.0)
def f_Theta(theta_val_array, alpha_param):
"""Θ resistance function."""
return 1.0 / (1.0 + alpha_param * theta_val_array)
def f_K(k_local_array, gamma_param):
"""K gating function."""
return np.power(k_local_array, gamma_param)
# --- Simulation Function ---
def run_io_simulation_v2_2(params):
"""Runs the IO v2.2 simulation with P_target dynamics v3."""
N = params['N']
S_max = params['S_max']
h = params['h']
alpha = params['alpha']
gamma = params['gamma']
p_M = params['p_M']
delta_theta_inc = params['delta_theta_inc']
theta_max = params['theta_max']
theta_base = params['theta_base']
# delta_p_inc removed
lambda_base_adapt = params['lambda_base_adapt']
beta_adapt = params['beta_adapt']
p_min = params['p_min']
seed = params.get('seed', None)
if seed is not None:
np.random.seed(seed)
else:
np.random.seed()
# Initialization
epsilon_state = np.random.randint(0, 2, size=N)
p_target_state = np.full((N, 2), 0.5)
theta_state = np.zeros(N)
epsilon_history = np.zeros((S_max, N), dtype=int)
avg_theta_history = np.zeros(S_max)
avg_ptarget_entropy_history = np.zeros(S_max)
# --- Simulation Loop ---
for S in range(S_max):
epsilon_history[S, :] = epsilon_state
prev_epsilon = epsilon_state.copy()
prev_p_target = p_target_state.copy()
prev_theta = theta_state.copy() # Use theta from start of step S for P_target update
# --- Phase 1: Calculate Influences ---
k_local = calculate_k_local(prev_epsilon)
neighbors_left_eps = np.roll(prev_epsilon, 1)
neighbors_right_eps = np.roll(prev_epsilon, -1)
influence_0 = (neighbors_left_eps == 0).astype(int) + (neighbors_right_eps == 0).astype(int)
influence_1 = (neighbors_left_eps == 1).astype(int) + (neighbors_right_eps == 1).astype(int)
total_causal_weight = influence_0 + influence_1 # = 2 for this setup
# --- Phase 2: Determine Probability of State Change ---
p_leave = 1.0 - prev_p_target[np.arange(N), prev_epsilon]
prob_H_driven = f_H(h, p_leave)
prob_Theta_resisted = f_Theta(prev_theta, alpha) # Use prev_theta here
prob_K_gated = f_K(k_local, gamma)
P_change = prob_H_driven * prob_Theta_resisted * prob_K_gated
# --- Phase 3: Execute State Transition ---
r_change = np.random.rand(N)
change_mask = r_change < P_change
no_change_mask = ~change_mask
# --- Initialize next step states ---
current_epsilon = prev_epsilon.copy() # Use current_epsilon for clarity
next_epsilon = current_epsilon.copy()
next_theta = prev_theta.copy()
next_p_target = prev_p_target.copy()
# --- Determine Target State for Changing Nodes ---
changing_indices = np.where(change_mask)[0]
if len(changing_indices) > 0:
p_target_0_intrinsic = prev_p_target[changing_indices, 0]
p_target_1_intrinsic = prev_p_target[changing_indices, 1]
mod_factor_0 = (1 + p_M * influence_0[changing_indices] / 2.0)
mod_factor_1 = (1 + p_M * influence_1[changing_indices] / 2.0)
p_prime_0 = p_target_0_intrinsic * mod_factor_0
p_prime_1 = p_target_1_intrinsic * mod_factor_1
sum_p_prime = p_prime_0 + p_prime_1
sum_p_prime[sum_p_prime == 0] = 1
P_modified_target_0 = p_prime_0 / sum_p_prime
r_target = np.random.rand(len(changing_indices))
epsilon_target = (r_target >= P_modified_target_0).astype(int)
next_epsilon[changing_indices] = epsilon_target
# --- Update Theta for ALL nodes ---
next_theta[change_mask] = theta_base
next_theta[no_change_mask] = np.minimum(prev_theta[no_change_mask] + delta_theta_inc, theta_max)
# --- Update P_target using Mechanism v3 ---
# Calculate Contextual Target P_context for ALL nodes
p_context = np.zeros_like(prev_p_target)
valid_ca = total_causal_weight > 0
valid_indices = np.where(valid_ca)[0]
if len(valid_indices) > 0:
p_context[valid_indices, 0] = influence_0[valid_indices] / total_causal_weight[valid_indices]
p_context[valid_indices, 1] = influence_1[valid_indices] / total_causal_weight[valid_indices]
invalid_indices = np.where(~valid_ca)[0]
if len(invalid_indices) > 0:
p_context[invalid_indices, :] = 0.5 # Default to uniform
# Calculate effective adaptation rate based on *previous* theta
f_theta_adapt = 1.0 / (1.0 + beta_adapt * prev_theta)
lambda_eff = lambda_base_adapt * f_theta_adapt
# Update P_target based on whether epsilon changed *this step*
# For changing nodes: Reset towards P_context (using lambda_reset = 1.0)
if len(changing_indices) > 0:
next_p_target[changing_indices, :] = p_context[changing_indices, :]
# For stable nodes: Adapt gradually towards P_context
stable_indices = np.where(no_change_mask)[0]
if len(stable_indices) > 0:
lambda_eff_stable = lambda_eff[stable_indices] # Get lambda_eff for stable nodes
next_p_target[stable_indices, :] = (1.0 - lambda_eff_stable[:, np.newaxis]) * prev_p_target[stable_indices, :] \
+ lambda_eff_stable[:, np.newaxis] * p_context[stable_indices, :]
# Apply H floor and Final Normalization for ALL nodes
next_p_target = normalize_p_target(next_p_target)
# --- Assign final states for next step ---
epsilon_state = next_epsilon
theta_state = next_theta
p_target_state = next_p_target
# --- Phase 4: Update Causal Network (Not implemented) ---
# --- Calculate Metrics for History ---
avg_theta_history[S] = np.mean(theta_state)
p0 = p_target_state[:, 0]
p1 = p_target_state[:, 1]
ptarget_entropy = - (p0 * np.log2(p0) + p1 * np.log2(p1))
avg_ptarget_entropy_history[S] = np.mean(ptarget_entropy)
# --- Prepare Results ---
results = {
"parameters": params,
"epsilon_history": epsilon_history,
"avg_theta_history": avg_theta_history,
"avg_ptarget_entropy_history": avg_ptarget_entropy_history
}
return results
# --- Plotting Function (Identical to 0112) ---
def plot_results(results, title_suffix=""):
"""Generates plots from simulation results and returns base64 string."""
params = results["parameters"]
epsilon_history = results["epsilon_history"]
avg_theta_history = results["avg_theta_history"]
avg_ptarget_entropy_history = results["avg_ptarget_entropy_history"]
S_max = params['S_max']
fig, axs = plt.subplots(3, 1, figsize=(10, 8), sharex=True)
cmap = mcolors.ListedColormap(['black', 'white'])
axs[0].imshow(epsilon_history, cmap=cmap, aspect='auto', interpolation='none')
axs[0].set_title(f'IO v2.2 Simulation {title_suffix}: ε State Evolution')
axs[0].set_ylabel('Sequence Step (S)')
axs[1].plot(avg_theta_history)
axs[1].set_title('Average Stability (Θ_val)')
axs[1].set_ylabel('Avg Θ_val')
axs[1].grid(True)
axs[2].plot(avg_ptarget_entropy_history)
axs[2].set_title('Average Potentiality Entropy (H(P_target))')
axs[2].set_xlabel('Sequence Step (S)')
axs[2].set_ylabel('Avg Entropy (bits)')
axs[2].grid(True)
plt.tight_layout()
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
plot_base64 = base64.b64encode(buf.read()).decode('utf-8')
buf.close()
plt.close(fig)
return plot_base64
# --- Example Usage (commented out - execution happens in separate nodes) ---
# params_run8 = {
# 'N': 200, 'S_max': 500, 'h': 0.5, 'alpha': 0.1, 'gamma': 1.0,
# 'p_M': 0.25, 'delta_theta_inc': 0.05, 'theta_max': 5.0,
# 'theta_base': 0.0, #'delta_p_inc': 0.01, # Removed
# 'lambda_base_adapt': 0.05, # NEW
# 'beta_adapt': 0.1, # NEW
# 'p_min': 1e-9, 'seed': 42
# }
# results_run8 = run_io_simulation_v2_2(params_run8)
# plot_b64_run8 = plot_results(results_run8, title_suffix="(Run 8 - P_target Adapt v3)")
# print(f"Run 8 Complete. Final Avg Theta: {results_run8['avg_theta_history'][-1]:f}, Final Avg P_target Entropy: {results_run8['avg_ptarget_entropy_history'][-1]:f}")
# print(f"Plot generated: {plot_b64_run8[:100]}...")
```
## 4. Code Structure and Logic
* The code structure follows [[releases/archive/Information Ontology 1/0112_IO_Simulation_v2.1_Code]] with parameters passed via dictionary and separate simulation/plotting functions.
* The core change is within the main loop, specifically how `next_p_target` is calculated.
* It now calculates `P_context` based on causal neighbors.
* It calculates an effective adaptation rate `lambda_eff` modulated by the *previous* step's `theta_state` (`prev_theta`).
* It applies different update rules based on whether the node changed state (`change_mask`) or remained stable (`no_change_mask`):
* Changing nodes reset `next_p_target` towards `P_context` (using `lambda_reset=1.0` here).
* Stable nodes adapt `next_p_target` gradually towards `P_context` using `lambda_eff`.
* The final normalization and Η floor (`p_min`) are applied to `next_p_target`.
## 5. Next Steps
This code (v2.2) is now ready for execution. The next node ([[releases/archive/Information Ontology 1/0117_IO_Simulation_Run8]]) will use this code to run a simulation with parameters designed to test if this new `P_target` dynamic successfully maintains potentiality entropy and allows for complex emergence.