physics_in_parallel 4.2.0-alpha

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
/*!
Deterministic displacement kernels for square-lattice pair generation.

A kernel maps indexed random values to a move length or nearest-neighbor
direction code. Sampling is a pure function of an explicit key, sweep, and
sample index, so output does not depend on Rayon worker scheduling.
*/

use std::error::Error;
use std::fmt;

use crate::threading::parallel_chunk_len;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};

use super::random::{DOMAIN_KERNEL_SAMPLE, IndexedRng, uniform_index, unit_f64};
use crate::rng::{ResolvedRng, RngError};

/// Serializable description of one square-lattice displacement distribution.
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum KernelType {
    /// Continuous radial density proportional to r^(-1-mu) on [c, l).
    /// mu = 0 selects log-uniform radii. This is not a pointwise lattice PMF.
    PowerLaw {
        l: f64,
        c: f64,
        mu: f64,
    },
    #[serde(alias = "uniform")]
    UniformDistance {
        l: f64,
        c: f64,
    },
    NearestNeighbor {
        dimension: usize,
    },
}

impl KernelType {
    /// Builds an inscribed periodic power-law kernel in lattice-site units.
    /// Defaults are c = 1 and l = half the shortest axis's site count. This
    /// optional cutoff policy does not restrict ordinary kernel constructors.
    /// Physical spacing is deliberately not interpreted as a site distance.
    pub fn power_law_for(
        geometry: &super::SquareLatticeGeometry,
        mu: f64,
        c: Option<f64>,
        l: Option<f64>,
    ) -> Result<Self, KernelError> {
        let (c, l) = geometry_bounds(geometry, c, l)?;
        Ok(PowerLawKernel::try_new(l, c, mu)?.kind)
    }

    /// Builds an inscribed periodic uniform-radius kernel in lattice-site units.
    /// Uses the same optional cutoff policy as `power_law_for`.
    pub fn uniform_distance_for(
        geometry: &super::SquareLatticeGeometry,
        c: Option<f64>,
        l: Option<f64>,
    ) -> Result<Self, KernelError> {
        let (c, l) = geometry_bounds(geometry, c, l)?;
        Ok(UniformDistanceKernel::try_new(l, c)?.kind)
    }
}

fn geometry_bounds(
    geometry: &super::SquareLatticeGeometry,
    c: Option<f64>,
    l: Option<f64>,
) -> Result<(f64, f64), KernelError> {
    if geometry.boundary() != super::BoundaryCondition::Periodic {
        return Err(KernelError::GeometryRequiresPeriodic);
    }
    let maximum = *geometry.shape().iter().min().expect("validated geometry") as f64 / 2.0;
    let c = c.unwrap_or(1.0);
    let l = l.unwrap_or(maximum);
    if !c.is_finite() || !l.is_finite() || c < 1.0 || l <= c || l > maximum {
        return Err(KernelError::InvalidGeometryBounds { c, l, maximum });
    }
    Ok((c, l))
}

/// Invalid displacement-kernel configuration.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum KernelError {
    InvalidPowerLaw { l: f64, c: f64, mu: f64 },
    InvalidUniformDistance { l: f64, c: f64 },
    InvalidNearestNeighborDimension { dimension: usize },
    GeometryRequiresPeriodic,
    InvalidGeometryBounds { c: f64, l: f64, maximum: f64 },
    Rng(RngError),
}

impl fmt::Display for KernelError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidPowerLaw { l, c, mu } => write!(
                formatter,
                "power-law kernel requires finite l > c > 0 and finite mu >= 0; got l={l}, c={c}, mu={mu}"
            ),
            Self::InvalidUniformDistance { l, c } => write!(
                formatter,
                "uniform-distance kernel requires finite l > c >= 0; got l={l}, c={c}"
            ),
            Self::InvalidNearestNeighborDimension { dimension } => write!(
                formatter,
                "nearest-neighbor kernel dimension must be positive; got {dimension}"
            ),
            Self::Rng(error) => error.fmt(formatter),
            Self::GeometryRequiresPeriodic => write!(
                formatter,
                "inscribed kernel defaults require periodic geometry"
            ),
            Self::InvalidGeometryBounds { c, l, maximum } => write!(
                formatter,
                "inscribed site radii require 1 <= c < l <= {maximum}; got c={c}, l={l}"
            ),
        }
    }
}

impl Error for KernelError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Rng(error) => Some(error),
            _ => None,
        }
    }
}

/// Indexed displacement distribution used by kernel-configured
/// [`PairGenerator`](super::PairGenerator).
pub trait Kernel: Send + Sync {
    /// Samples one value from `(sweep, sample_index)` using unified RNG configuration.
    fn sample_indexed(
        &self,
        rng: ResolvedRng,
        sweep: u64,
        sample_index: u64,
    ) -> Result<f64, KernelError>;

    /// Samples a stable batch whose result does not depend on worker count.
    fn sample_batch_indexed(
        &self,
        rng: ResolvedRng,
        sweep: u64,
        n: usize,
    ) -> Result<Vec<f64>, KernelError>;

