hoomd-interaction 1.1.0

Hamiltonians and other interaction models that apply to hoomd-rs simulations.
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
// Copyright (c) 2024-2026 The Regents of the University of Michigan.
// Part of hoomd-rs, released under the BSD 3-Clause License.

//! [`AngularMask`] and related data structures.

use serde::{Deserialize, Serialize};

use super::AnisotropicEnergy;
use crate::univariate::UnivariateEnergy;
use hoomd_vector::{InnerProduct, Rotate, Unit, Vector};

/// A single patch in the [`AngularMask`] potential.
///
/// The width of the patch is given as the cosine of its half-angle.
///
/// # Example
///
/// ```
/// use hoomd_interaction::pairwise::angular_mask::Patch;
/// use std::f64::consts::PI;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let patch = Patch {
///     director: [0.0, 1.0, 0.0].try_into()?,
///     cos_delta: (PI / 4.0).cos(),
/// };
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Patch<V> {
    /// Vector pointing from the center of the particle to the center of the mask `[unitless]`.
    pub director: Unit<V>,
    /// Cosine of the half-angle width of the mask `[unitless]`.
    pub cos_delta: f64,
}

/// Evaluate an isotropic pairwise energy masked by angular patches (_not differentiable_).
///
/// ```math
/// U(\vec{r}_{ij}, \mathbf{o}_{ij}) = f(|\vec{r}_{ij}|) \cdot \max
/// \left(1,
/// \sum_{m=1}^{N_{\mathrm{masks},i}}
/// \sum_{n=1}^{N_{\mathrm{masks},j}}
/// s(\vec{d}_{m,i},
/// \mathbf{o}_{ij} \vec{d}_{n,j} \mathbf{o}_{ij}^*,
/// \delta_{m,i},
/// \delta_{n,j}) \right)
/// ```
/// where
/// ```math
/// s(\vec{a}, \vec{b}, \delta_a, \delta_b) =
/// \begin{cases}
/// 1 & \hat{a} \cdot \hat{r}_{ij} \ge \cos \delta_{a} \land
/// \hat{b} \cdot \hat{r}_{ji} \ge \cos \delta_{b} \\
/// 0 & \text{otherwise} \\
/// \end{cases}
/// ```
///
/// Implement the [Kern-Frenkel] potential with the [`Boxcar`] isotropic potential
/// and single patch in both `masks_i` and `masks_j`.
///
/// [Kern-Frenkel]: https://doi.org/10.1063/1.1569473
/// [`Boxcar`]: crate::univariate::Boxcar
///
/// # Examples
///
/// Construction:
///
/// ```
/// use hoomd_interaction::{
///     pairwise::{AngularMask, angular_mask::Patch},
///     univariate::Boxcar,
/// };
/// use hoomd_vector::Angle;
/// use std::f64::consts::PI;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let boxcar = Boxcar {
///     epsilon: -1.0,
///     left: 1.0,
///     right: 1.5,
/// };
/// let masks = [Patch {
///     director: [1.0, 0.0].try_into()?,
///     cos_delta: (PI / 8.0).cos(),
/// }];
/// let angular_mask = AngularMask::new(boxcar, masks);
/// # Ok(())
/// # }
/// ```
///
/// All fields are public and can be directly manipulated:
/// ```
/// use hoomd_interaction::{
///     pairwise::{AngularMask, angular_mask::Patch},
///     univariate::Boxcar,
/// };
/// use hoomd_vector::Angle;
/// use std::f64::consts::PI;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let boxcar = Boxcar {
///     epsilon: -1.0,
///     left: 1.0,
///     right: 1.5,
/// };
/// let masks = [Patch {
///     director: [1.0, 0.0].try_into()?,
///     cos_delta: (PI / 8.0).cos(),
/// }];
/// let mut angular_mask = AngularMask::new(boxcar, masks);
///
/// angular_mask.masks_i[0].cos_delta = (PI / 4.0).cos();
/// angular_mask.isotropic.epsilon = -2.0;
/// # Ok(())
/// # }
/// ```
///
/// Evaluate energy between particles:
///
/// ```
/// use hoomd_interaction::{
///     pairwise::{AngularMask, AnisotropicEnergy, angular_mask::Patch},
///     univariate::Boxcar,
/// };
/// use hoomd_vector::Angle;
/// use std::f64::consts::PI;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let boxcar = Boxcar {
///     epsilon: -1.0,
///     left: 1.0,
///     right: 1.5,
/// };
/// let masks = [Patch {
///     director: [1.0, 0.0].try_into()?,
///     cos_delta: (PI / 8.0).cos(),
/// }];
/// let angular_mask = AngularMask::new(boxcar, masks);
///
/// let energy = angular_mask.energy(&[1.0, 0.0].into(), &Angle::from(0.0));
/// assert_eq!(energy, 0.0);
///
/// let energy = angular_mask.energy(&[1.0, 0.0].into(), &Angle::from(PI));
/// assert_eq!(energy, -1.0);
/// # Ok(())
/// # }
/// ```
///
/// Apply different patches to the _i_ and _j_ particles:
/// ```
/// use hoomd_interaction::{
///     pairwise::{AngularMask, AnisotropicEnergy, angular_mask::Patch},
///     univariate::Boxcar,
/// };
/// use hoomd_vector::Angle;
/// use std::f64::consts::PI;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let boxcar = Boxcar {
///     epsilon: -1.0,
///     left: 1.0,
///     right: 1.5,
/// };
/// let masks_i = vec![
///     Patch {
///         director: [1.0, 0.0].try_into()?,
///         cos_delta: (PI / 8.0).cos(),
///     },
///     Patch {
///         director: [-1.0, 0.0].try_into()?,
///         cos_delta: (PI / 8.0).cos(),
///     },
/// ];
/// let masks_j = vec![Patch {
///     director: [0.0, 1.0].try_into()?,
///     cos_delta: (PI / 8.0).cos(),
/// }];
/// let angular_mask = AngularMask {
///     isotropic: boxcar,
///     masks_i,
///     masks_j,
/// };
///
/// let energy = angular_mask.energy(&[-1.0, 0.0].into(), &Angle::from(0.0));
/// assert_eq!(energy, 0.0);
///
/// let energy =
///     angular_mask.energy(&[-1.0, 0.0].into(), &Angle::from(-PI / 2.0));
/// assert_eq!(energy, -1.0);
/// # Ok(())
/// # }
/// ```
///
/// Evaluate the angular mask potential on 3D particles:
/// ```
/// use hoomd_interaction::{
///     pairwise::{AngularMask, AnisotropicEnergy, angular_mask::Patch},
///     univariate::Boxcar,
/// };
/// use hoomd_vector::{Cartesian, InnerProduct, Versor};
/// use std::f64::consts::PI;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let boxcar = Boxcar {
///     epsilon: -1.0,
///     left: 1.0,
///     right: 1.5,
/// };
///
/// let mask = [Patch {
///     director: [0.0, 0.0, 1.0].try_into()?,
///     cos_delta: (PI / 8.0).cos(),
/// }];
/// let (x_axis, _) = Cartesian::from([1.0, 0.0, 0.0]).to_unit_unchecked();
///
/// let angular_mask = AngularMask::new(boxcar, mask);
///
/// assert_eq!(
///     angular_mask.energy(
///         &Cartesian::from([0.0, 0.0, 1.0]),
///         &Versor::from_axis_angle(x_axis, 0.0)
///     ),
///     0.0
/// );
/// assert_eq!(
///     angular_mask.energy(
///         &Cartesian::from([0.0, 0.0, 1.0]),
///         &Versor::from_axis_angle(x_axis, PI)
///     ),
///     -1.0
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AngularMask<E, V> {
    /// The original potential.
    pub isotropic: E,

    /// Masks on the i particle.
    pub masks_i: Vec<Patch<V>>,

    /// Masks on the j particle.
    pub masks_j: Vec<Patch<V>>,
}

