File size: 19,428 Bytes
4e16dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efd9eee
 
4e16dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efd9eee
4e16dd3
efd9eee
 
 
4e16dd3
 
 
 
 
 
efd9eee
4e16dd3
efd9eee
4e16dd3
 
efd9eee
4e16dd3
 
 
 
 
 
 
 
 
 
 
 
efd9eee
 
 
 
 
 
4e16dd3
 
 
 
 
efd9eee
 
 
 
 
 
 
 
 
 
 
 
 
4e16dd3
efd9eee
 
 
4e16dd3
efd9eee
 
 
4e16dd3
 
efd9eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e16dd3
efd9eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e16dd3
 
efd9eee
 
4e16dd3
 
 
 
efd9eee
 
 
 
 
4e16dd3
 
 
 
efd9eee
4e16dd3
 
efd9eee
4e16dd3
efd9eee
 
 
4e16dd3
 
efd9eee
 
 
 
4e16dd3
 
 
 
 
 
efd9eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e16dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efd9eee
4e16dd3
 
efd9eee
4e16dd3
 
 
 
 
efd9eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e16dd3
 
efd9eee
 
 
 
 
4e16dd3
 
efd9eee
4e16dd3
 
 
 
 
 
 
 
 
 
 
efd9eee
4e16dd3
 
efd9eee
4e16dd3
 
 
 
 
 
 
efd9eee
4e16dd3
 
efd9eee
4e16dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f422c70
4e16dd3
 
 
 
 
 
f422c70
4e16dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f422c70
4e16dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efd9eee
4e16dd3
efd9eee
 
 
 
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import solara
import threading
import plotly.graph_objects as go
from HybridAvidityModel import HybridAvidityModel

# ───────────────────────────────────────────────────────────────────────────────
# Default parameters
# ───────────────────────────────────────────────────────────────────────────────
DT = 0.0001  # 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

RANDOM_SEED  = 42
P_MAX        = 0.10


# ─── Reactive State ───────────────────────────────────────────────────────────
step_skip = solara.reactive(1)
model = solara.reactive(HybridAvidityModel())
step_counter = solara.reactive(0)
running = solara.reactive(False)
scatter_figure = solara.reactive(go.Figure())
bar_figure = solara.reactive(go.Figure())
line_figure = solara.reactive(go.Figure())
binding_history = solara.reactive([])
# Reactive parameter bindings
kon_a = solara.reactive(KON_A)
koff_a = solara.reactive(KOFF_A)
kon_b = solara.reactive(KON_B)
koff_b = solara.reactive(KOFF_B)
n_receptor_a = solara.reactive(N_RECEPTOR_A)
n_receptor_b = solara.reactive(N_RECEPTOR_B)
n_antibodies = solara.reactive(N_ANTIBODIES)
computed_c_bulk = solara.reactive(0.0)
enable_binding_a = solara.reactive(True)
enable_binding_b = solara.reactive(True)