    /// Returns the compact configuration for this distribution.
    fn kind(&self) -> KernelType;

    /// Clones this kernel behind a trait object.
    fn boxed_clone(&self) -> Box<dyn Kernel>;
}

impl Clone for Box<dyn Kernel> {
    fn clone(&self) -> Self {
        self.boxed_clone()
    }
}

#[derive(Debug, Clone)]
pub struct PowerLawKernel {
    kind: KernelType,
    l_pow: f64,
    c_pow: f64,
}

impl PowerLawKernel {
    pub fn try_new(l: f64, c: f64, mu: f64) -> Result<Self, KernelError> {
        if !l.is_finite() || !c.is_finite() || !mu.is_finite() || l <= c || c <= 0.0 || mu < 0.0 {
            return Err(KernelError::InvalidPowerLaw { l, c, mu });
        }
        Ok(Self {
            kind: KernelType::PowerLaw { l, c, mu },
            l_pow: l.powf(-mu),
            c_pow: c.powf(-mu),
        })
    }

    pub fn new(l: f64, c: f64, mu: f64) -> Self {
        Self::try_new(l, c, mu).expect("invalid power-law kernel configuration")
    }
}

impl Kernel for PowerLawKernel {
    fn sample_indexed(
        &self,
        rng: ResolvedRng,
        sweep: u64,
        sample_index: u64,
    ) -> Result<f64, KernelError> {
        let rng = IndexedRng::new(rng).map_err(KernelError::Rng)?;
        Ok(self.sample_resolved(rng, sweep, sample_index))
    }

    fn sample_batch_indexed(
        &self,
        rng: ResolvedRng,
        sweep: u64,
        n: usize,
    ) -> Result<Vec<f64>, KernelError> {
        sample_batch_resolved(self, rng, sweep, n)
    }

    fn kind(&self) -> KernelType {
        self.kind
    }

    fn boxed_clone(&self) -> Box<dyn Kernel> {
        Box::new(self.clone())
    }
}

impl PowerLawKernel {
    fn sample_resolved(&self, key: IndexedRng, sweep: u64, sample_index: u64) -> f64 {
        let u = unit_f64(key, sweep, DOMAIN_KERNEL_SAMPLE, sample_index, 0, 0);
        self.sample_unit(u)
    }

    fn sample_unit(&self, unit: f64) -> f64 {
        let (l, c, mu) = match self.kind {
            KernelType::PowerLaw { l, c, mu } => (l, c, mu),
            _ => unreachable!("fixed power-law configuration"),
        };
        if mu == 0.0 {
            return ((1.0 - unit) * c.ln() + unit * l.ln()).exp().clamp(c, l);
        }
        // Preserve the established inversion and rank-one sequences whenever
        // inverse powers are representable and distinguish the endpoints.
        if self.c_pow.is_finite() && self.l_pow > 0.0 && self.l_pow < self.c_pow {
            return (unit * (self.l_pow - self.c_pow) + self.c_pow)
                .powf(-1.0 / mu)
                .max(c);
        }
        let log_c = c.ln();
        let log_span = l.ln() - log_c;
        let delta = (-mu * log_span).exp_m1();
        let log_r = if delta == 0.0 {
            (1.0 - unit) * log_c + unit * l.ln()
        } else {
            log_c - (unit * delta).ln_1p() / mu
        };
        log_r.exp().clamp(c, l)
    }
}

#[derive(Debug, Clone)]
pub struct UniformDistanceKernel {
    kind: KernelType,
}

impl UniformDistanceKernel {
    pub fn try_new(l: f64, c: f64) -> Result<Self, KernelError> {
        if !l.is_finite() || !c.is_finite() || c < 0.0 || l <= c {
            return Err(KernelError::InvalidUniformDistance { l, c });
        }
        Ok(Self {
            kind: KernelType::UniformDistance { l, c },
        })
    }

    pub fn new(l: f64, c: f64) -> Self {
        Self::try_new(l, c).expect("invalid uniform-distance kernel configuration")
    }
}

impl Kernel for UniformDistanceKernel {
    fn sample_indexed(
        &self,
        rng: ResolvedRng,
        sweep: u64,
        sample_index: u64,
    ) -> Result<f64, KernelError> {
        let rng = IndexedRng::new(rng).map_err(KernelError::Rng)?;
        Ok(self.sample_resolved(rng, sweep, sample_index))
    }

    fn sample_batch_indexed(
        &self,
        rng: ResolvedRng,
        sweep: u64,
        n: usize,
    ) -> Result<Vec<f64>, KernelError> {
        sample_batch_resolved(self, rng, sweep, n)
    }

    fn kind(&self) -> KernelType {
        self.kind
    }

    fn boxed_clone(&self) -> Box<dyn Kernel> {
        Box::new(self.clone())
    }
}

impl UniformDistanceKernel {
    fn sample_resolved(&self, key: IndexedRng, sweep: u64, sample_index: u64) -> f64 {
        let (low, high) = match self.kind {
            KernelType::UniformDistance { l, c } => (c, l),
            _ => unreachable!("UniformDistanceKernel kind is fixed at construction"),
        };
        let u = unit_f64(key, sweep, DOMAIN_KERNEL_SAMPLE, sample_index, 0, 0);
        low + (high - low) * u
    }
}

