Skip to main content

qslib_core/
geometry.rs

1use crate::{BasisError, Real, SiteCount, SiteId};
2use std::cmp::Ordering;
3use std::fmt::{self, Display, Formatter};
4
5/// Errors raised while constructing or querying a simulation geometry.
6#[derive(Clone, Debug, PartialEq)]
7pub enum GeometryError {
8    /// A lattice extent was zero.
9    InvalidExtent {
10        /// Extent name.
11        axis: &'static str,
12        /// Supplied extent.
13        value: usize,
14    },
15    /// A checked site-count or index calculation overflowed.
16    DimensionOverflow {
17        /// Checked operation that overflowed.
18        operation: &'static str,
19    },
20    /// A coordinate is outside the finite lattice domain.
21    CoordinateOutOfRange {
22        /// Horizontal coordinate.
23        x: isize,
24        /// Vertical coordinate.
25        y: isize,
26    },
27    /// A bond was requested from a site to itself.
28    SelfBond {
29        /// Site used at both endpoints.
30        site: SiteId,
31    },
32    /// A serialized bond is not in canonical endpoint or source form.
33    NonCanonicalBond {
34        /// First endpoint supplied by the caller.
35        first: SiteId,
36        /// Second endpoint supplied by the caller.
37        second: SiteId,
38    },
39    /// A site identifier is outside this geometry.
40    SiteOutOfRange {
41        /// Invalid site identifier.
42        site: u32,
43        /// Number of sites in the geometry.
44        site_count: usize,
45    },
46    /// A custom geometry contained no sites.
47    EmptyCustomGeometry,
48    /// A custom coordinate was not finite.
49    NonFiniteCoordinate {
50        /// Coordinate index when known.
51        index: usize,
52    },
53    /// A shell target or tolerance was invalid.
54    InvalidShell {
55        /// Invalid target or tolerance value.
56        value: Real,
57    },
58}
59
60impl Display for GeometryError {
61    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
62        match self {
63            Self::InvalidExtent { axis, value } => {
64                write!(formatter, "{axis} extent {value} is invalid")
65            }
66            Self::DimensionOverflow { operation } => {
67                write!(formatter, "geometry {operation} overflowed")
68            }
69            Self::CoordinateOutOfRange { x, y } => {
70                write!(formatter, "coordinate ({x}, {y}) is outside the geometry")
71            }
72            Self::SelfBond { site } => {
73                write!(formatter, "site {} cannot form a self-bond", site.get())
74            }
75            Self::NonCanonicalBond { first, second } => write!(
76                formatter,
77                "bond endpoints {} and {} are not in canonical form",
78                first.get(),
79                second.get()
80            ),
81            Self::SiteOutOfRange { site, site_count } => write!(
82                formatter,
83                "site {site} is outside a {site_count}-site geometry"
84            ),
85            Self::EmptyCustomGeometry => {
86                formatter.write_str("a custom geometry must contain at least one site")
87            }
88            Self::NonFiniteCoordinate { index } => {
89                write!(formatter, "custom coordinate {index} is non-finite")
90            }
91            Self::InvalidShell { value } => {
92                write!(formatter, "shell parameter {value:?} is invalid")
93            }
94        }
95    }
96}
97
98impl std::error::Error for GeometryError {}
99
100/// Boundary condition applied independently to a lattice direction.
101#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
102pub enum Boundary {
103    /// Do not wrap a neighbour leaving the finite domain.
104    Open,
105    /// Identify opposite faces of the finite domain.
106    Periodic,
107}
108
109/// Multiplicity policy for generated lattice bonds.
110#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
111pub enum BondMultiplicity {
112    /// Keep each unordered endpoint pair once.
113    Simple,
114    /// Keep every generated periodic image or directed lattice step.
115    PeriodicImages,
116}
117
118/// Tolerance policy for selecting a squared-distance shell.
119#[derive(Clone, Copy, Debug, PartialEq)]
120pub enum ShellTolerance {
121    /// Accept `|d² - target²| <= epsilon`.
122    Absolute(Real),
123    /// Accept `|d² - target²| <= epsilon * |target²|`.
124    Relative(Real),
125}
126
127/// Real-space embedding used by a rectangular coordinate grid.
128#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
129pub enum LatticeKind {
130    /// Orthogonal square or rectangular embedding.
131    Square,
132    /// The canonical triangular embedding.
133    Triangular,
134}
135
136/// Explicit adapter for legacy x-major flat indexing.
137#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
138pub struct XMajorAdapter {
139    lx: usize,
140    ly: usize,
141}
142
143impl XMajorAdapter {
144    /// Construct an adapter for an `Lx` by `Ly` rectangular array.
145    pub fn new(lx: usize, ly: usize) -> Result<Self, GeometryError> {
146        if lx == 0 {
147            return Err(GeometryError::InvalidExtent {
148                axis: "x",
149                value: lx,
150            });
151        }
152        if ly == 0 {
153            return Err(GeometryError::InvalidExtent {
154                axis: "y",
155                value: ly,
156            });
157        }
158        let total = lx.checked_mul(ly).ok_or(GeometryError::DimensionOverflow {
159            operation: "site count",
160        })?;
161        if total > u32::MAX as usize {
162            return Err(GeometryError::DimensionOverflow {
163                operation: "site identifier",
164            });
165        }
166        Ok(Self { lx, ly })
167    }
168
169    /// Convert a legacy x-major identifier to canonical row-major order.
170    pub fn to_canonical(&self, legacy: SiteId) -> Result<SiteId, GeometryError> {
171        let index = legacy.get() as usize;
172        let total = self.lx * self.ly;
173        if index >= total {
174            return Err(GeometryError::SiteOutOfRange {
175                site: legacy.get(),
176                site_count: total,
177            });
178        }
179        let x = index / self.ly;
180        let y = index % self.ly;
181        SiteId::try_from_usize(x + self.lx * y).map_err(|_| GeometryError::DimensionOverflow {
182            operation: "site identifier",
183        })
184    }
185
186    /// Convert a canonical row-major identifier to legacy x-major order.
187    pub fn from_canonical(&self, canonical: SiteId) -> Result<SiteId, GeometryError> {
188        let index = canonical.get() as usize;
189        let total = self.lx * self.ly;
190        if index >= total {
191            return Err(GeometryError::SiteOutOfRange {
192                site: canonical.get(),
193                site_count: total,
194            });
195        }
196        let x = index % self.lx;
197        let y = index / self.lx;
198        SiteId::try_from_usize(x * self.ly + y).map_err(|_| GeometryError::DimensionOverflow {
199            operation: "site identifier",
200        })
201    }
202}
203
204/// A finite Cartesian coordinate associated with one canonical site.
205#[derive(Clone, Copy, Debug, PartialEq)]
206pub struct Coordinate {
207    x: Real,
208    y: Real,
209}
210
211impl Coordinate {
212    /// Construct a finite Cartesian coordinate.
213    pub fn new(x: Real, y: Real) -> Result<Self, GeometryError> {
214        if x.is_finite() && y.is_finite() {
215            Ok(Self { x, y })
216        } else {
217            Err(GeometryError::NonFiniteCoordinate { index: 0 })
218        }
219    }
220
221    /// Return the horizontal coordinate.
222    pub const fn x(self) -> Real {
223        self.x
224    }
225
226    /// Return the vertical coordinate.
227    pub const fn y(self) -> Real {
228        self.y
229    }
230
231    /// Return `(x, y)` for compact comparisons and serialization adapters.
232    pub const fn as_tuple(self) -> (Real, Real) {
233        (self.x, self.y)
234    }
235}
236
237/// An undirected bond with an optional periodic-image translation.
238#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
239pub struct Bond {
240    first: SiteId,
241    second: SiteId,
242    image_x: i32,
243    image_y: i32,
244    source: SiteId,
245    direction_x: i8,
246    direction_y: i8,
247}
248
249impl Bond {
250    /// Construct a canonical simple bond between two distinct sites.
251    pub fn new(a: SiteId, b: SiteId) -> Result<Self, GeometryError> {
252        if a == b {
253            return Err(GeometryError::SelfBond { site: a });
254        }
255        let (first, second) = if a < b { (a, b) } else { (b, a) };
256        Ok(Self {
257            first,
258            second,
259            image_x: 0,
260            image_y: 0,
261            source: first,
262            direction_x: 0,
263            direction_y: 0,
264        })
265    }
266
267    /// Reconstruct a canonical bond from its complete serialized identity.
268    ///
269    /// This constructor is intended for durable artifact adapters. The
270    /// endpoints must already be in canonical order; no site-order conversion
271    /// or periodic-image reinterpretation is performed implicitly.
272    pub fn from_parts(
273        first: SiteId,
274        second: SiteId,
275        image_x: i32,
276        image_y: i32,
277        source: SiteId,
278        direction_x: i8,
279        direction_y: i8,
280    ) -> Result<Self, GeometryError> {
281        if first >= second || (source != first && source != second) {
282            return Err(GeometryError::NonCanonicalBond { first, second });
283        }
284        Ok(Self {
285            first,
286            second,
287            image_x,
288            image_y,
289            source,
290            direction_x,
291            direction_y,
292        })
293    }
294
295    /// Return a canonical bond carrying a periodic image translation.
296    pub(crate) fn with_image(
297        a: SiteId,
298        b: SiteId,
299        image_x: i32,
300        image_y: i32,
301        direction_x: isize,
302        direction_y: isize,
303    ) -> Result<Self, GeometryError> {
304        let mut bond = Self::new(a, b)?;
305        if a > b {
306            bond.image_x = -image_x;
307            bond.image_y = -image_y;
308        } else {
309            bond.image_x = image_x;
310            bond.image_y = image_y;
311        }
312        bond.source = a;
313        bond.direction_x =
314            i8::try_from(direction_x).map_err(|_| GeometryError::DimensionOverflow {
315                operation: "bond direction",
316            })?;
317        bond.direction_y =
318            i8::try_from(direction_y).map_err(|_| GeometryError::DimensionOverflow {
319                operation: "bond direction",
320            })?;
321        Ok(bond)
322    }
323
324    /// Return the first canonical endpoint.
325    pub const fn first(self) -> SiteId {
326        self.first
327    }
328
329    /// Return the second canonical endpoint.
330    pub const fn second(self) -> SiteId {
331        self.second
332    }
333
334    /// Return the periodic image translation in lattice-cell units.
335    pub const fn image_translation(self) -> (i32, i32) {
336        (self.image_x, self.image_y)
337    }
338
339    /// Return the directed source site used to generate this image.
340    pub const fn source(self) -> SiteId {
341        self.source
342    }
343
344    /// Return the lattice step that generated this image.
345    pub const fn direction(self) -> (i8, i8) {
346        (self.direction_x, self.direction_y)
347    }
348}
349
350impl Ord for Bond {
351    fn cmp(&self, other: &Self) -> Ordering {
352        (
353            self.first,
354            self.second,
355            self.image_x,
356            self.image_y,
357            self.source,
358            self.direction_x,
359            self.direction_y,
360        )
361            .cmp(&(
362                other.first,
363                other.second,
364                other.image_x,
365                other.image_y,
366                other.source,
367                other.direction_x,
368                other.direction_y,
369            ))
370    }
371}
372
373impl PartialOrd for Bond {
374    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
375        Some(self.cmp(other))
376    }
377}
378
379/// A rectangular lattice with explicit row-major site order and boundaries.
380#[derive(Clone, Debug, PartialEq)]
381pub struct RectangularGeometry {
382    lx: usize,
383    ly: usize,
384    boundary_x: Boundary,
385    boundary_y: Boundary,
386    kind: LatticeKind,
387    site_count: SiteCount,
388}
389
390impl RectangularGeometry {
391    /// Construct an orthogonal rectangular geometry.
392    pub fn new(
393        lx: usize,
394        ly: usize,
395        boundary_x: Boundary,
396        boundary_y: Boundary,
397    ) -> Result<Self, GeometryError> {
398        Self::with_kind(lx, ly, boundary_x, boundary_y, LatticeKind::Square)
399    }
400
401    /// Construct a rectangular coordinate grid with an explicit embedding.
402    pub fn with_kind(
403        lx: usize,
404        ly: usize,
405        boundary_x: Boundary,
406        boundary_y: Boundary,
407        kind: LatticeKind,
408    ) -> Result<Self, GeometryError> {
409        if lx == 0 {
410            return Err(GeometryError::InvalidExtent {
411                axis: "x",
412                value: lx,
413            });
414        }
415        if ly == 0 {
416            return Err(GeometryError::InvalidExtent {
417                axis: "y",
418                value: ly,
419            });
420        }
421        let site_total = lx.checked_mul(ly).ok_or(GeometryError::DimensionOverflow {
422            operation: "site count",
423        })?;
424        if site_total > u32::MAX as usize {
425            return Err(GeometryError::DimensionOverflow {
426                operation: "site identifier",
427            });
428        }
429        let site_count = SiteCount::new(site_total).map_err(|_| GeometryError::InvalidExtent {
430            axis: "sites",
431            value: site_total,
432        })?;
433        Ok(Self {
434            lx,
435            ly,
436            boundary_x,
437            boundary_y,
438            kind,
439            site_count,
440        })
441    }
442
443    /// Number of sites.
444    pub const fn site_count(&self) -> SiteCount {
445        self.site_count
446    }
447
448    /// Return the horizontal extent.
449    pub const fn lx(&self) -> usize {
450        self.lx
451    }
452
453    /// Return the vertical extent.
454    pub const fn ly(&self) -> usize {
455        self.ly
456    }
457
458    /// Return the horizontal boundary condition.
459    pub const fn boundary_x(&self) -> Boundary {
460        self.boundary_x
461    }
462
463    /// Return the vertical boundary condition.
464    pub const fn boundary_y(&self) -> Boundary {
465        self.boundary_y
466    }
467
468    /// Return the selected embedding.
469    pub const fn kind(&self) -> LatticeKind {
470        self.kind
471    }
472
473    /// Map row-major `(x, y)` coordinates to a site identifier.
474    pub fn site_id(&self, x: usize, y: usize) -> Result<SiteId, GeometryError> {
475        if x >= self.lx || y >= self.ly {
476            return Err(GeometryError::CoordinateOutOfRange {
477                x: x as isize,
478                y: y as isize,
479            });
480        }
481        let index = x
482            .checked_add(
483                y.checked_mul(self.lx)
484                    .ok_or(GeometryError::DimensionOverflow {
485                        operation: "row-major index",
486                    })?,
487            )
488            .ok_or(GeometryError::DimensionOverflow {
489                operation: "row-major index",
490            })?;
491        SiteId::try_from_usize(index).map_err(|error| match error {
492            BasisError::IdentifierOverflow { value } => GeometryError::DimensionOverflow {
493                operation: if value > u32::MAX as usize {
494                    "site identifier"
495                } else {
496                    "row-major index"
497                },
498            },
499            _ => GeometryError::DimensionOverflow {
500                operation: "site identifier",
501            },
502        })
503    }
504
505    /// Map a canonical site identifier to its row-major coordinate.
506    pub fn coordinate(&self, site: SiteId) -> Result<Coordinate, GeometryError> {
507        if site.get() as usize >= self.lx * self.ly {
508            return Err(GeometryError::SiteOutOfRange {
509                site: site.get(),
510                site_count: self.lx * self.ly,
511            });
512        }
513        let x = (site.get() as usize) % self.lx;
514        let y = (site.get() as usize) / self.lx;
515        let (x, y) = (x as Real, y as Real);
516        match self.kind {
517            LatticeKind::Square => Coordinate::new(x, y),
518            LatticeKind::Triangular => Coordinate::new(x + 0.5 * y, 3.0_f64.sqrt() * 0.5 * y),
519        }
520    }
521
522    /// Return the canonical minimum-image Cartesian displacement `r_b - r_a`.
523    pub fn minimum_image_displacement(
524        &self,
525        a: SiteId,
526        b: SiteId,
527    ) -> Result<Coordinate, GeometryError> {
528        let ca = self.coordinate(a)?;
529        let cb = self.coordinate(b)?;
530        let raw = (cb.x - ca.x, cb.y - ca.y);
531        if self.kind == LatticeKind::Square {
532            let dx = if self.boundary_x == Boundary::Periodic {
533                raw.0
534                    - self.lx as Real * ((raw.0 + 0.5 * self.lx as Real) / self.lx as Real).floor()
535            } else {
536                raw.0
537            };
538            let dy = if self.boundary_y == Boundary::Periodic {
539                raw.1
540                    - self.ly as Real * ((raw.1 + 0.5 * self.ly as Real) / self.ly as Real).floor()
541            } else {
542                raw.1
543            };
544            return Coordinate::new(dx, dy);
545        }
546        let mut best = raw;
547        let mut best_norm = raw.0 * raw.0 + raw.1 * raw.1;
548        let mut best_translation = (0_i64, 0_i64);
549        let cell_y = 3.0_f64.sqrt() * 0.5 * self.ly as Real;
550        let radius = best_norm.sqrt();
551        let (y_start, y_end) = if self.boundary_y == Boundary::Periodic {
552            (
553                ((raw.1 - radius) / cell_y).floor() as i64,
554                ((raw.1 + radius) / cell_y).ceil() as i64,
555            )
556        } else {
557            (0, 0)
558        };
559        for ty in y_start..=y_end {
560            let residual_x = raw.0 - 0.5 * self.ly as Real * ty as Real;
561            let x_radius = (best_norm - (raw.1 - cell_y * ty as Real).powi(2))
562                .max(0.0)
563                .sqrt();
564            let (x_start, x_end) = if self.boundary_x == Boundary::Periodic {
565                (
566                    ((residual_x - x_radius) / self.lx as Real).floor() as i64,
567                    ((residual_x + x_radius) / self.lx as Real).ceil() as i64,
568                )
569            } else {
570                (0, 0)
571            };
572            for tx in x_start..=x_end {
573                if tx == 0 && ty == 0 {
574                    continue;
575                }
576                let sx = tx as Real * self.lx as Real + 0.5 * ty as Real * self.ly as Real;
577                let sy = cell_y * ty as Real;
578                let candidate = (raw.0 - sx, raw.1 - sy);
579                let norm = candidate.0 * candidate.0 + candidate.1 * candidate.1;
580                if norm < best_norm || (norm == best_norm && (tx, ty) < best_translation) {
581                    best = candidate;
582                    best_norm = norm;
583                    best_translation = (tx, ty);
584                }
585            }
586        }
587        Coordinate::new(best.0, best.1)
588    }
589
590    /// Return unordered pairs whose minimum-image squared distance lies in a shell.
591    pub fn pairs_at_squared_distance(
592        &self,
593        target_squared: Real,
594        tolerance: ShellTolerance,
595    ) -> Result<Vec<Bond>, GeometryError> {
596        if !target_squared.is_finite() || target_squared < 0.0 {
597            return Err(GeometryError::InvalidShell {
598                value: target_squared,
599            });
600        }
601        let epsilon = match tolerance {
602            ShellTolerance::Absolute(value) | ShellTolerance::Relative(value)
603                if value.is_finite() && value >= 0.0 =>
604            {
605                value
606            }
607            ShellTolerance::Absolute(value) | ShellTolerance::Relative(value) => {
608                return Err(GeometryError::InvalidShell { value });
609            }
610        };
611        let mut result = Vec::new();
612        for i in 0..self.site_count.get() {
613            for j in (i + 1)..self.site_count.get() {
614                let displacement =
615                    self.minimum_image_displacement(SiteId::new(i as u32), SiteId::new(j as u32))?;
616                let squared = displacement.x * displacement.x + displacement.y * displacement.y;
617                let allowed = match tolerance {
618                    ShellTolerance::Absolute(_) => epsilon,
619                    ShellTolerance::Relative(_) => epsilon * target_squared.abs(),
620                };
621                if (squared - target_squared).abs() <= allowed {
622                    result.push(Bond::new(SiteId::new(i as u32), SiteId::new(j as u32))?);
623                }
624            }
625        }
626        Ok(result)
627    }
628
629    /// Generate canonical bonds under the requested multiplicity policy.
630    pub fn bonds(&self, multiplicity: BondMultiplicity) -> Result<Vec<Bond>, GeometryError> {
631        let mut bonds = Vec::new();
632        let directions: &[(isize, isize)] = match self.kind {
633            LatticeKind::Square => &[(1, 0), (0, 1)],
634            LatticeKind::Triangular => &[(1, 0), (0, 1), (1, -1)],
635        };
636        for y in 0..self.ly {
637            for x in 0..self.lx {
638                let source = self.site_id(x, y)?;
639                for &(dx, dy) in directions {
640                    if let Some((target, ix, iy)) = self.step(x, y, dx, dy) {
641                        let candidate = if multiplicity == BondMultiplicity::Simple {
642                            Bond::new(source, target)?
643                        } else {
644                            Bond::with_image(source, target, ix, iy, dx, dy)?
645                        };
646                        if multiplicity == BondMultiplicity::PeriodicImages
647                            || !bonds.iter().any(|bond: &Bond| {
648                                bond.first() == candidate.first()
649                                    && bond.second() == candidate.second()
650                            })
651                        {
652                            bonds.push(candidate);
653                        }
654                    }
655                }
656            }
657        }
658        bonds.sort_unstable();
659        Ok(bonds)
660    }
661
662    fn step(&self, x: usize, y: usize, dx: isize, dy: isize) -> Option<(SiteId, i32, i32)> {
663        let nx = x as isize + dx;
664        let ny = y as isize + dy;
665        let (nx, ix) = wrap(nx, self.lx, self.boundary_x)?;
666        let (ny, iy) = wrap(ny, self.ly, self.boundary_y)?;
667        let target = self.site_id(nx, ny).ok()?;
668        if target == self.site_id(x, y).ok()? {
669            return None;
670        }
671        Some((target, ix, iy))
672    }
673}
674
675fn wrap(value: isize, extent: usize, boundary: Boundary) -> Option<(usize, i32)> {
676    if (0..extent as isize).contains(&value) {
677        return Some((value as usize, 0));
678    }
679    match boundary {
680        Boundary::Open => None,
681        Boundary::Periodic => {
682            let extent = extent as isize;
683            let quotient = value.div_euclid(extent);
684            Some((value.rem_euclid(extent) as usize, quotient as i32))
685        }
686    }
687}
688
689/// A custom ordered collection of finite Cartesian sites.
690#[derive(Clone, Debug, PartialEq)]
691pub struct CustomGeometry {
692    coordinates: Vec<Coordinate>,
693    site_count: SiteCount,
694}
695
696impl CustomGeometry {
697    /// Construct a custom geometry; vector position is the canonical site id.
698    pub fn new(coordinates: Vec<Coordinate>) -> Result<Self, GeometryError> {
699        if coordinates.is_empty() {
700            return Err(GeometryError::EmptyCustomGeometry);
701        }
702        if coordinates.len() > u32::MAX as usize {
703            return Err(GeometryError::DimensionOverflow {
704                operation: "site identifier",
705            });
706        }
707        let site_count =
708            SiteCount::new(coordinates.len()).map_err(|_| GeometryError::EmptyCustomGeometry)?;
709        Ok(Self {
710            coordinates,
711            site_count,
712        })
713    }
714
715    /// Number of custom sites.
716    pub const fn site_count(&self) -> SiteCount {
717        self.site_count
718    }
719
720    /// Return a custom site's coordinate.
721    pub fn coordinate(&self, site: SiteId) -> Result<Coordinate, GeometryError> {
722        self.coordinates
723            .get(site.get() as usize)
724            .copied()
725            .ok_or(GeometryError::SiteOutOfRange {
726                site: site.get(),
727                site_count: self.coordinates.len(),
728            })
729    }
730
731    /// Generate the complete simple graph of unordered custom-site pairs.
732    pub fn complete_bonds(&self) -> Result<Vec<Bond>, GeometryError> {
733        let mut result = Vec::new();
734        for i in 0..self.coordinates.len() {
735            for j in (i + 1)..self.coordinates.len() {
736                result.push(Bond::new(
737                    SiteId::try_from_usize(i).map_err(|_| GeometryError::DimensionOverflow {
738                        operation: "site identifier",
739                    })?,
740                    SiteId::try_from_usize(j).map_err(|_| GeometryError::DimensionOverflow {
741                        operation: "site identifier",
742                    })?,
743                )?);
744            }
745        }
746        Ok(result)
747    }
748}