Skip to content

Commit fa0d149

Browse files
committed
[Iter 4] Code modification in PDE_D_ThresholdCoupling.py
[Automated commit by Claude]
1 parent 186e562 commit fa0d149

1 file changed

Lines changed: 276 additions & 0 deletions

File tree

Lines changed: 276 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
1+
import torch
2+
import torch_geometric as pyg
3+
import torch_geometric.utils as pyg_utils
4+
from ParticleGraph.utils import to_numpy
5+
6+
class PDE_D_ThresholdCoupling(pyg.nn.MessagePassing):
7+
"""
8+
Concentration-threshold coupling (CTC) bistable particle model.
9+
10+
Particles are attracted to concentration gradients below a threshold T
11+
and repelled above it, creating an attractor at the C1=T isoline.
12+
With multi-type particles, each type can have a different threshold,
13+
producing nested ring structures.
14+
15+
Literature:
16+
- Wolpert, L. (1969) J Theor Biol 25:1-47
17+
"Positional information and the spatial pattern of cellular differentiation"
18+
- Meinhardt, H. & Gierer, A. (1974) J Cell Sci 15:321-346
19+
"Threshold-dependent response to morphogen gradients"
20+
- Dessaud, E. et al. (2008) Development 135:2489-2503
21+
"Graded Sonic Hedgehog signaling via concentration thresholds in neural tube"
22+
23+
Physics:
24+
sign_factor = -tanh(steepness * (C1 - T) / A)
25+
Below T (C1 < T): sign_factor > 0, gradient-following (attracted to peaks)
26+
Above T (C1 > T): sign_factor < 0, gradient-reversed (repelled from peaks)
27+
At C1 = T: sign_factor = 0, zero net mobility (attractor isoline)
28+
29+
Per-type thresholds: T_type = base_T * (1 + cross_type_factor * (type_idx - mean_idx))
30+
31+
Per-type params layout: [M1, M2, consumption, production, ar_p1, ar_p2, ar_p3, ar_p4]
32+
"""
33+
34+
PARAMS_DOC = {
35+
"model_name": "ThresholdCoupling",
36+
"literature": "Wolpert (1969) J Theor Biol 25:1-47; Dessaud et al. (2008) Development 135:2489",
37+
"description": "Bistable concentration-threshold coupling with per-type thresholds",
38+
"equations": {
39+
"field_to_particle": "v = M * grad_C * (-tanh(3*(C1-T)/A)); T = ctc_threshold * A",
40+
"particle_to_field": "dC1 = -consumption * w(r), dC2 = production * w(r)",
41+
"particle_to_particle": "f = (p1*exp(-d^(2p2)/(2sigma^2)) - p3*exp(-d^(2p4)/(2sigma^2))) * dir"
42+
},
43+
"params_mesh": [
44+
{
45+
"row": 0, "description": "C1 field parameters (shared with mesh model) + CTC threshold",
46+
"slots": [
47+
{"index": 0, "name": "D1", "description": "Diffusion coeff for C1 (mesh model)", "typical_range": [0.01, 0.5]},
48+
{"index": 1, "name": "Da_c", "description": "Damkohler number (mesh model)", "typical_range": [1.0, 50.0]},
49+
{"index": 2, "name": "A", "description": "Brusselator param A (mesh model, also CTC reference)", "typical_range": [0.5, 5.0]},
50+
{"index": 3, "name": "B", "description": "Brusselator param B (mesh model)", "typical_range": [1.0, 10.0]},
51+
{"index": 4, "name": "mu", "description": "Morphological parameter (mesh model)", "typical_range": [0.01, 0.1]},
52+
{"index": 5, "name": "M1", "description": "Mobility coefficient for C1 gradients", "typical_range": [-16, 16]},
53+
{"index": 6, "name": "unused", "description": "Unused (pad)", "typical_range": [0.0, 0.0]},
54+
{"index": 7, "name": "ctc_threshold", "description": "CTC threshold (T=ctc*A; reversal at C1=T)", "typical_range": [0.5, 3.0]}
55+
]
56+
},
57+
{
58+
"row": 1, "description": "C2 field parameters",
59+
"slots": [
60+
{"index": 0, "name": "D2", "description": "Diffusion coeff for C2 (mesh model)", "typical_range": [0.1, 1.0]},
61+
{"index": 1, "name": "M2", "description": "Mobility coefficient for C2 gradients", "typical_range": [-16, 16]}
62+
]
63+
},
64+
{
65+
"row": 2, "description": "Particle-field coupling + per-type threshold spread",
66+
"slots": [
67+
{"index": 0, "name": "Pe", "description": "Peclet number", "typical_range": [0.5, 2.0]},
68+
{"index": 1, "name": "consumption", "description": "Particle consumption rate of C1", "typical_range": [10, 200]},
69+
{"index": 2, "name": "production", "description": "Particle production rate of C2", "typical_range": [-200, -10]},
70+
{"index": 3, "name": "influence_radius", "description": "Gaussian influence radius for pf coupling", "typical_range": [0.01, 0.1]},
71+
{"index": 4, "name": "unused", "description": "Unused (pad)", "typical_range": [0.0, 0.0]},
72+
{"index": 5, "name": "cross_type_factor", "description": "Per-type CTC threshold spread (0=same threshold, 0.3=+-30% spread)", "typical_range": [0.0, 0.5]}
73+
]
74+
}
75+
],
76+
"width_constraint": "ALL rows of params_mesh MUST have same number of columns (8). Pad shorter rows.",
77+
"particle_params": {
78+
"description": "Per-type params from simulation.params (one row per n_particle_types)",
79+
"slots": [
80+
{"index": 0, "name": "M1", "description": "Per-type mobility for C1"},
81+
{"index": 1, "name": "M2", "description": "Per-type mobility for C2"},
82+
{"index": 2, "name": "consumption", "description": "Per-type consumption rate"},
83+
{"index": 3, "name": "production", "description": "Per-type production rate"},
84+
{"index": 4, "name": "ar_p1", "description": "Attraction strength"},
85+
{"index": 5, "name": "ar_p2", "description": "Attraction exponent"},
86+
{"index": 6, "name": "ar_p3", "description": "Repulsion strength"},
87+
{"index": 7, "name": "ar_p4", "description": "Repulsion exponent"}
88+
]
89+
}
90+
}
91+
92+
def __init__(self, aggr_type='mean', p=None, particle_params=None, bc_dpos=None, dimension=2, sigma=0.005):
93+
super(PDE_D_ThresholdCoupling, self).__init__(aggr=aggr_type)
94+
95+
self.p = p
96+
self.particle_params = particle_params
97+
self.bc_dpos = bc_dpos
98+
self.dimension = dimension
99+
self.sigma = sigma
100+
101+
self.M1 = p[0, 5]
102+
self.M2 = p[1, 1]
103+
self.consumption_rate = p[2, 1]
104+
self.production_rate = p[2, 2]
105+
self.influence_radius = p[2, 3]
106+
self.Pe = p[2, 0]
107+
self.repulsion_strength = 50
108+
self.repulsion_range = 0.04
109+
110+
# CTC threshold
111+
self.ctc_threshold = p[0, 7] if p.shape[1] > 7 else 0.0
112+
self.A_ref = p[0, 2]
113+
114+
# Per-type threshold spread
115+
self.cross_type_factor = p[2, 5] if p.shape[1] > 5 else 0.0
116+
117+
print(f"initialized PDE_D_ThresholdCoupling with parameters:")
118+
print(f" mobility: M1={self.M1.item()}, M2={self.M2.item()}")
119+
ctc_val = self.ctc_threshold.item() if hasattr(self.ctc_threshold, 'item') else self.ctc_threshold
120+
T_val = ctc_val * self.A_ref.item()
121+
print(f" ctc_threshold={ctc_val:.3f} (T={T_val:.2f}, reversal at C1=T*A, Wolpert 1969)")
122+
ctf_val = self.cross_type_factor.item() if hasattr(self.cross_type_factor, 'item') else self.cross_type_factor
123+
if ctf_val > 0 and particle_params is not None:
124+
n_types = particle_params.shape[0]
125+
mean_idx = (n_types - 1) / 2.0
126+
for t in range(n_types):
127+
t_offset = ctf_val * (t - mean_idx)
128+
t_val = T_val * (1.0 + t_offset)
129+
print(f" Type {t}: CTC threshold = {t_val:.2f} (offset={t_offset:+.2f})")
130+
print(f" Pe={self.Pe.item():.3f}, sigma={self.sigma}")
131+
print(f" particle->field: consumption={self.consumption_rate.item()}, production={self.production_rate.item()}, influence_radius={self.influence_radius.item():.3f}")
132+
if particle_params is not None:
133+
print(f" multi-type support: {particle_params.shape[0]} particle types")
134+
135+
def forward(self, data, direction='fp'):
136+
x, edge_index = data.x, data.edge_index
137+
edge_index, _ = pyg_utils.remove_self_loops(edge_index)
138+
139+
if self.particle_params is not None:
140+
particle_type = x[:, 1 + 2*self.dimension].long()
141+
max_type = particle_type.max().item()
142+
n_param_rows = self.particle_params.shape[0]
143+
if max_type >= n_param_rows:
144+
raise ValueError(
145+
f"PDE_D_ThresholdCoupling: particle_params has {n_param_rows} rows but found "
146+
f"particle type {max_type}. Need {max_type + 1} rows in simulation.params."
147+
)
148+
parameters = self.particle_params[to_numpy(particle_type), :]
149+
else:
150+
parameters = None
151+
152+
if direction == 'interpolate':
153+
result = self.propagate(edge_index, x=x, mode='interpolate', parameters=parameters)
154+
pos = x[:, 1:self.dimension+1]
155+
in_box = ((pos >= 0) & (pos <= 1)).all(dim=1, keepdim=True)
156+
result = result * in_box.float()
157+
return result
158+
elif direction == 'fp':
159+
result = self.propagate(edge_index, x=x, mode='fp', parameters=parameters)
160+
pos = x[:, 1:self.dimension+1]
161+
in_box = ((pos >= 0) & (pos <= 1)).all(dim=1, keepdim=True)
162+
result = result * in_box.float()
163+
return result
164+
elif direction == 'pf':
165+
result = self.propagate(edge_index, x=x, mode='pf', parameters=parameters)
166+
return result
167+
else:
168+
result = self.propagate(edge_index, x=x, mode='pp', parameters=parameters)
169+
return result
170+
171+
def message(self, edge_index_i, edge_index_j, x_i, x_j, mode=None, parameters_i=None):
172+
pos_i = x_i[:, 1:self.dimension+1]
173+
pos_j = x_j[:, 1:self.dimension+1]
174+
175+
d_pos = self.bc_dpos(pos_j - pos_i)
176+
dist = torch.sqrt(torch.sum(d_pos**2, dim=1))
177+
dist_safe = torch.clamp(dist, min=1e-6)
178+
179+
if mode == 'interpolate':
180+
C1_mesh = x_j[:, 6:7]
181+
C2_mesh = x_j[:, 7:8]
182+
weight = torch.exp(-dist / 0.01).unsqueeze(1)
183+
return torch.cat([C1_mesh * weight, C2_mesh * weight, weight], dim=1)
184+
185+
elif mode == 'fp':
186+
fields_i = x_i[:, 6:8]
187+
fields_j = x_j[:, 6:8]
188+
189+
dC1 = fields_j[:, 0:1] - fields_i[:, 0:1]
190+
dC2 = fields_j[:, 1:2] - fields_i[:, 1:2]
191+
192+
kernel = torch.exp(-dist / 0.05)
193+
dir_norm = d_pos / dist_safe.unsqueeze(1)
194+
domain_scale = 32.0
195+
grad_C1 = (dC1 * kernel.unsqueeze(1)) / (dist_safe.unsqueeze(1) * domain_scale)
196+
grad_C2 = (dC2 * kernel.unsqueeze(1)) / (dist_safe.unsqueeze(1) * domain_scale)
197+
198+
if parameters_i is not None:
199+
M1 = parameters_i[:, 0:1]
200+
M2 = parameters_i[:, 1:2]
201+
else:
202+
M1 = self.M1
203+
M2 = self.M2
204+
205+
velocity_raw = (M1 * grad_C1 + M2 * grad_C2) * dir_norm
206+
207+
# Concentration-threshold coupling (CTC)
208+
if self.ctc_threshold > 0:
209+
C1_local = fields_i[:, 0:1]
210+
A_ref = self.A_ref
211+
base_T = self.ctc_threshold * A_ref
212+
steepness = 3.0
213+
214+
# Per-type thresholds when multi-type + cross_type_factor > 0
215+
if (parameters_i is not None and self.cross_type_factor > 0
216+
and x_i.numel() > 0):
217+
type_i = x_i[:, 1 + 2*self.dimension].long()
218+
n_types = type_i.max().item() + 1 if type_i.numel() > 0 else 1
219+
mean_idx = (n_types - 1) / 2.0
220+
type_offset = self.cross_type_factor * (type_i.float() - mean_idx)
221+
T = base_T * (1.0 + type_offset.unsqueeze(1))
222+
else:
223+
T = base_T
224+
225+
sign_factor = -torch.tanh(steepness * (C1_local - T) / (A_ref + 1e-6))
226+
velocity_raw = velocity_raw * sign_factor
227+
228+
return velocity_raw
229+
230+
elif mode == 'pf':
231+
weights = torch.exp(-dist**2 / (2 * (self.influence_radius/3)**2))
232+
233+
if parameters_i is not None:
234+
consumption = parameters_i[:, 2]
235+
production = parameters_i[:, 3]
236+
else:
237+
consumption = self.consumption_rate
238+
production = self.production_rate
239+
240+
field_updates = torch.zeros((pos_i.size(0), 2), device=pos_i.device)
241+
field_updates[:, 0] = -consumption * weights
242+
field_updates[:, 1] = production * weights
243+
return field_updates
244+
245+
else: # mode == 'pp'
246+
if parameters_i is not None:
247+
p1 = parameters_i[:, 4]
248+
p2 = parameters_i[:, 5]
249+
p3 = parameters_i[:, 6]
250+
p4 = parameters_i[:, 7]
251+
252+
f = (p1 * torch.exp(-dist ** (2 * p2) / (2 * self.sigma ** 2))
253+
- p3 * torch.exp(-dist ** (2 * p4) / (2 * self.sigma ** 2)))
254+
255+
forces = f[:, None] * d_pos / dist_safe.unsqueeze(1)
256+
else:
257+
forces = torch.zeros_like(pos_i)
258+
in_range = dist < self.repulsion_range
259+
if in_range.any():
260+
dir_norm = d_pos / dist_safe.unsqueeze(1)
261+
repulsion_mag = self.repulsion_strength * torch.exp(
262+
-5.0 * dist[in_range] / self.repulsion_range
263+
)
264+
forces[in_range] = -dir_norm[in_range] * repulsion_mag.unsqueeze(1)
265+
266+
return forces
267+
268+
def update(self, aggr_out, mode=None):
269+
if mode == 'interpolate':
270+
C1_weighted = aggr_out[:, 0:1]
271+
C2_weighted = aggr_out[:, 1:2]
272+
weight_sum = aggr_out[:, 2:3]
273+
weight_sum = torch.clamp(weight_sum, min=1e-10)
274+
return torch.cat([C1_weighted / weight_sum, C2_weighted / weight_sum], dim=1)
275+
else:
276+
return aggr_out

0 commit comments

Comments
 (0)