# ─── Plotting Logic ───────────────────────────────────────────────────────────
def render_plotly_snapshot(current_model, step_label):
    rec_a_x, rec_a_y = [], []
    rec_b_x, rec_b_y = [], []
    ab0_x, ab0_y = [], []
    ab1_x, ab1_y = [], []
    ab2_x, ab2_y = [], []

    n0, n1, n2 = 0, 0, 0
    n1_a, n1_b = 0, 0  # NEW: singly bound to A vs B
    agents = getattr(current_model, "agents", [])
    total_receptors = sum(1 for agent in agents if getattr(agent, "rec_type", None) in ("A", "B"))

    for agent in agents:
        if not hasattr(agent, "pos"):
            continue

        x, y = agent.pos
        rec_type = getattr(agent, "rec_type", None)

        if rec_type == "A":
            rec_a_x.append(x)
            rec_a_y.append(y)
        elif rec_type == "B":
            rec_b_x.append(x)
            rec_b_y.append(y)
        else:
            n_bound = getattr(agent, "n_bound", 0)
            if n_bound == 0:
                ab0_x.append(x)
                ab0_y.append(y)
                n0 += 1
            elif n_bound == 1:
                ab1_x.append(x)
                ab1_y.append(y)
                n1 += 1
                # Identify which arm is bound
                arm_state = getattr(agent, "arm_state", {})
                if arm_state.get("A") is not None:
                    n1_a += 1
                elif arm_state.get("B") is not None:
                    n1_b += 1
            elif n_bound == 2:
                ab2_x.append(x)
                ab2_y.append(y)
                n2 += 1

    # ─── Line chart data update ─────────────────────────────────────────────
    current_time = step_label * current_model.dt
    binding_history.value.append((current_time, n1, n2, n1_a, n1_b))
    times = [t for t, *_ in binding_history.value]
    singly = [s for _, s, *_ in binding_history.value]
    doubly = [d for _, _, d, *_ in binding_history.value]
    singly_a = [a for *_, a, _ in binding_history.value]
    singly_b = [b for *_, _, b in binding_history.value]

    line_fig = go.Figure()
    line_fig.add_trace(go.Scatter(
        x=times, y=singly_a, mode='lines+markers', name='Singly Bound A',
        line=dict(color='purple')
    ))
    line_fig.add_trace(go.Scatter(
        x=times, y=singly_b, mode='lines+markers', name='Singly Bound B',
        line=dict(color='orange')
    ))
    line_fig.add_trace(go.Scatter(
        x=times, y=doubly, mode='lines+markers', name='Doubly Bound',
        line=dict(color='green')
    ))

    line_fig.update_layout(
        title="Receptor Binding Over Time",
        xaxis=dict(
            title="Time (s)",
            range=[0, current_time],  # Start at 0, end at current time
            zeroline=True,
            showline=True,
            linecolor='black'
        ),
        yaxis=dict(
            title="Number of Bound Antibodies",
            range=[0, max(max(singly + [0]), max(doubly + [0]), 1)],  # Start at 0, auto upper bound
            zeroline=True,
            showline=True,
            linecolor='black'
        ),
        width=500,
        height=500,
        plot_bgcolor="gainsboro",
        paper_bgcolor="whitesmoke",
        legend=dict(x=0.01, y=0.99)
    )

    line_figure.value = line_fig

    # ─── Scatter plot ───────────────────────────────────────────────────────
    scatter_fig = go.Figure()
    scatter_fig.add_trace(go.Scatter(x=rec_a_x, y=rec_a_y, mode='markers', name="Receptor A",
                                     marker=dict(symbol="hourglass", size=9, color="purple")))
    scatter_fig.add_trace(go.Scatter(x=rec_b_x, y=rec_b_y, mode='markers', name="Receptor B",
                                     marker=dict(symbol="diamond-tall", size=9, color="orange")))
    scatter_fig.add_trace(go.Scatter(x=ab0_x or [None], y=ab0_y or [None], mode='markers',
                                     name="Unbound Antibodies",
                                     marker=dict(symbol="y-up", size=12, line=dict(width=4, color="DarkSlateGrey"))))
    scatter_fig.add_trace(go.Scatter(x=ab1_x or [None], y=ab1_y or [None], mode='markers',
                                     name="Monovalent Antibodies",
                                     marker=dict(symbol="y-up", size=14, line=dict(width=5, color="cyan"))))
    scatter_fig.add_trace(go.Scatter(x=ab2_x or [None], y=ab2_y or [None], mode='markers',
                                     name="Bivalent Antibodies",
                                     marker=dict(symbol="y-up", size=18, line=dict(width=6, color="Green"))))

    area = current_model.space_size ** 2  # Β΅mΒ²
    depth_um = 0.06  # Β΅m
    volume_liters = area * depth_um * 1e-15
    avogadro_number = 6.022e23
    concentration_nM = (n0 / (avogadro_number * volume_liters) * 1e9) if volume_liters > 0 else 0

    scatter_fig.update_layout(
        title=(f"Step {step_label} | Free Abs: {n0} | [Ab] β‰ˆ {concentration_nM:.2f} nM | Time β‰ˆ {current_time:.2f} s"),
        xaxis=dict(title="X (Β΅m)", range=[0, current_model.space_size], showgrid=False, showline=True, mirror=True,
                   linecolor='black', linewidth=2),
        yaxis=dict(title="Y (Β΅m)", range=[-0.5, current_model.space_size], showgrid=False, showline=True, mirror=True,
                   linecolor='black', linewidth=2),
        width=700,
        height=700,
        plot_bgcolor="gainsboro",
        paper_bgcolor="whitesmoke",
        legend=dict(title="Agent Types", x=1, y=1, xanchor="right", yanchor="top", bgcolor="rgba(255,255,255,0.85)")
    )

    # ─── Bar plot ────────────────────────────────────────────────────────────
    bar_fig = go.Figure()
    bar_fig.add_trace(go.Bar(x=["Singly Bound", "Doubly Bound"],
                             y=[n1, n2],
                             marker_color=["cyan", "green"]))
    bar_fig.update_layout(
        title=f"Antibody Bound States @ Step {step_label}",
        xaxis=dict(title="Binding State", showgrid=False, showline=True, mirror=True,
                   linecolor='black', linewidth=2),
        yaxis=dict(title="Count (antibodies)", range=[0, total_receptors], showgrid=False, showline=True,
                   mirror=True, linecolor='black', linewidth=2),
        width=500,
        height=500,
        plot_bgcolor="gainsboro",
        paper_bgcolor="whitesmoke"
    )

    return scatter_fig, bar_fig, line_fig

