Spaces:
Sleeping
Sleeping
Daniel Holdbrook commited on
Commit Β·
4e16dd3
1
Parent(s): 20de211
Add application file
Browse files- AntibodyAgent.py +197 -0
- Dockerfile +22 -0
- HybridAvidityModel.py +265 -0
- ReceptorAgent.py +60 -0
- app.py +411 -0
- requirements.txt +6 -0
AntibodyAgent.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math, random
|
| 2 |
+
from typing import Dict, Optional
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from mesa import Agent, Model
|
| 6 |
+
from ReceptorAgent import ReceptorAgent
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class AntibodyAgent(Agent):
|
| 10 |
+
"""
|
| 11 |
+
Bispecific antibody with two arms (A binds Rec-A, B binds Rec-B).
|
| 12 |
+
|
| 13 |
+
β Uses one Poisson clock per antibody.
|
| 14 |
+
β Expects kon_a / kon_b in Mβ»ΒΉ sβ»ΒΉ, koff_a / koff_b in sβ»ΒΉ.
|
| 15 |
+
β model.dt is the *micro-step* chosen by your adaptive driver.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
# ------------------------------------------------------------------ #
|
| 19 |
+
# Construction #
|
| 20 |
+
# ------------------------------------------------------------------ #
|
| 21 |
+
def __init__(self, uid: int, model: Model):
|
| 22 |
+
super().__init__(model)
|
| 23 |
+
self.arm_state: Dict[str, Optional[ReceptorAgent]] = {"A": None, "B": None}
|
| 24 |
+
|
| 25 |
+
# cached model constants
|
| 26 |
+
self.space_size = model.space_size
|
| 27 |
+
self.membrane_y = model.membrane_y
|
| 28 |
+
self.d_ab = model.d_ab # Β΅mΒ² sβ»ΒΉ
|
| 29 |
+
self.link_length = model.link_length
|
| 30 |
+
self.bind_radius = model.bind_radius
|
| 31 |
+
|
| 32 |
+
# kinetics (physical units)
|
| 33 |
+
self.kon_a = model.kon_a # Mβ»ΒΉ sβ»ΒΉ
|
| 34 |
+
self.kon_b = model.kon_b
|
| 35 |
+
self.koff_a = model.koff_a # sβ»ΒΉ
|
| 36 |
+
self.koff_b = model.koff_b
|
| 37 |
+
self.kon_factor = model.kon_factor # 1 / (N_A V_eff)
|
| 38 |
+
|
| 39 |
+
# will be overwritten each macro-step by the driver
|
| 40 |
+
self.dt = model.dt
|
| 41 |
+
|
| 42 |
+
# ------------------------------------------------------------------ #
|
| 43 |
+
# Derived state #
|
| 44 |
+
# ------------------------------------------------------------------ #
|
| 45 |
+
@property
|
| 46 |
+
def n_bound(self) -> int:
|
| 47 |
+
return sum(rec is not None for rec in self.arm_state.values())
|
| 48 |
+
|
| 49 |
+
# ------------------------------------------------------------------ #
|
| 50 |
+
# Core step #
|
| 51 |
+
# ------------------------------------------------------------------ #
|
| 52 |
+
def step(self):
|
| 53 |
+
"""Move first, then allow *one* event (bind OR unbind)."""
|
| 54 |
+
self._move()
|
| 55 |
+
self._attempt_state_change()
|
| 56 |
+
|
| 57 |
+
# ------------------------------------------------------------------ #
|
| 58 |
+
# Movement (unchanged) #
|
| 59 |
+
# ------------------------------------------------------------------ #
|
| 60 |
+
def _move(self):
|
| 61 |
+
if self.n_bound == 0:
|
| 62 |
+
self._diffuse_free()
|
| 63 |
+
else:
|
| 64 |
+
self._tether_to_receptors()
|
| 65 |
+
|
| 66 |
+
def _diffuse_free(self):
|
| 67 |
+
sigma = math.sqrt(2 * self.d_ab * self.dt)
|
| 68 |
+
dx, dy = np.random.normal(0.0, sigma, 2)
|
| 69 |
+
|
| 70 |
+
x_new = (self.pos[0] + dx) % self.space_size
|
| 71 |
+
y_new = self.pos[1] + dy
|
| 72 |
+
|
| 73 |
+
if y_new < self.membrane_y:
|
| 74 |
+
y_new = self.membrane_y + (self.membrane_y - y_new)
|
| 75 |
+
elif y_new > self.space_size:
|
| 76 |
+
y_new = self.space_size - (y_new - self.space_size)
|
| 77 |
+
|
| 78 |
+
self.model.space.move_agent(self, (x_new, y_new))
|
| 79 |
+
|
| 80 |
+
def _tether_to_receptors(self):
|
| 81 |
+
xs = [rec.pos[0] for rec in self.arm_state.values() if rec]
|
| 82 |
+
ys = [rec.pos[1] for rec in self.arm_state.values() if rec]
|
| 83 |
+
anchor_x, anchor_y = sum(xs) / len(xs), sum(ys) / len(ys)
|
| 84 |
+
|
| 85 |
+
x_new = (anchor_x + np.random.normal(0.0, 0.01)) % self.space_size
|
| 86 |
+
y_new = max(
|
| 87 |
+
self.membrane_y,
|
| 88 |
+
min(self.space_size, anchor_y + np.random.normal(0.0, 0.01)),
|
| 89 |
+
)
|
| 90 |
+
self.model.space.move_agent(self, (x_new, y_new))
|
| 91 |
+
|
| 92 |
+
# ------------------------------------------------------------------ #
|
| 93 |
+
# One-draw Poisson kinetics #
|
| 94 |
+
# ------------------------------------------------------------------ #
|
| 95 |
+
def _attempt_state_change(self):
|
| 96 |
+
"""At most ONE elementary bind/unbind event per micro-step."""
|
| 97 |
+
channels = [] # (label, Ξ»_i) tuples
|
| 98 |
+
|
| 99 |
+
# ---- binding channels -----------------------------------------
|
| 100 |
+
if self.arm_state["A"] is None:
|
| 101 |
+
nA = self._count_candidates("A")
|
| 102 |
+
if nA:
|
| 103 |
+
lam = self.kon_a * self.kon_factor * nA
|
| 104 |
+
channels.append(("bind_A", lam))
|
| 105 |
+
|
| 106 |
+
if self.arm_state["B"] is None:
|
| 107 |
+
nB = self._count_candidates("B")
|
| 108 |
+
if nB:
|
| 109 |
+
lam = self.kon_b * self.kon_factor * nB
|
| 110 |
+
channels.append(("bind_B", lam))
|
| 111 |
+
|
| 112 |
+
# ---- unbinding channels ---------------------------------------
|
| 113 |
+
if self.arm_state["A"] is not None:
|
| 114 |
+
channels.append(("unbind_A", self.koff_a))
|
| 115 |
+
|
| 116 |
+
if self.arm_state["B"] is not None:
|
| 117 |
+
channels.append(("unbind_B", self.koff_b))
|
| 118 |
+
|
| 119 |
+
if not channels:
|
| 120 |
+
return # nothing can happen
|
| 121 |
+
|
| 122 |
+
Ξ»_tot = sum(lam for _, lam in channels)
|
| 123 |
+
p = 1.0 - math.exp(-Ξ»_tot * self.dt) # survival function
|
| 124 |
+
|
| 125 |
+
if random.random() >= p: # no event this tick
|
| 126 |
+
return
|
| 127 |
+
|
| 128 |
+
# roulette selection of the firing channel
|
| 129 |
+
r = random.random() * Ξ»_tot
|
| 130 |
+
acc = 0.0
|
| 131 |
+
for label, lam in channels:
|
| 132 |
+
acc += lam
|
| 133 |
+
if r <= acc:
|
| 134 |
+
if label == "bind_A":
|
| 135 |
+
rec = self._pick_random_candidate("A")
|
| 136 |
+
self._bind("A", rec)
|
| 137 |
+
elif label == "bind_B":
|
| 138 |
+
rec = self._pick_random_candidate("B")
|
| 139 |
+
self._bind("B", rec)
|
| 140 |
+
elif label == "unbind_A":
|
| 141 |
+
self._unbind("A")
|
| 142 |
+
elif label == "unbind_B":
|
| 143 |
+
self._unbind("B")
|
| 144 |
+
break
|
| 145 |
+
|
| 146 |
+
# ------------------------------------------------------------------ #
|
| 147 |
+
# Candidate helpers #
|
| 148 |
+
# ------------------------------------------------------------------ #
|
| 149 |
+
def _count_candidates(self, arm: str) -> int:
|
| 150 |
+
radius = self.link_length if self.n_bound else self.bind_radius
|
| 151 |
+
height = self.link_length # or set CAPTURE_HEIGHT explicitly
|
| 152 |
+
|
| 153 |
+
rec_type = "A" if arm == "A" else "B"
|
| 154 |
+
|
| 155 |
+
# Only proceed if antibody is close enough vertically
|
| 156 |
+
if abs(self.pos[1] - self.model.membrane_y) > height:
|
| 157 |
+
return 0
|
| 158 |
+
|
| 159 |
+
# Temporarily "project" to y = 0
|
| 160 |
+
projected_pos = (self.pos[0], self.model.membrane_y)
|
| 161 |
+
|
| 162 |
+
neighbors = self.model.space.get_neighbors(projected_pos, radius, include_center=False)
|
| 163 |
+
|
| 164 |
+
return sum(
|
| 165 |
+
isinstance(n, ReceptorAgent)
|
| 166 |
+
and n.rec_type == rec_type
|
| 167 |
+
and n.bound_ab is None
|
| 168 |
+
for n in neighbors
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
def _pick_random_candidate(self, arm: str) -> ReceptorAgent:
|
| 172 |
+
radius = self.link_length if self.n_bound else self.bind_radius
|
| 173 |
+
rec_type = "A" if arm == "A" else "B"
|
| 174 |
+
# Temporarily "project" to y = 0
|
| 175 |
+
projected_pos = (self.pos[0], self.model.membrane_y)
|
| 176 |
+
neighbors = self.model.space.get_neighbors(projected_pos, radius, include_center=False)
|
| 177 |
+
pool = [
|
| 178 |
+
n
|
| 179 |
+
for n in neighbors
|
| 180 |
+
if isinstance(n, ReceptorAgent)
|
| 181 |
+
and n.rec_type == rec_type
|
| 182 |
+
and n.bound_ab is None
|
| 183 |
+
]
|
| 184 |
+
return random.choice(pool)
|
| 185 |
+
|
| 186 |
+
# ------------------------------------------------------------------ #
|
| 187 |
+
# Book-keeping helpers #
|
| 188 |
+
# ------------------------------------------------------------------ #
|
| 189 |
+
def _bind(self, arm: str, receptor: ReceptorAgent):
|
| 190 |
+
self.arm_state[arm] = receptor
|
| 191 |
+
receptor.bound_ab = self
|
| 192 |
+
|
| 193 |
+
def _unbind(self, arm: str):
|
| 194 |
+
rec = self.arm_state[arm]
|
| 195 |
+
if rec:
|
| 196 |
+
rec.bound_ab = None
|
| 197 |
+
self.arm_state[arm] = None
|
Dockerfile
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use official Python image
|
| 2 |
+
FROM python:3.10-slim
|
| 3 |
+
|
| 4 |
+
# Set working directory
|
| 5 |
+
WORKDIR /code
|
| 6 |
+
|
| 7 |
+
# Install system dependencies
|
| 8 |
+
RUN apt-get update && apt-get install -y \
|
| 9 |
+
build-essential \
|
| 10 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
+
|
| 12 |
+
# Copy files into container
|
| 13 |
+
COPY . /code
|
| 14 |
+
|
| 15 |
+
# Install Python dependencies
|
| 16 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 17 |
+
|
| 18 |
+
# Expose default port
|
| 19 |
+
EXPOSE 7860
|
| 20 |
+
|
| 21 |
+
# Run the Solara app
|
| 22 |
+
CMD ["solara", "run", "app.py", "--host", "0.0.0.0", "--port", "7860"]
|
HybridAvidityModel.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import random
|
| 3 |
+
import math
|
| 4 |
+
import numpy as np
|
| 5 |
+
from mesa import Model
|
| 6 |
+
from mesa.space import ContinuousSpace
|
| 7 |
+
from ReceptorAgent import ReceptorAgent
|
| 8 |
+
from AntibodyAgent import AntibodyAgent
|
| 9 |
+
|
| 10 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
+
# Default parameters
|
| 12 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 13 |
+
DT = 0.0001 #1.0 # s
|
| 14 |
+
SPACE_SIZE = 10.0 # Β΅m
|
| 15 |
+
MEMBRANE_Y = 0.0
|
| 16 |
+
|
| 17 |
+
N_RECEPTOR_A = 50
|
| 18 |
+
N_RECEPTOR_B = 50
|
| 19 |
+
N_ANTIBODIES = 150
|
| 20 |
+
C_BULK = 50e-9 # mol/L = 50 nM
|
| 21 |
+
BOUNDARY_EXIT_DIST = 0.1 # Β΅m
|
| 22 |
+
BOUNDARY_ENTRY_DIST = 0.1
|
| 23 |
+
|
| 24 |
+
# Diffusion (Β΅mΒ² per DT)
|
| 25 |
+
D_REC = 5.0e-2
|
| 26 |
+
D_AB = 4.0e1
|
| 27 |
+
|
| 28 |
+
# Kinetics
|
| 29 |
+
KON_A, KOFF_A = 1e6, 1e-4
|
| 30 |
+
KON_B, KOFF_B = 1e6, 1e-4
|
| 31 |
+
|
| 32 |
+
BIND_RADIUS = 0.015 # Β΅m
|
| 33 |
+
LINK_LENGTH = 0.03 # Β΅m
|
| 34 |
+
|
| 35 |
+
# TOTAL_STEPS = 10000
|
| 36 |
+
RANDOM_SEED = 42
|
| 37 |
+
P_MAX = 0.10 # Ideally 0.1
|
| 38 |
+
|
| 39 |
+
random.seed(RANDOM_SEED)
|
| 40 |
+
np.random.seed(RANDOM_SEED)
|
| 41 |
+
|
| 42 |
+
# -------------------------------------------------------------------- #
|
| 43 |
+
# Geometry β conversion factor #
|
| 44 |
+
# -------------------------------------------------------------------- #
|
| 45 |
+
AVOGADRO = 6.022_140_76e23 # molβ»ΒΉ
|
| 46 |
+
CAPTURE_RADIUS = 0.015e-6 # 15 nm (BIND_RADIUS)
|
| 47 |
+
CAPTURE_HEIGHT = 0.03e-6 # 30 nm (arm reach above membrane)
|
| 48 |
+
V_EFF = math.pi * CAPTURE_RADIUS**2 * CAPTURE_HEIGHT # mΒ³
|
| 49 |
+
KON_FACTOR = 1e-3 / (AVOGADRO * V_EFF) # mol/L β molecules in V_eff with mΒ³ -> L correction (1e-3)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# -------------------------------------------------------------------- #
|
| 53 |
+
# Safe off rates #
|
| 54 |
+
# -------------------------------------------------------------------- #
|
| 55 |
+
koff_max = max(KOFF_A, KOFF_B)
|
| 56 |
+
off_rate_safe = (koff_max * DT <= P_MAX/2)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 60 |
+
# Model class
|
| 61 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 62 |
+
class HybridAvidityModel(Model):
|
| 63 |
+
"""Mesa model holding all agents and parameters."""
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
*,
|
| 68 |
+
space_size: float = SPACE_SIZE,
|
| 69 |
+
n_receptor_a: int = N_RECEPTOR_A,
|
| 70 |
+
n_receptor_b: int = N_RECEPTOR_B,
|
| 71 |
+
n_antibodies: int = N_ANTIBODIES,
|
| 72 |
+
membrane_y: float = MEMBRANE_Y,
|
| 73 |
+
d_rec: float = D_REC,
|
| 74 |
+
d_ab: float = D_AB,
|
| 75 |
+
dt: float = DT,
|
| 76 |
+
link_length: float = LINK_LENGTH,
|
| 77 |
+
bind_radius: float = BIND_RADIUS,
|
| 78 |
+
kon_a: float = KON_A,
|
| 79 |
+
kon_b: float = KON_B,
|
| 80 |
+
koff_a: float = KOFF_A,
|
| 81 |
+
koff_b: float = KOFF_B,
|
| 82 |
+
kon_factor: float = KON_FACTOR,
|
| 83 |
+
c_bulk: float = C_BULK,
|
| 84 |
+
exit_dist: float = BOUNDARY_EXIT_DIST,
|
| 85 |
+
entry_height: float = BOUNDARY_ENTRY_DIST
|
| 86 |
+
):
|
| 87 |
+
"""
|
| 88 |
+
Parameters
|
| 89 |
+
----------
|
| 90 |
+
space_size : Side length of the (square) simulation space.
|
| 91 |
+
n_receptor_a : Number of type-A receptors to seed.
|
| 92 |
+
n_receptor_b : Number of type-B receptors to seed.
|
| 93 |
+
n_antibodies : Number of antibody agents to seed.
|
| 94 |
+
membrane_y : Fixed y-coordinate of the membrane.
|
| 95 |
+
"""
|
| 96 |
+
super().__init__(seed=RANDOM_SEED)
|
| 97 |
+
|
| 98 |
+
# Store parameters on the model instance
|
| 99 |
+
self.space_size = space_size
|
| 100 |
+
self.n_receptor_a = n_receptor_a
|
| 101 |
+
self.n_receptor_b = n_receptor_b
|
| 102 |
+
self.n_antibodies = n_antibodies
|
| 103 |
+
self.membrane_y = membrane_y
|
| 104 |
+
self.d_rec = d_rec
|
| 105 |
+
self.d_ab = d_ab
|
| 106 |
+
self.dt = dt # integration timestep
|
| 107 |
+
self.link_length = link_length # max reach of the second arm once first is bound
|
| 108 |
+
self.bind_radius = bind_radius # search radius when completely unbound
|
| 109 |
+
self.kon_a = kon_a # on-rate for arm A
|
| 110 |
+
self.kon_b = kon_b # on-rate for arm B
|
| 111 |
+
self.koff_a = koff_a # off-rate for arm A
|
| 112 |
+
self.koff_b = koff_b # off-rate for arm B
|
| 113 |
+
self.kon_factor = kon_factor
|
| 114 |
+
self.c_bulk = c_bulk
|
| 115 |
+
self.exit_dist = exit_dist
|
| 116 |
+
self.entry_height = entry_height
|
| 117 |
+
|
| 118 |
+
# Non-toroidal: we handle x-wrap manually; y never wraps
|
| 119 |
+
self.space = ContinuousSpace(self.space_size, self.space_size, torus=False)
|
| 120 |
+
|
| 121 |
+
self._init_agents()
|
| 122 |
+
|
| 123 |
+
self._next_id = 0
|
| 124 |
+
|
| 125 |
+
def next_id(self): # β Add this method
|
| 126 |
+
self._next_id += 1
|
| 127 |
+
return self._next_id
|
| 128 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 129 |
+
def _init_agents(self):
|
| 130 |
+
uid = 0
|
| 131 |
+
# Receptor A
|
| 132 |
+
for _ in range(self.n_receptor_a):
|
| 133 |
+
x = random.uniform(0, self.space_size)
|
| 134 |
+
rec = ReceptorAgent(uid, self, "A")
|
| 135 |
+
self.space.place_agent(rec, (x, self.membrane_y))
|
| 136 |
+
self.agents.add(rec)
|
| 137 |
+
|
| 138 |
+
# Receptor B
|
| 139 |
+
for _ in range(self.n_receptor_b):
|
| 140 |
+
x = random.uniform(0, self.space_size)
|
| 141 |
+
rec = ReceptorAgent(uid, self, "B")
|
| 142 |
+
self.space.place_agent(rec, (x, self.membrane_y))
|
| 143 |
+
self.agents.add(rec)
|
| 144 |
+
|
| 145 |
+
# Antibodies
|
| 146 |
+
for _ in range(self.n_antibodies):
|
| 147 |
+
x = random.uniform(0, self.space_size)
|
| 148 |
+
y = random.uniform(self.membrane_y, self.space_size)
|
| 149 |
+
ab = AntibodyAgent(uid, self)
|
| 150 |
+
self.space.place_agent(ab, (x, y))
|
| 151 |
+
self.agents.add(ab)
|
| 152 |
+
|
| 153 |
+
def _adaptive_substeps(self) -> int:
|
| 154 |
+
"""
|
| 155 |
+
Return the smallest positive integer n such that, if we subdivide
|
| 156 |
+
the macro-step self.dt into n micro-steps, every *binding* and
|
| 157 |
+
*unbinding* probability is β€ P_MAX.
|
| 158 |
+
"""
|
| 159 |
+
# Worst unbinding probability anywhere
|
| 160 |
+
koff_max = max(self.koff_a, self.koff_b)
|
| 161 |
+
n_sub_off = math.ceil(koff_max * self.dt / P_MAX)
|
| 162 |
+
|
| 163 |
+
# Worst binding probability (scan antibodies)
|
| 164 |
+
n_sub_on = 1
|
| 165 |
+
for ab in (ag for ag in self.agents if isinstance(ag, AntibodyAgent)):
|
| 166 |
+
# new early exit for double bound antibodies - all off-rate dependant
|
| 167 |
+
if ab.n_bound == 2:
|
| 168 |
+
continue # no binding possible β skip
|
| 169 |
+
# new early-exit ---------------------------------------------------
|
| 170 |
+
reach = self.link_length if ab.n_bound else self.bind_radius
|
| 171 |
+
if ab.pos[1] - self.membrane_y > 2*reach: # too far above membrane
|
| 172 |
+
continue
|
| 173 |
+
# ------------------------------------------------------------------
|
| 174 |
+
# conservative upper bound: assume every compatible receptor
|
| 175 |
+
# in the lateral search strip is in range
|
| 176 |
+
r_search = self.link_length if ab.n_bound else self.bind_radius
|
| 177 |
+
frac_strip = 2 * r_search / self.space_size
|
| 178 |
+
n_cand_upper = math.ceil(
|
| 179 |
+
(self.n_receptor_a + self.n_receptor_b) * frac_strip
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
lamA = (
|
| 183 |
+
ab.kon_a * self.kon_factor * n_cand_upper
|
| 184 |
+
if ab.arm_state["A"] is None
|
| 185 |
+
else ab.koff_a
|
| 186 |
+
)
|
| 187 |
+
lamB = (
|
| 188 |
+
ab.kon_b * self.kon_factor * n_cand_upper
|
| 189 |
+
if ab.arm_state["B"] is None
|
| 190 |
+
else ab.koff_b
|
| 191 |
+
)
|
| 192 |
+
lam_tot = lamA + lamB
|
| 193 |
+
n_sub_on = max(n_sub_on, math.ceil(lam_tot * self.dt / P_MAX))
|
| 194 |
+
|
| 195 |
+
return max(1, n_sub_off, n_sub_on)
|
| 196 |
+
|
| 197 |
+
def _handle_antibody_entry_exit(self, dt_micro):
|
| 198 |
+
"""Poisson entry/exit for 2D model with effective depth."""
|
| 199 |
+
# --- Entry of antibodies ---
|
| 200 |
+
delta_reaction_zone = self.link_length * 2 # Β΅m β effective depth for concentration conversion
|
| 201 |
+
C_bulk_M = self.c_bulk # mol/L
|
| 202 |
+
|
| 203 |
+
# Volumetric concentration in molecules/Β΅mΒ³
|
| 204 |
+
C_bulk_vol_particles = C_bulk_M * AVOGADRO * 1e-15 # (1L = 1e15 Β΅mΒ³)
|
| 205 |
+
|
| 206 |
+
# Line flux density: D * C_volumetric (molecules / (Β΅m*s))
|
| 207 |
+
line_flux_density_in = self.d_ab * C_bulk_vol_particles
|
| 208 |
+
|
| 209 |
+
A_boundary_length = self.space_size # length of 1D "top boundary" in Β΅m
|
| 210 |
+
|
| 211 |
+
expected_incoming_count = line_flux_density_in * A_boundary_length * dt_micro
|
| 212 |
+
N_new = np.random.poisson(expected_incoming_count)
|
| 213 |
+
|
| 214 |
+
for _ in range(N_new):
|
| 215 |
+
x = random.uniform(0, self.space_size)
|
| 216 |
+
# Place new antibodies just inside the top boundary, within entry_height
|
| 217 |
+
y = self.space_size - random.uniform(1e-9, self.entry_height) # ensure y < self.space_size
|
| 218 |
+
ab = AntibodyAgent(self.next_id(), self) # Use model.next_id() for unique ID
|
| 219 |
+
self.space.place_agent(ab, (x, y))
|
| 220 |
+
self.agents.add(ab) # Add to custom agent scheduler/set
|
| 221 |
+
|
| 222 |
+
# --- Exit of antibodies ---
|
| 223 |
+
# Get unbound antibodies near the top boundary (in the exit zone)
|
| 224 |
+
exit_zone_abs = [
|
| 225 |
+
ag for ag in self.agents
|
| 226 |
+
if isinstance(ag, AntibodyAgent)
|
| 227 |
+
and ag.n_bound == 0
|
| 228 |
+
and ag.pos[1] >= self.space_size - self.exit_dist
|
| 229 |
+
]
|
| 230 |
+
|
| 231 |
+
current_N_in_exit_zone = len(exit_zone_abs)
|
| 232 |
+
|
| 233 |
+
if current_N_in_exit_zone > 0:
|
| 234 |
+
# Rate constant for a particle to diffuse out of the exit_dist layer (1/s)
|
| 235 |
+
# k_exit_particle = D / L^2
|
| 236 |
+
k_exit_per_particle = self.d_ab / (self.exit_dist ** 2)
|
| 237 |
+
|
| 238 |
+
# Mean number of particles exiting in dt_micro
|
| 239 |
+
lambda_poisson_exit = k_exit_per_particle * current_N_in_exit_zone * dt_micro
|
| 240 |
+
|
| 241 |
+
N_exit = np.random.poisson(lambda_poisson_exit)
|
| 242 |
+
# Ensure we don't try to remove more particles than available in the exit zone
|
| 243 |
+
N_exit = min(current_N_in_exit_zone, N_exit)
|
| 244 |
+
|
| 245 |
+
if N_exit > 0:
|
| 246 |
+
to_remove = random.sample(exit_zone_abs, N_exit)
|
| 247 |
+
for ag_to_remove in to_remove:
|
| 248 |
+
# It's good practice to ensure agent is still in collection if complex logic could remove it elsewhere,
|
| 249 |
+
# though with current structure, exit_zone_abs is fresh.
|
| 250 |
+
self.space.remove_agent(ag_to_remove) # Remove from space
|
| 251 |
+
self.agents.remove(ag_to_remove) # Remove from custom agent scheduler/set
|
| 252 |
+
|
| 253 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 254 |
+
def step(self):
|
| 255 |
+
n_sub = self._adaptive_substeps()
|
| 256 |
+
dt_micro = self.dt / n_sub
|
| 257 |
+
#print(f"New step size = {dt_micro}")
|
| 258 |
+
# Tell every agent the micro-timestep it must use this macro-tick
|
| 259 |
+
for ag in self.agents:
|
| 260 |
+
ag.dt = dt_micro # both antibodies & receptors
|
| 261 |
+
|
| 262 |
+
# Now advance the simulation in n_sub micro-steps
|
| 263 |
+
for _ in range(n_sub):
|
| 264 |
+
self.agents.shuffle().do("step")
|
| 265 |
+
self._handle_antibody_entry_exit(dt_micro)
|
ReceptorAgent.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import math
|
| 3 |
+
from typing import Optional, TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from mesa import Agent, Model
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING: # ONLY for the type checker
|
| 9 |
+
from AntibodyAgent import AntibodyAgent
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ReceptorAgent(Agent):
|
| 13 |
+
"""
|
| 14 |
+
A single membrane receptor diffusing along x (1-D).
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
uid : unique ID for Mesa
|
| 19 |
+
model : the HybridAvidityModel instance
|
| 20 |
+
rec_type : 'A' or 'B'
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, uid: int, model: Model, rec_type: str):
|
| 24 |
+
super().__init__(model)
|
| 25 |
+
self.rec_type = rec_type # 'A' or 'B'
|
| 26 |
+
self.bound_ab: Optional["AntibodyAgent"] = None
|
| 27 |
+
# self.legacy_id = uid
|
| 28 |
+
|
| 29 |
+
# Fast local refs to model-wide constants
|
| 30 |
+
self.space_size = model.space_size
|
| 31 |
+
self.membrane_y = model.membrane_y
|
| 32 |
+
self.d_rec = model.d_rec # receptor diffusion coefficient
|
| 33 |
+
self.dt = model.dt # integration timestep
|
| 34 |
+
|
| 35 |
+
# --------------------------------------------------------------------- #
|
| 36 |
+
# Agent behaviour #
|
| 37 |
+
# --------------------------------------------------------------------- #
|
| 38 |
+
def step(self):
|
| 39 |
+
"""
|
| 40 |
+
One Monte-Carlo step.
|
| 41 |
+
|
| 42 |
+
β’ If the receptor is bivalently bound, it performs a coupled random
|
| 43 |
+
walk with its partner receptor (distance held constant).
|
| 44 |
+
|
| 45 |
+
β’ Otherwise it diffuses freely along x (toroidal), fixed y.
|
| 46 |
+
"""
|
| 47 |
+
if self.bound_ab and self.bound_ab.n_bound == 2:
|
| 48 |
+
mate = next(r for r in self.bound_ab.arm_state.values() if r is not self)
|
| 49 |
+
|
| 50 |
+
# Joint Brownian step along x, keep inter-receptor distance
|
| 51 |
+
dx = np.random.normal(0.0, math.sqrt(2 * self.d_rec * self.dt))
|
| 52 |
+
for rec in (self, mate):
|
| 53 |
+
x_new = (rec.pos[0] + dx) % self.space_size
|
| 54 |
+
self.model.space.move_agent(rec, (x_new, self.membrane_y))
|
| 55 |
+
|
| 56 |
+
else:
|
| 57 |
+
dx = np.random.normal(0.0, math.sqrt(2 * self.d_rec * self.dt))
|
| 58 |
+
x_new = (self.pos[0] + dx) % self.space_size
|
| 59 |
+
self.model.space.move_agent(self, (x_new, self.membrane_y))
|
| 60 |
+
|
app.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import solara
|
| 2 |
+
import threading
|
| 3 |
+
import plotly.graph_objects as go
|
| 4 |
+
from HybridAvidityModel import HybridAvidityModel
|
| 5 |
+
|
| 6 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 7 |
+
# Default parameters
|
| 8 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 9 |
+
DT = 0.0001 # s
|
| 10 |
+
SPACE_SIZE = 10.0 # Β΅m
|
| 11 |
+
MEMBRANE_Y = 0.0
|
| 12 |
+
|
| 13 |
+
N_RECEPTOR_A = 50
|
| 14 |
+
N_RECEPTOR_B = 50
|
| 15 |
+
N_ANTIBODIES = 150
|
| 16 |
+
C_BULK = 50e-9 # mol/L = 50 nM
|
| 17 |
+
BOUNDARY_EXIT_DIST = 0.1 # Β΅m
|
| 18 |
+
BOUNDARY_ENTRY_DIST = 0.1
|
| 19 |
+
|
| 20 |
+
# Diffusion (Β΅mΒ² per DT)
|
| 21 |
+
D_REC = 5.0e-2
|
| 22 |
+
D_AB = 4.0e1
|
| 23 |
+
|
| 24 |
+
# Kinetics
|
| 25 |
+
KON_A, KOFF_A = 1e6, 1e-4
|
| 26 |
+
KON_B, KOFF_B = 1e6, 1e-4
|
| 27 |
+
|
| 28 |
+
BIND_RADIUS = 0.015 # Β΅m
|
| 29 |
+
LINK_LENGTH = 0.03 # Β΅m
|
| 30 |
+
|
| 31 |
+
RANDOM_SEED = 42
|
| 32 |
+
P_MAX = 0.10
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# βββ Reactive State βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 36 |
+
step_skip = solara.reactive(1)
|
| 37 |
+
model = solara.reactive(HybridAvidityModel())
|
| 38 |
+
step_counter = solara.reactive(0)
|
| 39 |
+
running = solara.reactive(False)
|
| 40 |
+
scatter_figure = solara.reactive(go.Figure())
|
| 41 |
+
bar_figure = solara.reactive(go.Figure())
|
| 42 |
+
# Reactive parameter bindings
|
| 43 |
+
kon_a = solara.reactive(KON_A)
|
| 44 |
+
koff_a = solara.reactive(KOFF_A)
|
| 45 |
+
kon_b = solara.reactive(KON_B)
|
| 46 |
+
koff_b = solara.reactive(KOFF_B)
|
| 47 |
+
n_receptor_a = solara.reactive(N_RECEPTOR_A)
|
| 48 |
+
n_receptor_b = solara.reactive(N_RECEPTOR_B)
|
| 49 |
+
n_antibodies = solara.reactive(N_ANTIBODIES)
|
| 50 |
+
computed_c_bulk = solara.reactive(0.0)
|
| 51 |
+
enable_binding_a = solara.reactive(True)
|
| 52 |
+
enable_binding_b = solara.reactive(True)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# βββ Plotting Logic βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 56 |
+
def render_plotly_snapshot(current_model, step_label):
|
| 57 |
+
rec_a_x, rec_a_y = [], []
|
| 58 |
+
rec_b_x, rec_b_y = [], []
|
| 59 |
+
agents = getattr(current_model, "agents", [])
|
| 60 |
+
# Compute receptor count here
|
| 61 |
+
total_receptors = sum(
|
| 62 |
+
1 for agent in agents if getattr(agent, "rec_type", None) in ("A", "B")
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
ab0_x, ab0_y = [], []
|
| 66 |
+
ab1_x, ab1_y = [], []
|
| 67 |
+
ab2_x, ab2_y = [], []
|
| 68 |
+
n0, n1, n2 = 0, 0, 0
|
| 69 |
+
|
| 70 |
+
for agent in agents:
|
| 71 |
+
if not hasattr(agent, "pos"):
|
| 72 |
+
continue
|
| 73 |
+
|
| 74 |
+
x, y = agent.pos
|
| 75 |
+
agent_type = getattr(agent, "rec_type", None)
|
| 76 |
+
|
| 77 |
+
if agent_type == "A":
|
| 78 |
+
rec_a_x.append(x)
|
| 79 |
+
rec_a_y.append(y)
|
| 80 |
+
elif agent_type == "B":
|
| 81 |
+
rec_b_x.append(x)
|
| 82 |
+
rec_b_y.append(y)
|
| 83 |
+
else:
|
| 84 |
+
n_bound = getattr(agent, "n_bound", 0)
|
| 85 |
+
if n_bound == 0:
|
| 86 |
+
ab0_x.append(x)
|
| 87 |
+
ab0_y.append(y)
|
| 88 |
+
n0 += 1
|
| 89 |
+
elif n_bound == 1:
|
| 90 |
+
ab1_x.append(x)
|
| 91 |
+
ab1_y.append(y)
|
| 92 |
+
n1 += 1
|
| 93 |
+
elif n_bound == 2:
|
| 94 |
+
ab2_x.append(x)
|
| 95 |
+
ab2_y.append(y)
|
| 96 |
+
n2 += 1
|
| 97 |
+
|
| 98 |
+
scatter_fig = go.Figure()
|
| 99 |
+
scatter_fig.add_trace(go.Scatter(
|
| 100 |
+
x=rec_a_x, y=rec_a_y,
|
| 101 |
+
mode='markers',
|
| 102 |
+
name="Receptor A",
|
| 103 |
+
marker=dict(symbol="hourglass", size=9, color="purple"),
|
| 104 |
+
showlegend=True
|
| 105 |
+
))
|
| 106 |
+
scatter_fig.add_trace(go.Scatter(
|
| 107 |
+
x=rec_b_x, y=rec_b_y,
|
| 108 |
+
mode='markers',
|
| 109 |
+
name="Receptor B",
|
| 110 |
+
marker=dict(symbol="diamond-tall", size=9, color="orange"),
|
| 111 |
+
showlegend=True
|
| 112 |
+
))
|
| 113 |
+
scatter_fig.add_trace(go.Scatter(
|
| 114 |
+
x=ab0_x if ab0_x else [None],
|
| 115 |
+
y=ab0_y if ab0_y else [None],
|
| 116 |
+
mode='markers',
|
| 117 |
+
name="Unbound Antibodies",
|
| 118 |
+
marker=dict(symbol="y-up", size=12, line = dict(width=4, color="DarkSlateGrey")),
|
| 119 |
+
showlegend=True
|
| 120 |
+
))
|
| 121 |
+
scatter_fig.add_trace(go.Scatter(
|
| 122 |
+
x=ab1_x if ab1_x else [None],
|
| 123 |
+
y=ab1_y if ab1_y else [None],
|
| 124 |
+
mode='markers',
|
| 125 |
+
name="Monovalent Antibodies",
|
| 126 |
+
marker=dict(symbol="y-up", size=14, line = dict(width=5, color="cyan")),
|
| 127 |
+
showlegend=True
|
| 128 |
+
))
|
| 129 |
+
scatter_fig.add_trace(go.Scatter(
|
| 130 |
+
x=ab2_x if ab2_x else [None],
|
| 131 |
+
y=ab2_y if ab2_y else [None],
|
| 132 |
+
mode='markers',
|
| 133 |
+
name="Bivalent Antibodies",
|
| 134 |
+
marker=dict(symbol="y-up", size=18, line = dict(width=6, color="Green")),
|
| 135 |
+
showlegend=True
|
| 136 |
+
))
|
| 137 |
+
|
| 138 |
+
n0, n1, n2 = 0, 0, 0
|
| 139 |
+
for agent in agents:
|
| 140 |
+
if hasattr(agent, "n_bound"):
|
| 141 |
+
if agent.n_bound == 0:
|
| 142 |
+
n0 += 1
|
| 143 |
+
elif agent.n_bound == 1:
|
| 144 |
+
n1 += 1
|
| 145 |
+
elif agent.n_bound == 2:
|
| 146 |
+
n2 += 1
|
| 147 |
+
|
| 148 |
+
bar_fig = go.Figure()
|
| 149 |
+
bar_fig.add_trace(go.Bar(
|
| 150 |
+
x=["Singly Bound", "Doubly Bound"],
|
| 151 |
+
y=[n1, n2]
|
| 152 |
+
))
|
| 153 |
+
|
| 154 |
+
# Calculate effective concentration of free antibodies
|
| 155 |
+
area = current_model.space_size ** 2 # Β΅mΒ²
|
| 156 |
+
depth_um = 0.06 # 60 nm in Β΅m
|
| 157 |
+
volume_liters = area * depth_um * 1e-15 # Β΅mΒ³ to L
|
| 158 |
+
avogadro_number = 6.022e23
|
| 159 |
+
concentration_nM = (n0 / (avogadro_number * volume_liters) * 1e9) if volume_liters > 0 else 0
|
| 160 |
+
|
| 161 |
+
# Calculate effective time
|
| 162 |
+
effective_time_sec = step_label * getattr(current_model, "dt", 1.0)
|
| 163 |
+
|
| 164 |
+
scatter_fig.update_layout(
|
| 165 |
+
title=(
|
| 166 |
+
f"Step {step_label} | "
|
| 167 |
+
f"Free Abs: {n0} | "
|
| 168 |
+
f"[Ab] β {concentration_nM:.2f} nM | "
|
| 169 |
+
f"Time β {effective_time_sec:.2f} s"
|
| 170 |
+
),
|
| 171 |
+
xaxis=dict(
|
| 172 |
+
title="X (Β΅m)",
|
| 173 |
+
range=[0, current_model.space_size],
|
| 174 |
+
showgrid=False,
|
| 175 |
+
showline=True, # Show x-axis line
|
| 176 |
+
mirror=True, # Mirror it on the top
|
| 177 |
+
linecolor='black',
|
| 178 |
+
linewidth=2
|
| 179 |
+
),
|
| 180 |
+
yaxis=dict(
|
| 181 |
+
title="Y (Β΅m)",
|
| 182 |
+
range=[-0.5, current_model.space_size],
|
| 183 |
+
showgrid=False,
|
| 184 |
+
showline=True, # Show y-axis line
|
| 185 |
+
mirror=True, # Mirror it on the right
|
| 186 |
+
linecolor='black',
|
| 187 |
+
linewidth=2
|
| 188 |
+
),
|
| 189 |
+
width=700,
|
| 190 |
+
height=700,
|
| 191 |
+
plot_bgcolor="gainsboro",
|
| 192 |
+
paper_bgcolor="whitesmoke",
|
| 193 |
+
legend=dict(
|
| 194 |
+
title="Agent Types",
|
| 195 |
+
x=1,
|
| 196 |
+
y=1,
|
| 197 |
+
xanchor="right",
|
| 198 |
+
yanchor="top",
|
| 199 |
+
bgcolor="rgba(255,255,255,0.85)" # white with 30% opacity
|
| 200 |
+
)
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
bar_fig = go.Figure()
|
| 204 |
+
bar_fig.add_trace(go.Bar(
|
| 205 |
+
x=["Singly Bound", "Doubly Bound"],
|
| 206 |
+
y=[n1 if n1 else 0, n2 if n2 else 0],
|
| 207 |
+
marker_color=["cyan", "green"]
|
| 208 |
+
))
|
| 209 |
+
|
| 210 |
+
bar_fig.update_layout(
|
| 211 |
+
title=f"Antibody Bound States @ Step {step_label}",
|
| 212 |
+
xaxis=dict(
|
| 213 |
+
title="Binding State",
|
| 214 |
+
showgrid=False,
|
| 215 |
+
showline=True,
|
| 216 |
+
mirror=True,
|
| 217 |
+
linecolor='black',
|
| 218 |
+
linewidth=2
|
| 219 |
+
),
|
| 220 |
+
yaxis=dict(
|
| 221 |
+
title="Count (antibodies)",
|
| 222 |
+
range=[0, total_receptors],
|
| 223 |
+
showgrid=False,
|
| 224 |
+
showline=True,
|
| 225 |
+
mirror=True,
|
| 226 |
+
linecolor='black',
|
| 227 |
+
linewidth=2
|
| 228 |
+
),
|
| 229 |
+
width=500,
|
| 230 |
+
height=500,
|
| 231 |
+
plot_bgcolor="gainsboro",
|
| 232 |
+
paper_bgcolor="whitesmoke"
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
return scatter_fig, bar_fig
|
| 236 |
+
|
| 237 |
+
def calculate_c_bulk(n_antibodies_value, space_size=SPACE_SIZE, depth_um=0.06):
|
| 238 |
+
volume_liters = space_size**2 * depth_um * 1e-15 # Β΅mΒ³ to L
|
| 239 |
+
avogadro_number = 6.022e23
|
| 240 |
+
return (n_antibodies_value / (avogadro_number * volume_liters))
|
| 241 |
+
|
| 242 |
+
def apply_system_settings():
|
| 243 |
+
computed_c_bulk.value = calculate_c_bulk(n_antibodies.value)
|
| 244 |
+
effective_kon_a = kon_a.value if enable_binding_a.value else 0.0
|
| 245 |
+
effective_koff_a = koff_a.value if enable_binding_a.value else 0.0
|
| 246 |
+
effective_kon_b = kon_b.value if enable_binding_b.value else 0.0
|
| 247 |
+
effective_koff_b = koff_b.value if enable_binding_b.value else 0.0
|
| 248 |
+
model.value = HybridAvidityModel(
|
| 249 |
+
n_receptor_a=n_receptor_a.value,
|
| 250 |
+
n_receptor_b=n_receptor_b.value,
|
| 251 |
+
n_antibodies=n_antibodies.value,
|
| 252 |
+
kon_a=effective_kon_a,
|
| 253 |
+
koff_a=effective_koff_a,
|
| 254 |
+
kon_b=effective_kon_b,
|
| 255 |
+
koff_b=effective_koff_b,
|
| 256 |
+
c_bulk=computed_c_bulk.value
|
| 257 |
+
)
|
| 258 |
+
step_counter.value = 0
|
| 259 |
+
scatter, bar = render_plotly_snapshot(model.value, step_counter.value)
|
| 260 |
+
scatter_figure.value = scatter
|
| 261 |
+
bar_figure.value = bar
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
# βββ Reset Logic βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 266 |
+
def reset_model():
|
| 267 |
+
model.value = HybridAvidityModel()
|
| 268 |
+
step_counter.value = 0
|
| 269 |
+
scatter, bar = render_plotly_snapshot(model.value, step_counter.value)
|
| 270 |
+
scatter_figure.value = scatter
|
| 271 |
+
bar_figure.value = bar
|
| 272 |
+
|
| 273 |
+
# βββ Simulation Step Logic βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 274 |
+
def step_model_actions():
|
| 275 |
+
if model.value is None:
|
| 276 |
+
print("Model is not initialized.")
|
| 277 |
+
return
|
| 278 |
+
|
| 279 |
+
for _ in range(step_skip.value):
|
| 280 |
+
model.value.step()
|
| 281 |
+
|
| 282 |
+
step_counter.value += step_skip.value
|
| 283 |
+
scatter_fig_new, bar_fig_new = render_plotly_snapshot(model.value, step_counter.value)
|
| 284 |
+
scatter_figure.value = scatter_fig_new
|
| 285 |
+
bar_figure.value = bar_fig_new
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# βββ Solara Page Component βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 289 |
+
@solara.component
|
| 290 |
+
def Page():
|
| 291 |
+
def initial_render():
|
| 292 |
+
if hasattr(model.value, 'agents') and model.value.agents:
|
| 293 |
+
scatter, bar = render_plotly_snapshot(model.value, step_counter.value)
|
| 294 |
+
scatter_figure.value = scatter
|
| 295 |
+
bar_figure.value = bar
|
| 296 |
+
else:
|
| 297 |
+
empty_scatter = go.Figure()
|
| 298 |
+
empty_scatter.update_layout(
|
| 299 |
+
title="Initializing...",
|
| 300 |
+
xaxis=dict(range=[0, model.value.space_size]),
|
| 301 |
+
yaxis=dict(range=[-1, model.value.space_size])
|
| 302 |
+
)
|
| 303 |
+
scatter_figure.value = empty_scatter
|
| 304 |
+
|
| 305 |
+
empty_bar = go.Figure()
|
| 306 |
+
empty_bar.update_layout(title="Initializing...")
|
| 307 |
+
bar_figure.value = empty_bar
|
| 308 |
+
|
| 309 |
+
solara.use_effect(initial_render, [])
|
| 310 |
+
|
| 311 |
+
timer_ref = solara.use_ref(None)
|
| 312 |
+
|
| 313 |
+
def loop():
|
| 314 |
+
if running.value:
|
| 315 |
+
step_model_actions()
|
| 316 |
+
timer_ref.current = threading.Timer(0.1, loop)
|
| 317 |
+
timer_ref.current.start()
|
| 318 |
+
|
| 319 |
+
def start_stop_loop():
|
| 320 |
+
if running.value:
|
| 321 |
+
loop()
|
| 322 |
+
else:
|
| 323 |
+
if timer_ref.current:
|
| 324 |
+
timer_ref.current.cancel()
|
| 325 |
+
timer_ref.current = None
|
| 326 |
+
|
| 327 |
+
solara.use_effect(start_stop_loop, [running.value])
|
| 328 |
+
|
| 329 |
+
def cleanup():
|
| 330 |
+
if timer_ref.current:
|
| 331 |
+
timer_ref.current.cancel()
|
| 332 |
+
|
| 333 |
+
solara.use_effect(lambda: cleanup, [])
|
| 334 |
+
with solara.Row(gap="20px", justify="left", style="margin-top: 20px;"):
|
| 335 |
+
with solara.Card("Controls", margin=1, elevation=2, style="width: 400px;"):
|
| 336 |
+
solara.Switch(label="Auto Run Simulation", value=running)
|
| 337 |
+
solara.SliderInt("Step size", value=step_skip, min=1, max=200)
|
| 338 |
+
solara.Markdown(f"**Current Step:** `{step_counter.value}`")
|
| 339 |
+
solara.Button("Step Model", on_click=step_model_actions, disabled=running.value, icon_name="mdi-run")
|
| 340 |
+
solara.Button("Reset Model", on_click=reset_model, icon_name="mdi-reload")
|
| 341 |
+
|
| 342 |
+
with solara.Card("System", margin=1, elevation=2, style="width: 400px;"):
|
| 343 |
+
with solara.Column(gap="10px"):
|
| 344 |
+
with solara.Row(justify="left"):
|
| 345 |
+
solara.Text("Receptor A", style={"min-width": "90px"})
|
| 346 |
+
solara.SliderInt(label="", value=n_receptor_a, min=0, max=200, step=1)
|
| 347 |
+
solara.Text(f"{n_receptor_a.value}", style={"min-width": "50px", "text-align": "right"})
|
| 348 |
+
|
| 349 |
+
with solara.Row(justify="left"):
|
| 350 |
+
solara.Text("Receptor B", style={"min-width": "90px"})
|
| 351 |
+
solara.SliderInt(label="", value=n_receptor_b, min=0, max=200, step=1)
|
| 352 |
+
solara.Text(f"{n_receptor_b.value}", style={"min-width": "50px", "text-align": "right"})
|
| 353 |
+
|
| 354 |
+
with solara.Row(justify="left"):
|
| 355 |
+
solara.Text("Antibodies", style={"min-width": "90px"})
|
| 356 |
+
solara.SliderInt(label="", value=n_antibodies, min=0, max=500, step=1)
|
| 357 |
+
solara.Text(f"{n_antibodies.value}", style={"min-width": "50px", "text-align": "right"})
|
| 358 |
+
with solara.Row(justify="left"):
|
| 359 |
+
solara.Markdown(f"**Calculated c_bulk:** `{calculate_c_bulk(n_antibodies.value) * 1e9:.2f} nM`")
|
| 360 |
+
solara.Button("Apply System Settings", on_click=apply_system_settings, icon_name="mdi-cogs")
|
| 361 |
+
|
| 362 |
+
with solara.Card("Antibody Kinetics", margin=1, elevation=2, style={"width": "400px"}):
|
| 363 |
+
solara.Text("on/off", style={"font-size": "12px", "font-weight": "normal", "color": "#666", "text-align": "right"})
|
| 364 |
+
# Receptor A
|
| 365 |
+
with solara.Row(justify="start", gap="10px"):
|
| 366 |
+
with solara.Column(style={"flex": "1"}):
|
| 367 |
+
with solara.Row(justify="center"):
|
| 368 |
+
solara.Text("kon_A (1/M/s)", style={"min-width": "100px"})
|
| 369 |
+
solara.SliderFloat(label="", value=kon_a, min=1e4, max=1e7, step=1e5,
|
| 370 |
+
disabled=not enable_binding_a.value)
|
| 371 |
+
solara.Text(f"{kon_a.value:.2e}", style={"min-width": "70px", "text-align": "right"})
|
| 372 |
+
with solara.Row(justify="center"):
|
| 373 |
+
solara.Text("koff_A (1/s)", style={"min-width": "100px"})
|
| 374 |
+
solara.SliderFloat(label="", value=koff_a, min=1e-5, max=1e-2, step=1e-5,
|
| 375 |
+
disabled=not enable_binding_a.value)
|
| 376 |
+
solara.Text(f"{koff_a.value:.2e}", style={"min-width": "70px", "text-align": "right"})
|
| 377 |
+
with solara.Column(
|
| 378 |
+
style={"width": "40px", "align-items": "flex-end", "justify-content": "center",
|
| 379 |
+
"flex-shrink": "0"}
|
| 380 |
+
):
|
| 381 |
+
solara.Checkbox(value=enable_binding_a)
|
| 382 |
+
|
| 383 |
+
# Receptor B
|
| 384 |
+
with solara.Row(justify="start", gap="10px"):
|
| 385 |
+
with solara.Column(style={"flex": "1"}):
|
| 386 |
+
with solara.Row(justify="center"):
|
| 387 |
+
solara.Text("kon_B (1/M/s)", style={"min-width": "100px"})
|
| 388 |
+
solara.SliderFloat(label="", value=kon_b, min=1e4, max=1e7, step=1e5,
|
| 389 |
+
disabled=not enable_binding_b.value)
|
| 390 |
+
solara.Text(f"{kon_b.value:.2e}", style={"min-width": "70px", "text-align": "right"})
|
| 391 |
+
with solara.Row(justify="center"):
|
| 392 |
+
solara.Text("koff_B (1/s)", style={"min-width": "100px"})
|
| 393 |
+
solara.SliderFloat(label="", value=koff_b, min=1e-5, max=1e-2, step=1e-5,
|
| 394 |
+
disabled=not enable_binding_b.value)
|
| 395 |
+
solara.Text(f"{koff_b.value:.2e}", style={"min-width": "70px", "text-align": "right"})
|
| 396 |
+
with solara.Column(
|
| 397 |
+
style={"width": "40px", "align-items": "flex-end", "justify-content": "center",
|
| 398 |
+
"flex-shrink": "0"}
|
| 399 |
+
):
|
| 400 |
+
solara.Checkbox(value=enable_binding_b)
|
| 401 |
+
|
| 402 |
+
# Button
|
| 403 |
+
with solara.Row(justify="start"):
|
| 404 |
+
solara.Button("Apply Kinetics", on_click=apply_system_settings, icon_name="mdi-check",
|
| 405 |
+
style={"width": "100%"})
|
| 406 |
+
|
| 407 |
+
with solara.Row(gap="20px", justify="left", style="margin-top: 20px;"):
|
| 408 |
+
with solara.Card(elevation=2):
|
| 409 |
+
solara.FigurePlotly(scatter_figure.value)
|
| 410 |
+
with solara.Card(elevation=2):
|
| 411 |
+
solara.FigurePlotly(bar_figure.value)
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Core packages
|
| 2 |
+
solara
|
| 3 |
+
plotly
|
| 4 |
+
numpy
|
| 5 |
+
mesa
|
| 6 |
+
|