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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Immutable sampling configuration shared by buffered and on-demand paths.

use super::super::{
    kernel::{BuiltinKernel, KernelType, try_create_builtin_kernel},
    representation::SquareLatticeGeometry,
};
use super::{PairGenerationError as E, PairingMethod, SourceMode};
use crate::math::{TensorError, tensor::rank_n::layout::RowMajorLayout};
use crate::rng::{IndexedRng, ResolvedRng, domains as d};
use rayon::prelude::*;

/// An indexed pair stream without storage proportional to the sweep size.
///
/// Construction stores only geometry and validated mixture configuration.
/// Calls allocate no per-pair storage and may run concurrently in any order.
/// Radii measure lattice sites, regardless of physical axis spacings.
#[derive(Clone, Debug)]
pub struct PairSampler {
    pub(super) layout: RowMajorLayout,
    pub(super) geometry: Option<SquareLatticeGeometry>,
    method: PairingMethod,
    prepared: PreparedMethod,
    key: IndexedRng,
}

impl PairSampler {
    /// Constructs a raw-coordinate stream without assuming a boundary policy.
    pub fn new(shape: &[usize], method: PairingMethod, rng: ResolvedRng) -> Result<Self, E> {
        let key = IndexedRng::new(rng).map_err(E::Rng)?;
        let layout = RowMajorLayout::try_new(shape).map_err(|error| match error {
            TensorError::InvalidShape { shape } if shape.is_empty() => E::EmptyShape,
            TensorError::InvalidShape { shape } => E::ZeroAxis {
                axis: shape.iter().position(|n| *n == 0).expect("zero axis"),
            },
            _ => E::SiteCountOverflow,
        })?;
        let prepared = prepare(&method, shape, 0, &mut 0)?;
        Ok(Self {
            layout,
            geometry: None,
            method,
            prepared,
            key,
        })
    }

    /// Constructs a stream whose flat targets use this geometry's boundaries.
    /// Physical spacings do not rescale kernel radii.
    pub fn with_geometry(
        geometry: SquareLatticeGeometry,
        method: PairingMethod,
        rng: ResolvedRng,
    ) -> Result<Self, E> {
        let mut sampler = Self::new(geometry.shape(), method, rng)?;
        sampler.geometry = Some(geometry);
        Ok(sampler)
    }

    pub fn shape(&self) -> &[usize] {
        self.layout.shape()
    }
    pub fn rank(&self) -> usize {
        self.shape().len()
    }
    pub fn method(&self) -> &PairingMethod {
        &self.method
    }
    pub fn resolved_rng(&self) -> ResolvedRng {
        self.key.resolved_rng()
    }

    /// Returns canonical source and boundary-resolved target site indices.
    /// Fails if constructed without geometry. The pair index is global within
    /// the sweep, independent of iteration order, batch size, or worker count.
    pub fn pair_at(&self, sweep: u64, index: u64) -> Result<(usize, usize), E> {
        let geometry = self.geometry.as_ref().ok_or(E::MissingGeometry)?;
        let pair = self.sample(sweep, index);
        let target = self
            .layout
            .strides()
            .iter()
            .zip(self.shape())
            .enumerate()
            .map(|(axis, (&stride, &extent))| {
                geometry
                    .boundary()
                    .normalize(self.raw_target(&pair, axis), extent)
                    * stride
            })
            .sum();
        Ok((pair.source, target))
    }

