AvidityLab / app.py
Daniel Holdbrook
dash updates
f422c70
Raw History Blame Contribute Delete
19.4 kB
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)