physics_in_parallel 3.0.3

High-performance infrastructure for numerical simulations in physics
Documentation
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
/*!
Pairwise Hooke-law spring interactions for massive-particle models.

Purpose:
`SpringNetwork` stores an unordered set of particle pairs, with one reusable
`models::laws::Spring` payload on each pair. It can then add Hooke-law
acceleration contributions into the canonical particle acceleration attribute
`ATTR_A`.

Design:
The network owns only interaction topology and spring parameters. Particle
state lives in `PhysObj`; `apply_hooke_acceleration` reads `ATTR_R`,
`ATTR_M_INV`, optional `ATTR_ALIVE`, optional `ATTR_RIGID`, and adds into
`ATTR_A`. Existing acceleration is preserved and spring contributions are added
on top of it.
*/

use crate::engines::soa::interaction::InteractionOrder;
use crate::engines::soa::phys_obj::{AttrsError, PhysObj};
use crate::engines::soa::{Interaction, InteractionError, InteractionId};
use crate::models::laws::{Spring, SpringCutoff, SpringLawError};
use crate::models::particles::attrs::{ATTR_A, ATTR_R, ParticleSelection};
use crate::models::particles::state::{ParticleStateError, gather_inverse_mass, gather_masks};

/// Errors returned by spring-network operations.
#[derive(Debug, Clone, PartialEq)]
pub enum SpringNetworkError {
    /// Lower-level attribute/core access error.
    Attrs(AttrsError),
    /// Lower-level interaction storage error.
    Interaction(InteractionError),
    /// Lower-level spring law validation error.
    Law(SpringLawError),
    /// Required particle attribute has the wrong vector dimension.
    InvalidAttrShape {
        /// Attribute label that failed validation.
        label: &'static str,
        /// Expected vector dimension.
        expected_dim: usize,
        /// Actual vector dimension.
        got_dim: usize,
    },
    /// Attribute row count does not match the position row count.
    InconsistentParticleCount {
        /// Attribute label that failed validation.
        label: &'static str,
        /// Expected number of particle rows.
        expected: usize,
        /// Actual number of rows.
        got: usize,
    },
    /// Inverse mass is not finite or is negative.
    InvalidInverseMass {
        /// Particle row index.
        index: usize,
        /// Invalid inverse mass value.
        value: f64,
    },
    /// Internal interaction storage contained a non-pair entry.
    InvalidSpringArity {
        /// Interaction id with the wrong arity.
        id: InteractionId,
        /// Actual number of nodes.
        arity: usize,
    },
}

impl From<InteractionError> for SpringNetworkError {
    fn from(value: InteractionError) -> Self {
        Self::Interaction(value)
    }
}

impl From<AttrsError> for SpringNetworkError {
    fn from(value: AttrsError) -> Self {
        Self::Attrs(value)
    }
}

impl From<SpringLawError> for SpringNetworkError {
    fn from(value: SpringLawError) -> Self {
        Self::Law(value)
    }
}

impl From<ParticleStateError> for SpringNetworkError {
    fn from(value: ParticleStateError) -> Self {
        match value {
            ParticleStateError::Attrs(err) => Self::Attrs(err),
            ParticleStateError::InvalidAttrShape {
                label,
                expected_dim,
                got_dim,
            } => Self::InvalidAttrShape {
                label,
                expected_dim,
                got_dim,
            },
            ParticleStateError::InconsistentParticleCount {
                label,
                expected,
                got,
            } => Self::InconsistentParticleCount {
                label,
                expected,
                got,
            },
        }
    }
}

/// Undirected network of pairwise springs.
#[derive(Debug, Clone)]
pub struct SpringNetwork {
    springs: Interaction<Spring>,
}

impl Default for SpringNetwork {
    fn default() -> Self {
        Self::empty()
    }
}

impl SpringNetwork {
    /// Creates an empty spring network.
    pub fn empty() -> Self {
        Self {
            springs: Interaction::new(0, InteractionOrder::Unordered),
        }
    }

    /// Creates an empty spring network with a known particle bound and spring capacity.
    pub fn with_capacity(num_particles: usize, spring_capacity: usize) -> Self {
        let mut springs = Interaction::new(num_particles, InteractionOrder::Unordered);
        springs.reserve(spring_capacity);
        Self { springs }
    }

    /// Number of active springs.
    pub fn len(&self) -> usize {
        self.springs.len()
    }

    /// Returns true if the network has no springs.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Adds or overwrites spring parameters for an undirected particle pair.
    pub fn add_spring(
        &mut self,
        pair: (usize, usize),
        k: f64,
        l_0: f64,
        cutoff: Option<SpringCutoff>,
    ) -> Result<InteractionId, SpringNetworkError> {
        self.add_spring_payload(pair, Spring::new(k, l_0, cutoff)?)
    }