impl<E, V> AngularMask<E, V>
where
    V: Vector,
{
    /// Construct a [`AngularMask`] with the given function and masks.
    ///
    /// To obtain the best performance, construct [`AngularMask`] once and
    /// call use it many times. `new` dynamically allocates `Vec` types
    /// and is therefore not suitable to be called per particle,
    /// unlike other potentials such as [`LennardJones`] or [`Boxcar`].
    ///
    /// `new` sets both `masks_i` and `masks_j` to `masks`. Use struct initialization
    /// syntax to set these separately.
    ///
    /// [`LennardJones`]: crate::univariate::LennardJones
    /// [`Boxcar`]: crate::univariate::Boxcar
    ///
    /// # Example
    ///
    /// ```
    /// use hoomd_interaction::{
    ///     pairwise::{AngularMask, angular_mask::Patch},
    ///     univariate::Boxcar,
    /// };
    /// use std::f64::consts::PI;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let boxcar = Boxcar {
    ///     epsilon: -1.0,
    ///     left: 1.0,
    ///     right: 1.5,
    /// };
    /// let masks = [Patch {
    ///     director: [1.0, 0.0].try_into()?,
    ///     cos_delta: (PI / 8.0).cos(),
    /// }];
    /// let angular_mask = AngularMask::new(boxcar, masks);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    #[must_use]
    pub fn new<I>(isotropic: E, masks: I) -> Self
    where
        I: IntoIterator<Item = Patch<V>>,
    {
        let masks = Vec::from_iter(masks);
        Self {
            isotropic,
            masks_i: masks.clone(),
            masks_j: masks,
        }
    }
}

