import random import math import numpy as np from mesa import Model from mesa.space import ContinuousSpace from ReceptorAgent import ReceptorAgent from AntibodyAgent import AntibodyAgent # ─────────────────────────────────────────────────────────────────────────────── # Default parameters # ─────────────────────────────────────────────────────────────────────────────── DT = 0.0001 #1.0 # s SPACE_SIZE = 10.0 # µm MEMBRANE_Y = 0.0 N_RECEPTOR_A = 50 N_RECEPTOR_B = 50 N_ANTIBODIES = 150 C_BULK = 50e-9 # mol/L = 50 nM BOUNDARY_EXIT_DIST = 0.1 # µm BOUNDARY_ENTRY_DIST = 0.1 # Diffusion (µm² per DT) D_REC = 5.0e-2 D_AB = 4.0e1 # Kinetics KON_A, KOFF_A = 1e6, 1e-4 KON_B, KOFF_B = 1e6, 1e-4 BIND_RADIUS = 0.015 # µm LINK_LENGTH = 0.03 # µm # TOTAL_STEPS = 10000 RANDOM_SEED = 42 P_MAX = 0.10 # Ideally 0.1 random.seed(RANDOM_SEED) np.random.seed(RANDOM_SEED) # -------------------------------------------------------------------- # # Geometry → conversion factor # # -------------------------------------------------------------------- # AVOGADRO = 6.022_140_76e23 # mol⁻¹ CAPTURE_RADIUS = 0.015e-6 # 15 nm (BIND_RADIUS) CAPTURE_HEIGHT = 0.03e-6 # 30 nm (arm reach above membrane) V_EFF = math.pi * CAPTURE_RADIUS**2 * CAPTURE_HEIGHT # m³ KON_FACTOR = 1e-3 / (AVOGADRO * V_EFF) # mol/L → molecules in V_eff with m³ -> L correction (1e-3) # -------------------------------------------------------------------- # # Safe off rates # # -------------------------------------------------------------------- # koff_max = max(KOFF_A, KOFF_B) off_rate_safe = (koff_max * DT <= P_MAX/2) # ─────────────────────────────────────────────────────────────────────────────── # Model class # ─────────────────────────────────────────────────────────────────────────────── class HybridAvidityModel(Model): """Mesa model holding all agents and parameters.""" def __init__( self, *, space_size: float = SPACE_SIZE, n_receptor_a: int = N_RECEPTOR_A, n_receptor_b: int = N_RECEPTOR_B, n_antibodies: int = N_ANTIBODIES, membrane_y: float = MEMBRANE_Y, d_rec: float = D_REC, d_ab: float = D_AB, dt: float = DT, link_length: float = LINK_LENGTH, bind_radius: float = BIND_RADIUS, kon_a: float = KON_A, kon_b: float = KON_B, koff_a: float = KOFF_A, koff_b: float = KOFF_B, kon_factor: float = KON_FACTOR, c_bulk: float = C_BULK, exit_dist: float = BOUNDARY_EXIT_DIST, entry_height: float = BOUNDARY_ENTRY_DIST ): """ Parameters ---------- space_size : Side length of the (square) simulation space. n_receptor_a : Number of type-A receptors to seed. n_receptor_b : Number of type-B receptors to seed. n_antibodies : Number of antibody agents to seed. membrane_y : Fixed y-coordinate of the membrane. """ super().__init__(seed=RANDOM_SEED) # Store parameters on the model instance self.space_size = space_size self.n_receptor_a = n_receptor_a self.n_receptor_b = n_receptor_b self.n_antibodies = n_antibodies self.membrane_y = membrane_y self.d_rec = d_rec self.d_ab = d_ab self.dt = dt # integration timestep self.link_length = link_length # max reach of the second arm once first is bound self.bind_radius = bind_radius # search radius when completely unbound self.kon_a = kon_a # on-rate for arm A self.kon_b = kon_b # on-rate for arm B self.koff_a = koff_a # off-rate for arm A self.koff_b = koff_b # off-rate for arm B self.kon_factor = kon_factor self.c_bulk = c_bulk self.exit_dist = exit_dist self.entry_height = entry_height # Non-toroidal: we handle x-wrap manually; y never wraps self.space = ContinuousSpace(self.space_size, self.space_size, torus=False) self._init_agents() self._next_id = 0 def next_id(self): # ← Add this method self._next_id += 1 return self._next_id # ──────────────────────────────────────────────────────────────────────── def _init_agents(self): uid = 0 # Receptor A for _ in range(self.n_receptor_a): x = random.uniform(0, self.space_size) rec = ReceptorAgent(uid, self, "A") self.space.place_agent(rec, (x, self.membrane_y)) self.agents.add(rec) # Receptor B for _ in range(self.n_receptor_b): x = random.uniform(0, self.space_size) rec = ReceptorAgent(uid, self, "B") self.space.place_agent(rec, (x, self.membrane_y)) self.agents.add(rec) # Antibodies for _ in range(self.n_antibodies): x = random.uniform(0, self.space_size) y = random.uniform(self.membrane_y, self.space_size) ab = AntibodyAgent(uid, self) self.space.place_agent(ab, (x, y)) self.agents.add(ab) def _adaptive_substeps(self) -> int: """ Return the smallest positive integer n such that, if we subdivide the macro-step self.dt into n micro-steps, every *binding* and *unbinding* probability is ≤ P_MAX. """ # Worst unbinding probability anywhere koff_max = max(self.koff_a, self.koff_b) n_sub_off = math.ceil(koff_max * self.dt / P_MAX) # Worst binding probability (scan antibodies) n_sub_on = 1 for ab in (ag for ag in self.agents if isinstance(ag, AntibodyAgent)): # new early exit for double bound antibodies - all off-rate dependant if ab.n_bound == 2: continue # no binding possible → skip # new early-exit --------------------------------------------------- reach = self.link_length if ab.n_bound else self.bind_radius if ab.pos[1] - self.membrane_y > 2*reach: # too far above membrane continue # ------------------------------------------------------------------ # conservative upper bound: assume every compatible receptor # in the lateral search strip is in range r_search = self.link_length if ab.n_bound else self.bind_radius frac_strip = 2 * r_search / self.space_size n_cand_upper = math.ceil( (self.n_receptor_a + self.n_receptor_b) * frac_strip ) lamA = ( ab.kon_a * self.kon_factor * n_cand_upper if ab.arm_state["A"] is None else ab.koff_a ) lamB = ( ab.kon_b * self.kon_factor * n_cand_upper if ab.arm_state["B"] is None else ab.koff_b ) lam_tot = lamA + lamB n_sub_on = max(n_sub_on, math.ceil(lam_tot * self.dt / P_MAX)) return max(1, n_sub_off, n_sub_on) def _handle_antibody_entry_exit(self, dt_micro): """Poisson entry/exit for 2D model with effective depth.""" # --- Entry of antibodies --- delta_reaction_zone = self.link_length * 2 # µm — effective depth for concentration conversion C_bulk_M = self.c_bulk # mol/L # Volumetric concentration in molecules/µm³ C_bulk_vol_particles = C_bulk_M * AVOGADRO * 1e-15 # (1L = 1e15 µm³) # Line flux density: D * C_volumetric (molecules / (µm*s)) line_flux_density_in = self.d_ab * C_bulk_vol_particles A_boundary_length = self.space_size # length of 1D "top boundary" in µm expected_incoming_count = line_flux_density_in * A_boundary_length * dt_micro N_new = np.random.poisson(expected_incoming_count) for _ in range(N_new): x = random.uniform(0, self.space_size) # Place new antibodies just inside the top boundary, within entry_height y = self.space_size - random.uniform(1e-9, self.entry_height) # ensure y < self.space_size ab = AntibodyAgent(self.next_id(), self) # Use model.next_id() for unique ID self.space.place_agent(ab, (x, y)) self.agents.add(ab) # Add to custom agent scheduler/set # --- Exit of antibodies --- # Get unbound antibodies near the top boundary (in the exit zone) exit_zone_abs = [ ag for ag in self.agents if isinstance(ag, AntibodyAgent) and ag.n_bound == 0 and ag.pos[1] >= self.space_size - self.exit_dist ] current_N_in_exit_zone = len(exit_zone_abs) if current_N_in_exit_zone > 0: # Rate constant for a particle to diffuse out of the exit_dist layer (1/s) # k_exit_particle = D / L^2 k_exit_per_particle = self.d_ab / (self.exit_dist ** 2) # Mean number of particles exiting in dt_micro lambda_poisson_exit = k_exit_per_particle * current_N_in_exit_zone * dt_micro N_exit = np.random.poisson(lambda_poisson_exit) # Ensure we don't try to remove more particles than available in the exit zone N_exit = min(current_N_in_exit_zone, N_exit) if N_exit > 0: to_remove = random.sample(exit_zone_abs, N_exit) for ag_to_remove in to_remove: # It's good practice to ensure agent is still in collection if complex logic could remove it elsewhere, # though with current structure, exit_zone_abs is fresh. self.space.remove_agent(ag_to_remove) # Remove from space self.agents.remove(ag_to_remove) # Remove from custom agent scheduler/set # ──────────────────────────────────────────────────────────────────────── def step(self): n_sub = self._adaptive_substeps() dt_micro = self.dt / n_sub #print(f"New step size = {dt_micro}") # Tell every agent the micro-timestep it must use this macro-tick for ag in self.agents: ag.dt = dt_micro # both antibodies & receptors # Now advance the simulation in n_sub micro-steps for _ in range(n_sub): self.agents.shuffle().do("step") self._handle_antibody_entry_exit(dt_micro)