    /// Adds or overwrites one spring payload for an undirected particle pair.
    pub fn add_spring_payload(
        &mut self,
        pair: (usize, usize),
        spring: Spring,
    ) -> Result<InteractionId, SpringNetworkError> {
        spring.validate()?;
        self.ensure_n_objects_for(pair);
        Ok(self.springs.set_pair(pair.0, pair.1, spring)?)
    }

    /// Adds or overwrites many springs that share one payload.
    pub fn add_springs_payload(
        &mut self,
        pairs: &[(usize, usize)],
        spring: Spring,
    ) -> Result<(), SpringNetworkError> {
        spring.validate()?;
        if let Some(max_obj) = pairs.iter().map(|&(i, j)| i.max(j)).max() {
            self.ensure_n_objects(max_obj.saturating_add(1));
        }

        for &(i, j) in pairs {
            self.springs.set_pair(i, j, spring)?;
        }
        Ok(())
    }

    /// Removes one spring by particle pair.
    pub fn remove_spring(
        &mut self,
        pair: (usize, usize),
    ) -> Result<Option<Spring>, SpringNetworkError> {
        if pair.0.max(pair.1) >= self.springs.topology().n_objects() {
            return Ok(None);
        }
        Ok(self
            .springs
            .remove_pair(pair.0, pair.1)?
            .map(|(_, spring)| spring))
    }

    /// Returns an immutable spring payload by particle pair.
    pub fn get_spring(&self, pair: (usize, usize)) -> Result<Option<&Spring>, SpringNetworkError> {
        if pair.0.max(pair.1) >= self.springs.topology().n_objects() {
            return Ok(None);
        }
        Ok(self.springs.get_pair(pair.0, pair.1)?)
    }

    /// Returns a mutable spring payload by particle pair.
    pub fn get_spring_mut(
        &mut self,
        pair: (usize, usize),
    ) -> Result<Option<&mut Spring>, SpringNetworkError> {
        if pair.0.max(pair.1) >= self.springs.topology().n_objects() {
            return Ok(None);
        }
        Ok(self.springs.get_pair_mut(pair.0, pair.1)?)
    }

    /// Clears all springs while preserving allocated capacity.
    pub fn clear(&mut self) {
        self.springs.clear();
    }

    /// Read-only access to the wrapped interaction backend.
    pub fn interaction(&self) -> &Interaction<Spring> {
        &self.springs
    }

    /// Mutable access to the wrapped interaction backend.
    pub fn interaction_mut(&mut self) -> &mut Interaction<Spring> {
        &mut self.springs
    }

    /// Parallel read-only visit over active springs as `(i, j, spring)` tuples.
    pub fn par_iter_springs<F>(&self, f: F)
    where
        F: Fn(usize, usize, &Spring) + Send + Sync,
    {
        self.springs.par_for_each(|_id, nodes, spring| {
            debug_assert_eq!(
                nodes.nodes.len(),
                2,
                "SpringNetwork expects pairwise interactions (arity=2)"
            );

            if nodes.nodes.len() == 2 {
                f(nodes.nodes[0], nodes.nodes[1], spring);
            }
        });
    }

    /// Applies Hooke-law acceleration contributions for all active springs.
    ///
    /// Semantics:
    /// - For rigid/non-rigid pairs, the spring is still evaluated and only the non-rigid endpoint is updated.
    /// - For rigid/rigid pairs, no acceleration is written.
    /// - With `ParticleSelection::AliveOnly`, springs touching dead particles are skipped.
    /// - Use `ParticleSelection::All` only when intentionally debugging all allocated slots.
    pub fn apply_hooke_acceleration(
        &self,
        objects: &mut PhysObj,
        selection: ParticleSelection,
    ) -> Result<(), SpringNetworkError> {
        let (dim, n, r_data, m_inv_data, masks) = {
            let r = objects.core.get::<f64>(ATTR_R)?;

            if r.dim() == 0 || r.num_vectors() == 0 {
                return Ok(());
            }

            let dim = r.dim();
            let n = r.num_vectors();

            let r_data = r.as_tensor().data.clone();

            let m_inv_data = gather_inverse_mass(objects, n)?;
            for i in 0..n {
                if !m_inv_data[i].is_finite() || m_inv_data[i] < 0.0 {
                    return Err(SpringNetworkError::InvalidInverseMass {
                        index: i,
                        value: m_inv_data[i],
                    });
                }
            }

            let masks = gather_masks(objects, n, selection)?;

            (dim, n, r_data, m_inv_data, masks)
        };

        let mut accum = vec![0.0f64; n * dim];

        match dim {
            1 => accumulate_hooke_1d(
                &self.springs,
                &r_data,
                &m_inv_data,
                &masks,
                selection,
                n,
                &mut accum,
            )?,
            2 => accumulate_hooke_2d(
                &self.springs,
                &r_data,
                &m_inv_data,
                &masks,
                selection,
                n,
                &mut accum,
            )?,
            3 => accumulate_hooke_3d(
                &self.springs,
                &r_data,
                &m_inv_data,
                &masks,
                selection,
                n,
                &mut accum,
            )?,
            _ => accumulate_hooke_generic(
                &self.springs,
                &r_data,
                &m_inv_data,
                &masks,
                selection,
                n,
                dim,
                &mut accum,
            )?,
        }

        let a = objects.core.get_mut::<f64>(ATTR_A)?;
        if a.dim() != dim || a.num_vectors() != n {
            return Err(invalid_attr_or_count(
                ATTR_A,
                dim,
                a.dim(),
                n,
                a.num_vectors(),
            ));
        }

        for (dst, src) in a.as_tensor_mut().data.iter_mut().zip(accum) {
            *dst += src;
        }
        Ok(())
    }