impl<E, V, R> AnisotropicEnergy<V, R> for AngularMask<E, V>
where
    E: UnivariateEnergy,
    V: InnerProduct,
    R: Rotate<V> + Into<R::Matrix> + Copy,
{
    #[inline]
    fn energy(&self, r_ij: &V, o_ij: &R) -> f64 {
        let o_ij_matrix: R::Matrix = (*o_ij).into();
        let (unit_r_ij, r_ij_norm) = r_ij.to_unit_unchecked();
        let unit_r_ji = -(*unit_r_ij.get());

        for mask_j in &self.masks_j {
            let d_j = o_ij_matrix.rotate(mask_j.director.get());

            for mask_i in &self.masks_i {
                if mask_i.director.get().dot(unit_r_ij.get()) >= mask_i.cos_delta
                    && d_j.dot(&unit_r_ji) >= mask_j.cos_delta
                {
                    return self.isotropic.energy(r_ij_norm);
                }
            }
        }

        0.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approxim::assert_relative_eq;
    use rstest::*;
    use std::f64::consts::PI;

    use crate::univariate::{Boxcar, LennardJones};
    use hoomd_vector::{Angle, Cartesian, InnerProduct, Versor};

    #[test]
    fn single_patch_2d() {
        // Evaluate that patch directors, widths, and relative orientations are
        // handled properly.
        let epsilon = 1.125;
        let boxcar = Boxcar {
            epsilon,
            left: 0.0,
            right: 1000.0,
        };

        // First case: identical directors in the +x direction
        let mask = [Patch {
            director: [1.0, 0.0]
                .try_into()
                .expect("hard-coded vector should have non-zero length"),
            cos_delta: (PI / 8.0).cos(),
        }];
        let angular_mask = AngularMask::new(boxcar.clone(), mask);

        // Check corner cases when the j particle is along the patch direction.
        assert_eq!(
            angular_mask.energy(&Cartesian::from([1.0, 0.0]), &Angle::from(0.0)),
            0.0
        );
        assert_eq!(
            angular_mask.energy(&Cartesian::from([1.0, 0.0]), &Angle::from(PI)),
            epsilon
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([1.0, 0.0]),
                &Angle::from(PI + PI / 8.0 - 0.001)
            ),
            epsilon
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([1.0, 0.0]),
                &Angle::from(PI + PI / 8.0 + 0.001)
            ),
            0.0
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([1.0, 0.0]),
                &Angle::from(PI + PI / 8.0 + 0.001)
            ),
            0.0
        );

        // When the j particle is orthogonal to the patch direction, no orientation will interact.
        for theta in (0..100).map(|x| f64::from(x) * 2.0 * PI / 100.0) {
            assert_eq!(
                angular_mask.energy(&Cartesian::from([0.0, 1.0]), &Angle::from(theta)),
                0.0
            );
        }

        // Second case: identical directors in the 1,1 direction
        let mask = [Patch {
            director: [1.0, 1.0]
                .try_into()
                .expect("hard-coded vector should have non-zero length"),
            cos_delta: (PI / 3.0).cos(),
        }];
        let angular_mask = AngularMask::new(boxcar, mask);

        // Check corner cases when the j particle is along the patch direction
        assert_eq!(
            angular_mask.energy(&Cartesian::from([1.0, 1.0]), &Angle::from(0.0)),
            0.0
        );
        assert_eq!(
            angular_mask.energy(&Cartesian::from([1.0, 1.0]), &Angle::from(PI)),
            epsilon
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([1.0, 1.0]),
                &Angle::from(PI + PI / 3.0 - 0.001)
            ),
            epsilon
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([1.0, 1.0]),
                &Angle::from(PI + PI / 3.0 + 0.001)
            ),
            0.0
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([1.0, 1.0]),
                &Angle::from(PI + PI / 3.0 + 0.001)
            ),
            0.0
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([1.0, 1.0]),
                &Angle::from(PI + PI / 3.0 + 0.001)
            ),
            0.0
        );

        // With the large PI / 3.0 patch, a PI / 4 offset r_ij can interact.
        assert_eq!(
            angular_mask.energy(&Cartesian::from([0.0, 1.0]), &Angle::from(0.0)),
            0.0
        );
        assert_eq!(
            angular_mask.energy(&Cartesian::from([0.0, 1.0]), &Angle::from(-3.0 * PI / 4.0)),
            epsilon
        );
    }

    #[rstest]
    #[case([0.0, 1.0].into(), 0.0, 1.0)]
    #[case([0.0, 1.0].into(), PI / 2.0, 0.0)]
    #[case([0.0, 1.0].into(), PI, 1.0)]
    #[case([0.0, -1.0].into(), 0.0, 1.0)]
    #[case([0.0, -1.0].into(), PI / 2.0, 0.0)]
    #[case([0.0, -1.0].into(), PI, 1.0)]
    #[case([1.0, 0.0].into(), 0.0, 0.0)]
    #[case([1.0, 0.0].into(), PI / 2.0, 1.0)]
    #[case([1.0, 0.0].into(), PI, 0.0)]
    #[case([-1.0, 0.0].into(), 0.0, 0.0)]
    #[case([-1.0, 0.0].into(), PI / 2.0, 1.0)]
    #[case([-1.0, 0.0].into(), PI, 0.0)]
    fn multiple_patches_2d(#[case] r_ij: Cartesian<2>, #[case] theta: f64, #[case] expected: f64) {
        let epsilon = 1.0;
        let boxcar = Boxcar {
            epsilon,
            left: 0.0,
            right: 1000.0,
        };

        // Third case: multiple patches and different i,j masks.
        let masks_i = vec![
            Patch {
                director: [0.0, 1.0]
                    .try_into()
                    .expect("hard-coded vector should have non-zero length"),
                cos_delta: (PI / 8.0).cos(),
            },
            Patch {
                director: [0.0, -1.0]
                    .try_into()
                    .expect("hard-coded vector should have non-zero length"),
                cos_delta: (PI / 8.0).cos(),
            },
            Patch {
                director: [1.0, 0.0]
                    .try_into()
                    .expect("hard-coded vector should have non-zero length"),
                cos_delta: (PI / 8.0).cos(),
            },
            Patch {
                director: [-1.0, 0.0]
                    .try_into()
                    .expect("hard-coded vector should have non-zero length"),
                cos_delta: (PI / 8.0).cos(),
            },
        ];
        let masks_j = vec![
            Patch {
                director: [0.0, 1.0]
                    .try_into()
                    .expect("hard-coded vector should have non-zero length"),
                cos_delta: (PI / 8.0).cos(),
            },
            Patch {
                director: [0.0, -1.0]
                    .try_into()
                    .expect("hard-coded vector should have non-zero length"),
                cos_delta: (PI / 8.0).cos(),
            },
        ];
        let angular_mask = AngularMask {
            isotropic: boxcar,
            masks_i,
            masks_j,
        };

        assert_eq!(angular_mask.energy(&r_ij, &Angle::from(theta)), expected);
    }

    #[rstest]
    fn smooth_potential(#[values(0.9, 1.1, 1.2, 3.0)] r: f64) {
        let epsilon = 1.0;
        let sigma = 1.0;
        let lj: LennardJones = LennardJones { epsilon, sigma };

        let mask = [Patch {
            director: [1.0, 0.0]
                .try_into()
                .expect("hard-coded vector should have non-zero length"),
            cos_delta: (PI).cos(),
        }];
        let angular_mask = AngularMask::new(lj.clone(), mask);

        // The patch covers the full surface. angular_mask.energy() should evaluate to the same
        // as lj.energy() for all orientations.
        for theta in (0..100).map(|x| f64::from(x) * 2.0 * PI / 100.0) {
            let r_ij = Angle::from(theta).rotate(&Cartesian::from([0.0, r]));
            assert_relative_eq!(
                angular_mask.energy(&r_ij, &Angle::from(0.0)),
                lj.energy(r),
                epsilon = 1e-12
            );
        }
    }

    #[test]
    fn single_patch_3d() {
        // Evaluate that patch directors, widths, and relative orientations are
        // handled properly in 3D.
        let epsilon = 1.125;
        let boxcar = Boxcar {
            epsilon,
            left: 0.0,
            right: 1000.0,
        };

        // First case: identical directors in the +z direction
        let mask = [Patch {
            director: [0.0, 0.0, 1.0]
                .try_into()
                .expect("hard-coded vector should have non-zero length"),
            cos_delta: (PI / 8.0).cos(),
        }];
        let angular_mask = AngularMask::new(boxcar, mask);

        let (x_axis, _) = Cartesian::from([1.0, 0.0, 0.0]).to_unit_unchecked();
        let (y_axis, _) = Cartesian::from([1.0, 0.0, 0.0]).to_unit_unchecked();

        // Check corner cases when the j particle is along the patch direction.
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([0.0, 0.0, 1.0]),
                &Versor::from_axis_angle(x_axis, 0.0)
            ),
            0.0
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([0.0, 0.0, 1.0]),
                &Versor::from_axis_angle(y_axis, PI)
            ),
            epsilon
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([0.0, 0.0, 1.0]),
                &Versor::from_axis_angle(x_axis, PI + PI / 8.0 - 0.001)
            ),
            epsilon
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([0.0, 0.0, 1.0]),
                &Versor::from_axis_angle(y_axis, PI + PI / 8.0 + 0.001)
            ),
            0.0
        );
        assert_eq!(
            angular_mask.energy(
                &Cartesian::from([0.0, 0.0, 1.0]),
                &Versor::from_axis_angle(x_axis, PI + PI / 8.0 + 0.001)
            ),
            0.0
        );

        // When the j particle is orthogonal to the patch direction, no orientation will interact.
        for theta in (0..100).map(|x| f64::from(x) * 2.0 * PI / 100.0) {
            assert_eq!(
                angular_mask.energy(
                    &Cartesian::from([0.0, 1.0, 0.0]),
                    &Versor::from_axis_angle(x_axis, theta)
                ),
                0.0
            );
        }
    }
}