Spaces:
Sleeping
Sleeping
File size: 11,647 Bytes
4e16dd3 | 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 258 259 260 261 262 263 264 265 |
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) |