    fn ensure_n_objects_for(&mut self, pair: (usize, usize)) {
        let needed = pair.0.max(pair.1).saturating_add(1);
        self.ensure_n_objects(needed);
    }

    fn ensure_n_objects(&mut self, needed: usize) {
        if needed > self.springs.topology().n_objects() {
            self.springs
                .set_n_objects(needed)
                .expect("growing spring interaction object bound should not invalidate entries");
        }
    }
}

fn accumulate_hooke_1d(
    springs: &Interaction<Spring>,
    r_data: &[f64],
    m_inv_data: &[f64],
    masks: &crate::models::particles::state::ParticleMasks,
    selection: ParticleSelection,
    n: usize,
    accum: &mut [f64],
) -> Result<(), SpringNetworkError> {
    for (id, nodes, spring) in springs.iter() {
        if nodes.nodes.len() != 2 {
            return Err(SpringNetworkError::InvalidSpringArity {
                id,
                arity: nodes.nodes.len(),
            });
        }
        spring.validate()?;

        let i = nodes.nodes[0];
        let j = nodes.nodes[1];
        if i >= n || j >= n || i == j {
            continue;
        }

        if !masks.is_included(selection, i) || !masks.is_included(selection, j) {
            continue;
        }

        let dx = r_data[i] - r_data[j];
        let norm = dx.abs();
        if !norm.is_finite() || norm <= f64::EPSILON {
            continue;
        }

        if let Some((cut_min, cut_max)) = spring.cutoff
            && (norm < cut_min || norm > cut_max)
        {
            continue;
        }

        let force = dx * (-spring.k * (norm - spring.l_0) / norm);
        let i_rigid = masks.rigid.as_ref().is_some_and(|flags| flags[i]);
        let j_rigid = masks.rigid.as_ref().is_some_and(|flags| flags[j]);

        if !i_rigid {
            accum[i] += force * m_inv_data[i];
        }
        if !j_rigid {
            accum[j] -= force * m_inv_data[j];
        }
    }

    Ok(())
}

fn accumulate_hooke_2d(
    springs: &Interaction<Spring>,
    r_data: &[f64],
    m_inv_data: &[f64],
    masks: &crate::models::particles::state::ParticleMasks,
    selection: ParticleSelection,
    n: usize,
    accum: &mut [f64],
) -> Result<(), SpringNetworkError> {
    for (id, nodes, spring) in springs.iter() {
        if nodes.nodes.len() != 2 {
            return Err(SpringNetworkError::InvalidSpringArity {
                id,
                arity: nodes.nodes.len(),
            });
        }
        spring.validate()?;

        let i = nodes.nodes[0];
        let j = nodes.nodes[1];
        if i >= n || j >= n || i == j {
            continue;
        }

        if !masks.is_included(selection, i) || !masks.is_included(selection, j) {
            continue;
        }

        let i_base = i * 2;
        let j_base = j * 2;
        let dx = r_data[i_base] - r_data[j_base];
        let dy = r_data[i_base + 1] - r_data[j_base + 1];
        let norm_sq = dx * dx + dy * dy;
        if !norm_sq.is_finite() || norm_sq <= f64::EPSILON {
            continue;
        }
        let norm = norm_sq.sqrt();

        if let Some((cut_min, cut_max)) = spring.cutoff
            && (norm < cut_min || norm > cut_max)
        {
            continue;
        }

        let scale = -spring.k * (norm - spring.l_0) / norm;
        let i_rigid = masks.rigid.as_ref().is_some_and(|flags| flags[i]);
        let j_rigid = masks.rigid.as_ref().is_some_and(|flags| flags[j]);

        if !i_rigid {
            let i_scale = scale * m_inv_data[i];
            accum[i_base] += dx * i_scale;
            accum[i_base + 1] += dy * i_scale;
        }
        if !j_rigid {
            let j_scale = scale * m_inv_data[j];
            accum[j_base] -= dx * j_scale;
            accum[j_base + 1] -= dy * j_scale;
        }
    }

    Ok(())
}