def update_line_figure(n1, n2):
    current_time = step_counter.value * model.value.dt
    binding_history.value.append((current_time, n1, n2))

    # Extract data for plotting
    times = [t for t, _, _ in binding_history.value]
    singly = [s for _, s, _ in binding_history.value]
    doubly = [d for _, _, d in binding_history.value]

    # Create the line figure
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=times, y=singly, mode='lines+markers', name='Singly Bound'))
    fig.add_trace(go.Scatter(x=times, y=doubly, mode='lines+markers', name='Doubly Bound'))

    fig.update_layout(
        title="Receptor Binding Over Time",
        xaxis_title="Time (s)",
        yaxis_title="Number of Bound Antibodies",
        width=700,
        height=400,
        plot_bgcolor="gainsboro",
        paper_bgcolor="whitesmoke",
        legend=dict(x=0.01, y=0.99)
    )

    line_figure.value = fig


def calculate_c_bulk(n_antibodies_value, space_size=SPACE_SIZE, depth_um=0.06):
    volume_liters = space_size**2 * depth_um * 1e-15  # Β΅mΒ³ to L
    avogadro_number = 6.022e23
    return (n_antibodies_value / (avogadro_number * volume_liters))

def apply_system_settings():
    computed_c_bulk.value = calculate_c_bulk(n_antibodies.value)
    effective_kon_a = kon_a.value if enable_binding_a.value else 0.0
    effective_koff_a = koff_a.value if enable_binding_a.value else 0.0
    effective_kon_b = kon_b.value if enable_binding_b.value else 0.0
    effective_koff_b = koff_b.value if enable_binding_b.value else 0.0
    model.value = HybridAvidityModel(
        n_receptor_a=n_receptor_a.value,
        n_receptor_b=n_receptor_b.value,
        n_antibodies=n_antibodies.value,
        kon_a=effective_kon_a,
        koff_a=effective_koff_a,
        kon_b=effective_kon_b,
        koff_b=effective_koff_b,
        c_bulk=computed_c_bulk.value
    )
    step_counter.value = 0
    scatter, bar, line = render_plotly_snapshot(model.value, step_counter.value)
    scatter_figure.value = scatter
    bar_figure.value = bar
    line_figure.value = line