    /// Parallel indexed iteration without building a pair batch.
    pub fn par_pairs(
        &self,
        sweep: u64,
        count: usize,
    ) -> Result<impl IndexedParallelIterator<Item = (usize, usize)> + '_, E> {
        if self.geometry.is_none() {
            return Err(E::MissingGeometry);
        }
        Ok((0..count)
            .into_par_iter()
            .with_min_len(crate::threading::parallel_chunk_len(count).unwrap_or(1))
            .map(move |i| {
                self.pair_at(sweep, i as u64)
                    .expect("geometry was validated")
            }))
    }

    /// Writes one raw pair into caller-owned rows. Validates all row lengths
    /// before writing, leaving the output unchanged on an invalid rank.
    pub fn pair_into(
        &self,
        sweep: u64,
        index: u64,
        source: &mut [isize],
        displacement: &mut [isize],
        target: &mut [isize],
    ) -> Result<(), E> {
        for actual in [source.len(), displacement.len(), target.len()] {
            if actual != self.rank() {
                return Err(E::OutputRankMismatch {
                    expected: self.rank(),
                    actual,
                });
            }
        }
        self.fill_unchecked(sweep, index, source, displacement, target);
        Ok(())
    }

    pub(super) fn fill_unchecked(
        &self,
        sweep: u64,
        index: u64,
        source: &mut [isize],
        displacement: &mut [isize],
        target: &mut [isize],
    ) -> usize {
        let pair = self.sample(sweep, index);
        for axis in 0..self.rank() {
            source[axis] = self.coordinate(pair.source, axis);
            target[axis] = self.raw_target(&pair, axis);
            displacement[axis] = target[axis] - source[axis];
        }
        pair.source
    }

    fn coordinate(&self, site: usize, axis: usize) -> isize {
        ((site / self.layout.strides()[axis]) % self.shape()[axis]) as isize
    }

    fn raw_target(&self, pair: &SampledPair, axis: usize) -> isize {
        match &pair.jump {
            Jump::Independent { target } => self.coordinate(*target, axis),
            _ => self.coordinate(pair.source, axis) + pair.jump.component(axis, self.rank()),
        }
    }

    fn sample(&self, sweep: u64, item: u64) -> SampledPair {
        let mut method = &self.prepared;
        while let PreparedMethod::Mixture { node, components } = method {
            let unit = self.key.unit_f64(sweep, d::PAIRING_MIXTURE, item, *node, 0);
            let selected = components
                .partition_point(|(upper, _)| *upper <= unit)
                .min(components.len() - 1);
            method = &components[selected].1;
        }
        match method {
            PreparedMethod::Independent => SampledPair {
                source: self
                    .key
                    .uniform_index(
                        sweep,
                        d::INDEPENDENT_SOURCE_SITE,
                        item,
                        0,
                        self.layout.size(),
                    )
                    .unwrap(),
                jump: Jump::Independent {
                    target: self
                        .key
                        .uniform_index(
                            sweep,
                            d::INDEPENDENT_TARGET_SITE,
                            item,
                            0,
                            self.layout.size(),
                        )
                        .unwrap(),
                },
            },
            PreparedMethod::Kernel {
                kernel,
                sources,
                kind,
            } => {
                let source = match sources {
                    SourceMode::Origin => 0,
                    SourceMode::RandomUniform => self
                        .key
                        .uniform_index(sweep, d::SOURCE_COORDINATE, item, 0, self.layout.size())
                        .unwrap(),
                };
                let jump = match kind {
                    KernelType::NearestNeighbor { dimension } => {
                        let code = self
                            .key
                            .uniform_index(sweep, d::HAAR_COMPONENT, item, 0, 2 * dimension)
                            .unwrap();
                        Jump::Nearest {
                            axis: code / 2,
                            sign: if code.is_multiple_of(2) { 1 } else { -1 },
                        }
                    }
                    KernelType::PowerLaw { c, .. } | KernelType::UniformDistance { c, .. } => {
                        let mut attempt = 0;
                        loop {
                            let length = kernel.sample_unit(self.key.unit_f64(
                                sweep,
                                d::KERNEL_SAMPLE,
                                item,
                                0,
                                attempt,
                            ));
                            let direction =
                                Direction::sample(self.key, sweep, item, self.rank(), attempt);
                            let jump = Jump::Radial { length, direction };
                            if self.rank() == 1
                                || *c < 1.0
                                || (0..self.rank())
                                    .any(|axis| jump.component(axis, self.rank()) != 0)
                            {
                                break jump;
                            }
                            attempt += 1;
                        }
                    }
                };
                SampledPair { source, jump }
            }
            PreparedMethod::Mixture { .. } => unreachable!("mixtures resolved above"),
        }
    }
}

/// Validated rules and cumulative mixture weights; never rebuilt in a sweep.
#[derive(Clone, Debug)]
enum PreparedMethod {
    Independent,
    Kernel {
        kernel: BuiltinKernel,
        sources: SourceMode,
        kind: KernelType,
    },
    Mixture {
        node: u64,
        components: Vec<(f64, PreparedMethod)>,
    },
}

fn prepare(
    method: &PairingMethod,
    shape: &[usize],
    depth: usize,
    next_node: &mut u64,
) -> Result<PreparedMethod, E> {
    if depth > 32 {
        return Err(E::MixtureTooDeep);
    }
    match method {
        PairingMethod::IndependentUniform => Ok(PreparedMethod::Independent),
        PairingMethod::Kernel { kernel, sources } => {
            let builtin = try_create_builtin_kernel(*kernel).map_err(E::Kernel)?;
            let radius = match kernel {
                KernelType::NearestNeighbor { dimension } => {
                    if *dimension != shape.len() {
                        return Err(E::KernelRankMismatch {
                            kernel_dimension: *dimension,
                            rank: shape.len(),
                        });
                    }
                    1.0
                }
                KernelType::PowerLaw { l, .. } | KernelType::UniformDistance { l, .. } => *l,
            };
            // Include the actual inverse-CDF endpoint and a floating-point
            // margin without changing the legacy rank-one inversion itself.
            let radius = if matches!(kernel, KernelType::NearestNeighbor { .. }) {
                radius
            } else {
                radius
                    .max(builtin.sample_unit(1.0 - f64::EPSILON / 2.0))
                    .next_up()
            };
            let source_max = if *sources == SourceMode::Origin {
                0
            } else {
                *shape.iter().max().unwrap() - 1
            };
            if (radius.ceil() as u128)
                .checked_add(source_max as u128)
                .is_none_or(|end| end > isize::MAX as u128)
            {
                return Err(E::CoordinateOverflow);
            }
            Ok(PreparedMethod::Kernel {
                kernel: builtin,
                sources: *sources,
                kind: *kernel,
            })
        }
        PairingMethod::Mixture { components } => {
            let total: f64 = components.iter().map(|(_, w)| *w).sum();
            if components.is_empty()
                || !total.is_finite()
                || total <= 0.0
                || components.iter().any(|(_, w)| !w.is_finite() || *w < 0.0)
            {
                return Err(E::InvalidMixture);
            }
            let node = *next_node;
            *next_node += 1;
            let mut cumulative = 0.0;
            let mut prepared = Vec::new();
            for (method, weight) in components {
                let child = prepare(method, shape, depth + 1, next_node)?;
                if *weight > 0.0 {
                    cumulative += weight / total;
                    prepared.push((cumulative, child));
                }
            }
            prepared.last_mut().expect("positive total").0 = 1.0;
            Ok(PreparedMethod::Mixture {
                node,
                components: prepared,
            })
        }
    }
}

