File size: 7,824 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
import math, random
from typing import Dict, Optional

import numpy as np
from mesa import Agent, Model
from ReceptorAgent import ReceptorAgent


class AntibodyAgent(Agent):
    """
    Bispecific antibody with two arms (A binds Rec-A, B binds Rec-B).

    – Uses one Poisson clock per antibody.
    – Expects kon_a / kon_b in M⁻¹ s⁻¹, koff_a / koff_b in s⁻¹.
    – model.dt is the *micro-step* chosen by your adaptive driver.
    """

    # ------------------------------------------------------------------ #
    #  Construction                                                      #
    # ------------------------------------------------------------------ #
    def __init__(self, uid: int, model: Model):
        super().__init__(model)
        self.arm_state: Dict[str, Optional[ReceptorAgent]] = {"A": None, "B": None}

        # cached model constants
        self.space_size   = model.space_size
        self.membrane_y   = model.membrane_y
        self.d_ab         = model.d_ab      # µm² s⁻¹
        self.link_length  = model.link_length
        self.bind_radius  = model.bind_radius

        # kinetics (physical units)
        self.kon_a        = model.kon_a     # M⁻¹ s⁻¹
        self.kon_b        = model.kon_b
        self.koff_a       = model.koff_a    # s⁻¹
        self.koff_b       = model.koff_b
        self.kon_factor   = model.kon_factor  # 1 / (N_A V_eff)

        # will be overwritten each macro-step by the driver
        self.dt           = model.dt

    # ------------------------------------------------------------------ #
    #  Derived state                                                     #
    # ------------------------------------------------------------------ #
    @property
    def n_bound(self) -> int:
        return sum(rec is not None for rec in self.arm_state.values())

    # ------------------------------------------------------------------ #
    #  Core step                                                         #
    # ------------------------------------------------------------------ #
    def step(self):
        """Move first, then allow *one* event (bind OR unbind)."""
        self._move()
        self._attempt_state_change()

    # ------------------------------------------------------------------ #
    #  Movement (unchanged)                                              #
    # ------------------------------------------------------------------ #
    def _move(self):
        if self.n_bound == 0:
            self._diffuse_free()
        else:
            self._tether_to_receptors()

    def _diffuse_free(self):
        sigma = math.sqrt(2 * self.d_ab * self.dt)
        dx, dy = np.random.normal(0.0, sigma, 2)

        x_new = (self.pos[0] + dx) % self.space_size
        y_new = self.pos[1] + dy

        if y_new < self.membrane_y:
            y_new = self.membrane_y + (self.membrane_y - y_new)
        elif y_new > self.space_size:
            y_new = self.space_size - (y_new - self.space_size)

        self.model.space.move_agent(self, (x_new, y_new))

    def _tether_to_receptors(self):
        xs = [rec.pos[0] for rec in self.arm_state.values() if rec]
        ys = [rec.pos[1] for rec in self.arm_state.values() if rec]
        anchor_x, anchor_y = sum(xs) / len(xs), sum(ys) / len(ys)

        x_new = (anchor_x + np.random.normal(0.0, 0.01)) % self.space_size
        y_new = max(
            self.membrane_y,
            min(self.space_size, anchor_y + np.random.normal(0.0, 0.01)),
        )
        self.model.space.move_agent(self, (x_new, y_new))

    # ------------------------------------------------------------------ #
    #  One-draw Poisson kinetics                                         #
    # ------------------------------------------------------------------ #
    def _attempt_state_change(self):
        """At most ONE elementary bind/unbind event per micro-step."""
        channels = []                    # (label, λ_i) tuples

        # ---- binding channels -----------------------------------------
        if self.arm_state["A"] is None:
            nA = self._count_candidates("A")
            if nA:
                lam = self.kon_a * self.kon_factor * nA
                channels.append(("bind_A", lam))

        if self.arm_state["B"] is None:
            nB = self._count_candidates("B")
            if nB:
                lam = self.kon_b * self.kon_factor * nB
                channels.append(("bind_B", lam))

        # ---- unbinding channels ---------------------------------------
        if self.arm_state["A"] is not None:
            channels.append(("unbind_A", self.koff_a))

        if self.arm_state["B"] is not None:
            channels.append(("unbind_B", self.koff_b))

        if not channels:
            return                                        # nothing can happen

        λ_tot = sum(lam for _, lam in channels)
        p = 1.0 - math.exp(-λ_tot * self.dt)              # survival function

        if random.random() >= p:                          # no event this tick
            return

        # roulette selection of the firing channel
        r = random.random() * λ_tot
        acc = 0.0
        for label, lam in channels:
            acc += lam
            if r <= acc:
                if label == "bind_A":
                    rec = self._pick_random_candidate("A")
                    self._bind("A", rec)
                elif label == "bind_B":
                    rec = self._pick_random_candidate("B")
                    self._bind("B", rec)
                elif label == "unbind_A":
                    self._unbind("A")
                elif label == "unbind_B":
                    self._unbind("B")
                break

    # ------------------------------------------------------------------ #
    #  Candidate helpers                                                 #
    # ------------------------------------------------------------------ #
    def _count_candidates(self, arm: str) -> int:
        radius = self.link_length if self.n_bound else self.bind_radius
        height = self.link_length  # or set CAPTURE_HEIGHT explicitly

        rec_type = "A" if arm == "A" else "B"

        # Only proceed if antibody is close enough vertically
        if abs(self.pos[1] - self.model.membrane_y) > height:
            return 0

        # Temporarily "project" to y = 0
        projected_pos = (self.pos[0], self.model.membrane_y)

        neighbors = self.model.space.get_neighbors(projected_pos, radius, include_center=False)

        return sum(
            isinstance(n, ReceptorAgent)
            and n.rec_type == rec_type
            and n.bound_ab is None
            for n in neighbors
        )

    def _pick_random_candidate(self, arm: str) -> ReceptorAgent:
        radius   = self.link_length if self.n_bound else self.bind_radius
        rec_type = "A" if arm == "A" else "B"
        # Temporarily "project" to y = 0
        projected_pos = (self.pos[0], self.model.membrane_y)
        neighbors = self.model.space.get_neighbors(projected_pos, radius, include_center=False)
        pool = [
            n
            for n in neighbors
            if isinstance(n, ReceptorAgent)
            and n.rec_type == rec_type
            and n.bound_ab is None
        ]
        return random.choice(pool)

    # ------------------------------------------------------------------ #
    #  Book-keeping helpers                                              #
    # ------------------------------------------------------------------ #
    def _bind(self, arm: str, receptor: ReceptorAgent):
        self.arm_state[arm] = receptor
        receptor.bound_ab   = self

    def _unbind(self, arm: str):
        rec = self.arm_state[arm]
        if rec:
            rec.bound_ab = None
        self.arm_state[arm] = None