# ─── Reset Logic ─────────────────────────────────────────────────────
def reset_model():
    # Reset all user-editable settings to defaults
    n_receptor_a.value = N_RECEPTOR_A
    n_receptor_b.value = N_RECEPTOR_B
    n_antibodies.value = N_ANTIBODIES
    kon_a.value = KON_A
    koff_a.value = KOFF_A
    kon_b.value = KON_B
    koff_b.value = KOFF_B
    enable_binding_a.value = True
    enable_binding_b.value = True
    step_skip.value = 1

    # Recalculate c_bulk based on default values
    computed_c_bulk.value = calculate_c_bulk(N_ANTIBODIES)

    # Reset simulation state
    model.value = HybridAvidityModel()
    step_counter.value = 0
    binding_history.value = []
    line_figure.value = go.Figure()

    # Render default plots
    scatter, bar, line = render_plotly_snapshot(model.value, step_counter.value)
    scatter_figure.value = scatter
    bar_figure.value = bar
    line_figure.value = line

# ─── Simulation Step Logic ─────────────────────────────────────────────────────
def step_model_actions():
    if model.value is None:
        print("Model is not initialized.")
        return

    for _ in range(step_skip.value):
        model.value.step()

    step_counter.value += step_skip.value
    scatter_fig_new, bar_fig_new, line_fig_new = render_plotly_snapshot(model.value, step_counter.value)
    scatter_figure.value = scatter_fig_new
    bar_figure.value = bar_fig_new
    line_figure.value = line_fig_new