fn accumulate_hooke_3d(
    springs: &Interaction<Spring>,
    r_data: &[f64],
    m_inv_data: &[f64],
    masks: &crate::models::particles::state::ParticleMasks,
    selection: ParticleSelection,
    n: usize,
    accum: &mut [f64],
) -> Result<(), SpringNetworkError> {
    for (id, nodes, spring) in springs.iter() {
        if nodes.nodes.len() != 2 {
            return Err(SpringNetworkError::InvalidSpringArity {
                id,
                arity: nodes.nodes.len(),
            });
        }
        spring.validate()?;

        let i = nodes.nodes[0];
        let j = nodes.nodes[1];
        if i >= n || j >= n || i == j {
            continue;
        }

        if !masks.is_included(selection, i) || !masks.is_included(selection, j) {
            continue;
        }

        let i_base = i * 3;
        let j_base = j * 3;
        let dx = r_data[i_base] - r_data[j_base];
        let dy = r_data[i_base + 1] - r_data[j_base + 1];
        let dz = r_data[i_base + 2] - r_data[j_base + 2];
        let norm_sq = dx * dx + dy * dy + dz * dz;
        if !norm_sq.is_finite() || norm_sq <= f64::EPSILON {
            continue;
        }
        let norm = norm_sq.sqrt();

        if let Some((cut_min, cut_max)) = spring.cutoff
            && (norm < cut_min || norm > cut_max)
        {
            continue;
        }

        let scale = -spring.k * (norm - spring.l_0) / norm;
        let i_rigid = masks.rigid.as_ref().is_some_and(|flags| flags[i]);
        let j_rigid = masks.rigid.as_ref().is_some_and(|flags| flags[j]);

        if !i_rigid {
            let i_scale = scale * m_inv_data[i];
            accum[i_base] += dx * i_scale;
            accum[i_base + 1] += dy * i_scale;
            accum[i_base + 2] += dz * i_scale;
        }
        if !j_rigid {
            let j_scale = scale * m_inv_data[j];
            accum[j_base] -= dx * j_scale;
            accum[j_base + 1] -= dy * j_scale;
            accum[j_base + 2] -= dz * j_scale;
        }
    }

    Ok(())
}

fn accumulate_hooke_generic(
    springs: &Interaction<Spring>,
    r_data: &[f64],
    m_inv_data: &[f64],
    masks: &crate::models::particles::state::ParticleMasks,
    selection: ParticleSelection,
    n: usize,
    dim: usize,
    accum: &mut [f64],
) -> Result<(), SpringNetworkError> {
    let mut dr = vec![0.0f64; dim];

    for (id, nodes, spring) in springs.iter() {
        if nodes.nodes.len() != 2 {
            return Err(SpringNetworkError::InvalidSpringArity {
                id,
                arity: nodes.nodes.len(),
            });
        }
        spring.validate()?;

        let i = nodes.nodes[0];
        let j = nodes.nodes[1];
        if i >= n || j >= n || i == j {
            continue;
        }

        if !masks.is_included(selection, i) || !masks.is_included(selection, j) {
            continue;
        }

        for k in 0..dim {
            dr[k] = r_data[i * dim + k] - r_data[j * dim + k];
        }
        let norm_sq = dr.iter().map(|x| x * x).sum::<f64>();
        if !norm_sq.is_finite() || norm_sq <= f64::EPSILON {
            continue;
        }
        let norm = norm_sq.sqrt();

        if let Some((cut_min, cut_max)) = spring.cutoff
            && (norm < cut_min || norm > cut_max)
        {
            continue;
        }

        let scale = -spring.k * (norm - spring.l_0) / norm;
        let i_rigid = masks.rigid.as_ref().is_some_and(|flags| flags[i]);
        let j_rigid = masks.rigid.as_ref().is_some_and(|flags| flags[j]);

        for k in 0..dim {
            let dr_k = dr[k];
            if !i_rigid {
                accum[i * dim + k] += dr_k * scale * m_inv_data[i];
            }
            if !j_rigid {
                accum[j * dim + k] -= dr_k * scale * m_inv_data[j];
            }
        }
    }

    Ok(())
}

fn invalid_attr_or_count(
    label: &'static str,
    expected_dim: usize,
    got_dim: usize,
    expected_n: usize,
    got_n: usize,
) -> SpringNetworkError {
    if got_dim != expected_dim {
        SpringNetworkError::InvalidAttrShape {
            label,
            expected_dim,
            got_dim,
        }
    } else {
        SpringNetworkError::InconsistentParticleCount {
            label,
            expected: expected_n,
            got: got_n,
        }
    }
}