1use crate::{BasisError, Real, SiteCount, SiteId};
2use std::cmp::Ordering;
3use std::fmt::{self, Display, Formatter};
4
5#[derive(Clone, Debug, PartialEq)]
7pub enum GeometryError {
8 InvalidExtent {
10 axis: &'static str,
12 value: usize,
14 },
15 DimensionOverflow {
17 operation: &'static str,
19 },
20 CoordinateOutOfRange {
22 x: isize,
24 y: isize,
26 },
27 SelfBond {
29 site: SiteId,
31 },
32 NonCanonicalBond {
34 first: SiteId,
36 second: SiteId,
38 },
39 SiteOutOfRange {
41 site: u32,
43 site_count: usize,
45 },
46 EmptyCustomGeometry,
48 NonFiniteCoordinate {
50 index: usize,
52 },
53 InvalidShell {
55 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#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
102pub enum Boundary {
103 Open,
105 Periodic,
107}
108
109#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
111pub enum BondMultiplicity {
112 Simple,
114 PeriodicImages,
116}
117
118#[derive(Clone, Copy, Debug, PartialEq)]
120pub enum ShellTolerance {
121 Absolute(Real),
123 Relative(Real),
125}
126
127#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
129pub enum LatticeKind {
130 Square,
132 Triangular,
134}
135
136#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
138pub struct XMajorAdapter {
139 lx: usize,
140 ly: usize,
141}
142
143impl XMajorAdapter {
144 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 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 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#[derive(Clone, Copy, Debug, PartialEq)]
206pub struct Coordinate {
207 x: Real,
208 y: Real,
209}
210
211impl Coordinate {
212 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 pub const fn x(self) -> Real {
223 self.x
224 }
225
226 pub const fn y(self) -> Real {
228 self.y
229 }
230
231 pub const fn as_tuple(self) -> (Real, Real) {
233 (self.x, self.y)
234 }
235}
236
237#[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 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 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 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 pub const fn first(self) -> SiteId {
326 self.first
327 }
328
329 pub const fn second(self) -> SiteId {
331 self.second
332 }
333
334 pub const fn image_translation(self) -> (i32, i32) {
336 (self.image_x, self.image_y)
337 }
338
339 pub const fn source(self) -> SiteId {
341 self.source
342 }
343
344 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#[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 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 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 pub const fn site_count(&self) -> SiteCount {
445 self.site_count
446 }
447
448 pub const fn lx(&self) -> usize {
450 self.lx
451 }
452
453 pub const fn ly(&self) -> usize {
455 self.ly
456 }
457
458 pub const fn boundary_x(&self) -> Boundary {
460 self.boundary_x
461 }
462
463 pub const fn boundary_y(&self) -> Boundary {
465 self.boundary_y
466 }
467
468 pub const fn kind(&self) -> LatticeKind {
470 self.kind
471 }
472
473 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 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 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 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 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#[derive(Clone, Debug, PartialEq)]
691pub struct CustomGeometry {
692 coordinates: Vec<Coordinate>,
693 site_count: SiteCount,
694}
695
696impl CustomGeometry {
697 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 pub const fn site_count(&self) -> SiteCount {
717 self.site_count
718 }
719
720 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 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}