struct SampledPair {
    source: usize,
    jump: Jump,
}

enum Jump {
    Independent { target: usize },
    Nearest { axis: usize, sign: isize },
    Radial { length: f64, direction: Direction },
}
impl Jump {
    fn component(&self, axis: usize, rank: usize) -> isize {
        match self {
            Self::Nearest {
                axis: selected,
                sign,
            } => {
                if axis == *selected {
                    *sign
                } else {
                    0
                }
            }
            Self::Radial { length, direction } => {
                let value = direction.component(axis) * length;
                if rank == 1 {
                    value as isize
                } else {
                    value.round() as isize
                }
            }
            Self::Independent { .. } => unreachable!("independent target is already a site"),
        }
    }
}

/// Constant-size representation of a Haar direction. Gaussian components can
/// be recomputed by coordinate without storing a rank-sized vector.
enum Direction {
    Sign(f64),
    Plane(f64, f64),
    Sphere(f64, f64, f64),
    Gaussian {
        key: IndexedRng,
        sweep: u64,
        item: u64,
        attempt: u64,
        norm: f64,
    },
}
impl Direction {
    fn sample(key: IndexedRng, sweep: u64, item: u64, rank: usize, attempt: u64) -> Self {
        match rank {
            1 => Self::Sign(
                if key
                    .uniform_index(sweep, d::HAAR_COMPONENT, item, 0, 2)
                    .unwrap()
                    == 0
                {
                    -1.0
                } else {
                    1.0
                },
            ),
            2 => {
                let angle = std::f64::consts::TAU
                    * key.unit_f64(sweep, d::HAAR_COMPONENT, item, 0, attempt);
                let (sin, cos) = angle.sin_cos();
                Self::Plane(cos, sin)
            }
            3 => {
                let z = 2.0 * key.unit_f64(sweep, d::HAAR_COMPONENT, item, 0, attempt) - 1.0;
                let phi = std::f64::consts::TAU
                    * key.unit_f64(sweep, d::HAAR_COMPONENT, item, 1, attempt);
                let (sin, cos) = phi.sin_cos();
                let radius = (1.0 - z * z).sqrt();
                Self::Sphere(radius * cos, radius * sin, z)
            }
            _ => {
                let norm = (0..rank)
                    .map(|axis| {
                        let value = normal(key, sweep, item, axis as u64, attempt);
                        value * value
                    })
                    .sum::<f64>()
                    .sqrt();
                Self::Gaussian {
                    key,
                    sweep,
                    item,
                    attempt,
                    norm,
                }
            }
        }
    }
    fn component(&self, axis: usize) -> f64 {
        match self {
            Self::Sign(x) => *x,
            Self::Plane(x, y) => {
                if axis == 0 {
                    *x
                } else {
                    *y
                }
            }
            Self::Sphere(x, y, z) => match axis {
                0 => *x,
                1 => *y,
                _ => *z,
            },
            Self::Gaussian {
                key,
                sweep,
                item,
                attempt,
                norm,
            } => normal(*key, *sweep, *item, axis as u64, *attempt) / norm,
        }
    }
}

fn normal(key: IndexedRng, sweep: u64, item: u64, axis: u64, attempt: u64) -> f64 {
    if attempt == 0 {
        return key.standard_normal(sweep, d::HAAR_COMPONENT, item, axis);
    }
    // Two distinct coordinates per Box-Muller attempt.
    let u1 = (((key.indexed_word(sweep, d::HAAR_COMPONENT, item, axis, attempt * 2) >> 11) as f64)
        + 0.5)
        / ((1_u64 << 53) as f64);
    let u2 = key.unit_f64(sweep, d::HAAR_COMPONENT, item, axis, attempt * 2 + 1);
    (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
}