# ─── Solara Page Component ─────────────────────────────────────────────────────
@solara.component
def Page():
    def initial_render():
        if hasattr(model.value, 'agents') and model.value.agents:
            scatter, bar, line_fig_new = render_plotly_snapshot(model.value, step_counter.value)
            scatter_figure.value = scatter
            bar_figure.value = bar
            line_figure.value = line_fig_new
        else:
            empty_scatter = go.Figure()
            empty_scatter.update_layout(
                title="Initializing...",
                xaxis=dict(range=[0, model.value.space_size]),
                yaxis=dict(range=[-1, model.value.space_size])
            )
            scatter_figure.value = empty_scatter

            empty_bar = go.Figure()
            empty_bar.update_layout(title="Initializing...")
            bar_figure.value = empty_bar

    solara.use_effect(initial_render, [])

    timer_ref = solara.use_ref(None)

    def loop():
        if running.value:
            step_model_actions()
            timer_ref.current = threading.Timer(0.1, loop)
            timer_ref.current.start()

    def start_stop_loop():
        if running.value:
            loop()
        else:
            if timer_ref.current:
                timer_ref.current.cancel()
                timer_ref.current = None

    solara.use_effect(start_stop_loop, [running.value])

    def cleanup():
        if timer_ref.current:
            timer_ref.current.cancel()

    solara.use_effect(lambda: cleanup, [])
    with solara.Row(gap="20px", justify="left", style="margin-top: 20px;"):
        with solara.Card("Controls", margin=1, elevation=2, style="width: 415px;"):
            solara.Switch(label="Auto Run Simulation", value=running)
            solara.SliderInt("Step size", value=step_skip, min=1, max=200)
            solara.Markdown(f"**Current Step:** `{step_counter.value}`")
            solara.Button("Step Model", on_click=step_model_actions, disabled=running.value, icon_name="mdi-run")
            solara.Button("Reset Model", on_click=reset_model, icon_name="mdi-reload")

        with solara.Card("System", margin=1, elevation=2, style="width: 415px;"):
            with solara.Column(gap="10px"):
                with solara.Row(justify="left"):
                    solara.Text("Receptor A", style={"min-width": "90px"})
                    solara.SliderInt(label="", value=n_receptor_a, min=0, max=200, step=1)
                    solara.Text(f"{n_receptor_a.value}", style={"min-width": "50px", "text-align": "right"})

                with solara.Row(justify="left"):
                    solara.Text("Receptor B", style={"min-width": "90px"})
                    solara.SliderInt(label="", value=n_receptor_b, min=0, max=200, step=1)
                    solara.Text(f"{n_receptor_b.value}", style={"min-width": "50px", "text-align": "right"})

                with solara.Row(justify="left"):
                    solara.Text("Antibodies", style={"min-width": "90px"})
                    solara.SliderInt(label="", value=n_antibodies, min=0, max=500, step=1)
                    solara.Text(f"{n_antibodies.value}", style={"min-width": "50px", "text-align": "right"})
                with solara.Row(justify="left"):
                    solara.Markdown(f"**Calculated c_bulk:** `{calculate_c_bulk(n_antibodies.value) * 1e9:.2f} nM`")
                solara.Button("Apply System Settings", on_click=apply_system_settings, icon_name="mdi-cogs")

        with solara.Card("Antibody Kinetics", margin=1, elevation=2, style={"width": "415px"}):
            solara.Text("on/off", style={"font-size": "12px", "font-weight": "normal", "color": "#666", "text-align": "right"})
            # Receptor A
            with solara.Row(justify="start", gap="10px"):
                with solara.Column(style={"flex": "1"}):
                    with solara.Row(justify="center"):
                        solara.Text("kon_A (1/M/s)", style={"min-width": "100px"})
                        solara.SliderFloat(label="", value=kon_a, min=1e4, max=1e7, step=1e5,
                                           disabled=not enable_binding_a.value)
                        solara.Text(f"{kon_a.value:.2e}", style={"min-width": "70px", "text-align": "right"})
                    with solara.Row(justify="center"):
                        solara.Text("koff_A (1/s)", style={"min-width": "100px"})
                        solara.SliderFloat(label="", value=koff_a, min=1e-5, max=1e-2, step=1e-5,
                                           disabled=not enable_binding_a.value)
                        solara.Text(f"{koff_a.value:.2e}", style={"min-width": "70px", "text-align": "right"})
                with solara.Column(
                        style={"width": "40px", "align-items": "flex-end", "justify-content": "center",
                               "flex-shrink": "0"}
                ):
                    solara.Checkbox(value=enable_binding_a)

            # Receptor B
            with solara.Row(justify="start", gap="10px"):
                with solara.Column(style={"flex": "1"}):
                    with solara.Row(justify="center"):
                        solara.Text("kon_B (1/M/s)", style={"min-width": "100px"})
                        solara.SliderFloat(label="", value=kon_b, min=1e4, max=1e7, step=1e5,
                                           disabled=not enable_binding_b.value)
                        solara.Text(f"{kon_b.value:.2e}", style={"min-width": "70px", "text-align": "right"})
                    with solara.Row(justify="center"):
                        solara.Text("koff_B (1/s)", style={"min-width": "100px"})
                        solara.SliderFloat(label="", value=koff_b, min=1e-5, max=1e-2, step=1e-5,
                                           disabled=not enable_binding_b.value)
                        solara.Text(f"{koff_b.value:.2e}", style={"min-width": "70px", "text-align": "right"})
                with solara.Column(
                        style={"width": "40px", "align-items": "flex-end", "justify-content": "center",
                               "flex-shrink": "0"}
                ):
                    solara.Checkbox(value=enable_binding_b)

            # Button
            with solara.Row(justify="start"):
                solara.Button("Apply Kinetics", on_click=apply_system_settings, icon_name="mdi-check",
                              style={"width": "100%"})

    with solara.Row(gap="20px", justify="left", style="margin-top: 20px;"):
        with solara.Card(elevation=2):
            solara.FigurePlotly(scatter_figure.value)

        with solara.Card(elevation=2):
            with solara.Column():
                solara.FigurePlotly(bar_figure.value)
                solara.FigurePlotly(line_figure.value)