#[derive(Debug, Clone)]
pub struct NearestNeighborKernel {
    kind: KernelType,
    num_neighbors: usize,
}

impl NearestNeighborKernel {
    pub fn try_new(d: usize) -> Result<Self, KernelError> {
        let num_neighbors = d
            .checked_mul(2)
            .filter(|count| *count > 0)
            .ok_or(KernelError::InvalidNearestNeighborDimension { dimension: d })?;
        Ok(Self {
            kind: KernelType::NearestNeighbor { dimension: d },
            num_neighbors,
        })
    }

    pub fn new(d: usize) -> Self {
        Self::try_new(d).expect("invalid nearest-neighbor kernel configuration")
    }
}

impl Kernel for NearestNeighborKernel {
    fn sample_indexed(
        &self,
        rng: ResolvedRng,
        sweep: u64,
        sample_index: u64,
    ) -> Result<f64, KernelError> {
        let rng = IndexedRng::new(rng).map_err(KernelError::Rng)?;
        Ok(self.sample_resolved(rng, sweep, sample_index))
    }

    fn sample_batch_indexed(
        &self,
        rng: ResolvedRng,
        sweep: u64,
        n: usize,
    ) -> Result<Vec<f64>, KernelError> {
        sample_batch_resolved(self, rng, sweep, n)
    }

    fn kind(&self) -> KernelType {
        self.kind
    }

    fn boxed_clone(&self) -> Box<dyn Kernel> {
        Box::new(self.clone())
    }
}

impl NearestNeighborKernel {
    fn sample_resolved(&self, key: IndexedRng, sweep: u64, sample_index: u64) -> f64 {
        uniform_index(
            key,
            sweep,
            DOMAIN_KERNEL_SAMPLE,
            sample_index,
            0,
            self.num_neighbors,
        ) as f64
    }
}

trait ResolvedKernel {
    fn sample_resolved(&self, rng: IndexedRng, sweep: u64, sample_index: u64) -> f64;
}

impl ResolvedKernel for PowerLawKernel {
    fn sample_resolved(&self, rng: IndexedRng, sweep: u64, sample_index: u64) -> f64 {
        Self::sample_resolved(self, rng, sweep, sample_index)
    }
}

impl ResolvedKernel for UniformDistanceKernel {
    fn sample_resolved(&self, rng: IndexedRng, sweep: u64, sample_index: u64) -> f64 {
        Self::sample_resolved(self, rng, sweep, sample_index)
    }
}

impl ResolvedKernel for NearestNeighborKernel {
    fn sample_resolved(&self, rng: IndexedRng, sweep: u64, sample_index: u64) -> f64 {
        Self::sample_resolved(self, rng, sweep, sample_index)
    }
}

fn sample_batch_resolved<K: ResolvedKernel + Sync>(
    kernel: &K,
    rng: ResolvedRng,
    sweep: u64,
    n: usize,
) -> Result<Vec<f64>, KernelError> {
    let rng = IndexedRng::new(rng).map_err(KernelError::Rng)?;
    let mut output = vec![0.0; n];
    output
        .par_iter_mut()
        .with_min_len(parallel_chunk_len(n).unwrap_or(1))
        .enumerate()
        .for_each(|(index, value)| {
            *value = kernel.sample_resolved(rng, sweep, index as u64);
        });
    Ok(output)
}

#[derive(Clone, Debug)]
pub(crate) enum BuiltinKernel {
    PowerLaw(PowerLawKernel),
    UniformDistance(UniformDistanceKernel),
    NearestNeighbor(NearestNeighborKernel),
}

impl BuiltinKernel {
    pub(crate) fn sample_unit(&self, unit: f64) -> f64 {
        match self {
            Self::PowerLaw(kernel) => kernel.sample_unit(unit),
            Self::UniformDistance(kernel) => {
                let (low, high) = match kernel.kind {
                    KernelType::UniformDistance { l, c } => (c, l),
                    _ => unreachable!("uniform-distance kernel kind is fixed at construction"),
                };
                low + (high - low) * unit
            }
            Self::NearestNeighbor(kernel) => {
                (unit * kernel.num_neighbors as f64).floor() as usize as f64
            }
        }
    }
}

pub(crate) fn try_create_builtin_kernel(
    kernel_type: KernelType,
) -> Result<BuiltinKernel, KernelError> {
    match kernel_type {
        KernelType::PowerLaw { l, c, mu } => {
            Ok(BuiltinKernel::PowerLaw(PowerLawKernel::try_new(l, c, mu)?))
        }
        KernelType::UniformDistance { l, c } => Ok(BuiltinKernel::UniformDistance(
            UniformDistanceKernel::try_new(l, c)?,
        )),
        KernelType::NearestNeighbor { dimension } => Ok(BuiltinKernel::NearestNeighbor(
            NearestNeighborKernel::try_new(dimension)?,
        )),
    }
}