Skip to main content

seams/
lib.rs

1/* Copyright (c) d-SEAMS developers */
2//! Safe calls into the d-SEAMS C API.
3//!
4//! [d-SEAMS](https://dseams.info) classifies the molecules of a simulation
5//! frame. This crate gives Rust programs its analyses: CHILL and CHILL+ ice
6//! labels, Steinhardt order parameters, primitive rings, cages, radial
7//! distribution functions, hydrogen bonds, topological fingerprints and
8//! planar brine fronts.
9//!
10//! The crates.io package is `dseams`. The library keeps the name `seams`,
11//! so code says `use seams::System`.
12//!
13//! # Quick example
14//!
15//! Coordinates and cutoffs are in angstroms. This program classifies the
16//! eight-atom cubic ice cell that [`diamond8`] returns:
17//!
18//! ```
19//! let (xyz, edge) = seams::diamond8();
20//! seams::set_num_threads(1)?;
21//! let mut system = seams::System::new()?;
22//! system.set_ortho(&xyz, edge, edge, edge)?;
23//! assert_eq!(system.count(), 8);
24//! let ice = system.chill_plus(&seams::ChillOptions::default())?;
25//! assert_eq!(ice.counts[seams::Label::Cubic as usize], 8);
26//! let orders = system.q4q6(3.5)?;
27//! assert!(orders.q6.iter().all(|value| value.is_finite()));
28//! # Ok::<(), seams::Error>(())
29//! ```
30//!
31//! # How the crate is organised
32//!
33//! A [`System`] holds one frame. [`System::set_ortho`], [`System::set_frame`],
34//! [`System::set_atoms`] and [`System::read`] fill it, and every analysis is
35//! a method on it. A cell is nine numbers in the LAMMPS order: origin, edge
36//! lengths, then the tilts `xy`, `xz` and `yz`.
37//!
38//! - Ice labels: [`System::chill`] and [`System::chill_plus`] return a
39//!   [`Classification`] indexed by [`Label`]. They take [`ChillOptions`].
40//! - Order parameters: [`System::q4q6`], [`System::steinhardt`],
41//!   [`System::ql`] and [`System::q6bar`].
42//! - Structure: [`System::neighbours`] gives [`Neighbours`],
43//!   [`System::rings`] gives [`Rings`], and [`System::cages`] gives [`Cages`].
44//!   [`System::signature_cages`] counts closed cages by ring signature.
45//! - Periodic geometry: [`System::voronoi`] gives [`VoronoiCells`].
46//! - Distributions and bonds: [`System::rdf`], [`System::running_cn`],
47//!   [`System::density`], [`System::hbonds`] and [`System::directed_hbonds`].
48//!   [`HbondLifetimeAccumulator`] follows ordered or unordered bond pairs across frames.
49//! - Topology: [`System::fingerprint`], [`System::prisms`] and
50//!   [`System::domains`].
51//! - Ice fronts in brine: [`System::brine`] gives [`Brine`].
52//!
53//! Analyses with several settings take an options struct that implements
54//! `Default`, so you change only the fields you need. Neighbour lists and
55//! rings can be iterated.
56//!
57//! # Errors, ownership and threads
58//!
59//! Every call that can fail returns [`Result<T, Error>`](Result). An
60//! [`Error`] carries the engine's message and, when the crate names it, a
61//! [`Status`]. Each handle ([`System`], [`Neighbours`], [`Rings`], [`Cages`],
62//! [`Fingerprint`], [`Brine`] and [`VoronoiCells`]) owns a native object and frees it in
63//! [`Drop`].
64//!
65//! A handle may move to another thread ([`Send`]). It is not [`Sync`],
66//! because the C library requires exclusive use of a handle. Separate
67//! handles may run the Steinhardt calls on separate threads. The OpenMP
68//! width set by [`set_num_threads`] is process-global.
69//!
70//! # Choosing a libseams
71//!
72//! The `dseams-sys` build script links the shared `libseams` in the
73//! directory named by `SEAMS_LIBDIR` when that variable is set. Otherwise it
74//! uses the `bundled` feature, which compiles the engine from source and
75//! reads LAMMPS dumps and XYZ files, or an installed library found through
76//! pkg-config. A bundled build also enables chemfiles and readcon-core when
77//! pkg-config finds them. [`has_chemfiles`] and [`has_readcon`] report the
78//! linked engine's readers. `cargo add dseams --features bundled` is the
79//! shortest way to a working build.
80//!
81//! The raw C declarations are re-exported as [`ffi`].
82//!
83//! # Learn more
84//!
85//! The [book](https://rust.dseams.info) has a getting-started page and
86//! tutorials that run the analyses on real frames. The
87//! [engine book](https://docs.dseams.info) covers the science behind each
88//! analysis.
89
90#![deny(missing_docs)]
91
92pub use seams_sys as ffi;
93
94/// The crate README, compiled and run by `cargo test` as doctests.
95#[cfg(doctest)]
96#[doc = include_str!("../README.md")]
97struct ReadmeDoctests;
98
99use std::ffi::{CStr, CString};
100use std::os::raw::{c_char, c_int, c_void};
101
102/// Status codes. The numeric values match `seams_status`.
103///
104/// ```
105/// assert_eq!(seams::Status::Ok as i32, 0);
106/// assert_eq!(seams::Status::State as i32, 5);
107/// ```
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109#[repr(i32)]
110pub enum Status {
111    /// The call succeeded.
112    Ok = 0,
113    /// A required pointer is null.
114    Null = 1,
115    /// A number is outside the accepted range.
116    Range = 2,
117    /// The cell is missing or has no volume.
118    Cell = 3,
119    /// A caller argument is the wrong shape.
120    Argument = 4,
121    /// The handle has no frame yet.
122    State = 5,
123    /// An allocation failed.
124    Memory = 6,
125    /// The library hit an internal failure.
126    Internal = 7,
127}
128
129impl Status {
130    fn from_code(code: i32) -> Option<Self> {
131        Some(match code {
132            0 => Self::Ok,
133            1 => Self::Null,
134            2 => Self::Range,
135            3 => Self::Cell,
136            4 => Self::Argument,
137            5 => Self::State,
138            6 => Self::Memory,
139            7 => Self::Internal,
140            _ => return None,
141        })
142    }
143
144    fn as_str(self) -> &'static str {
145        match self {
146            Self::Ok => "ok",
147            Self::Null => "null pointer",
148            Self::Range => "out of range",
149            Self::Cell => "bad cell",
150            Self::Argument => "bad argument",
151            Self::State => "no frame",
152            Self::Memory => "out of memory",
153            Self::Internal => "internal error",
154        }
155    }
156}
157
158/// Neighbour graph.
159///
160/// ```
161/// assert_eq!(seams::Graph::Cutoff as i32, 0);
162/// assert_eq!(seams::Graph::Mutual as i32, 1);
163/// assert_eq!(seams::Graph::Seeded as i32, 2);
164/// ```
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166#[repr(i32)]
167pub enum Graph {
168    /// Every pair inside the cutoff.
169    Cutoff = ffi::SEAMS_GRAPH_CUTOFF,
170    /// Mutual four-nearest neighbours.
171    Mutual = ffi::SEAMS_GRAPH_MUTUAL,
172    /// Cage graph: mutual seeds and union completions.
173    Seeded = ffi::SEAMS_GRAPH_SEEDED,
174}
175
176/// CHILL+ threshold table.
177///
178/// Published edges are inclusive. OVITO edges are open.
179///
180/// ```
181/// assert_eq!(seams::ChillRule::Published as i32, 0);
182/// assert_eq!(seams::ChillRule::Ovito as i32, 1);
183/// ```
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185#[repr(i32)]
186pub enum ChillRule {
187    /// Nguyen and Molinero, 2015.
188    Published = ffi::SEAMS_CHILL_PUBLISHED,
189    /// OVITO Chill+ modifier.
190    Ovito = ffi::SEAMS_CHILL_OVITO,
191}
192
193/// CHILL and CHILL+ atom label. `Classification::counts[label as usize]` is the population.
194///
195/// ```
196/// assert_eq!(seams::Label::Hexagonal as i32, 1);
197/// assert_eq!(seams::label_name(seams::Label::Hexagonal), "hexagonal");
198/// ```
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200#[repr(i32)]
201pub enum Label {
202    /// Cubic ice.
203    Cubic = ffi::SEAMS_LABEL_CUBIC,
204    /// Hexagonal ice.
205    Hexagonal = ffi::SEAMS_LABEL_HEXAGONAL,
206    /// Liquid water.
207    Water = ffi::SEAMS_LABEL_WATER,
208    /// Interfacial ice.
209    Interfacial = ffi::SEAMS_LABEL_INTERFACIAL,
210    /// Clathrate.
211    Clathrate = ffi::SEAMS_LABEL_CLATHRATE,
212    /// Interfacial clathrate.
213    Interclathrate = ffi::SEAMS_LABEL_INTERCLATHRATE,
214    /// No class matched.
215    Unclassified = ffi::SEAMS_LABEL_UNCLASSIFIED,
216    /// Reclassified cubic.
217    Recubic = ffi::SEAMS_LABEL_RECUBIC,
218    /// Reclassified hexagonal.
219    Rehex = ffi::SEAMS_LABEL_REHEX,
220}
221
222/// Primitive-ring symmetry class.
223///
224/// ```
225/// assert_eq!(seams::ring_symmetry_name(seams::RingSymmetry::Hexagon), "hexagon");
226/// ```
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228#[repr(i32)]
229pub enum RingSymmetry {
230    /// No class yet.
231    Unclassified = ffi::SEAMS_RING_UNCLASSIFIED,
232    /// Double-diamond six-ring.
233    Ddc = ffi::SEAMS_RING_DDC,
234    /// Basal face of a hexagonal cage.
235    HcBasal = ffi::SEAMS_RING_HC_BASAL,
236    /// Prismatic face of a hexagonal cage.
237    HcPrismatic = ffi::SEAMS_RING_HC_PRISMATIC,
238    /// Basal face of both cage types.
239    BothBasal = ffi::SEAMS_RING_BOTH_BASAL,
240    /// Prismatic face of both cage types.
241    BothPrismatic = ffi::SEAMS_RING_BOTH_PRISMATIC,
242    /// Prismatic six-ring.
243    Prism = ffi::SEAMS_RING_PRISM,
244    /// Deformed prismatic six-ring.
245    DeformedPrism = ffi::SEAMS_RING_DEFORMED_PRISM,
246    /// Prism mixing the two cage types.
247    MixedPrism = ffi::SEAMS_RING_MIXED_PRISM,
248    /// Five-membered ring.
249    Pentagon = ffi::SEAMS_RING_PENTAGON,
250    /// Six-ring that is not a cage face.
251    Hexagon = ffi::SEAMS_RING_HEXAGON,
252    /// Neither a pentagon nor a hexagon face.
253    Other = ffi::SEAMS_RING_OTHER,
254}
255
256/// Per-atom cage membership. The four codes are disjoint.
257///
258/// ```
259/// assert_eq!(seams::CageLabel::Hex as i32, 1);
260/// ```
261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262#[repr(i32)]
263pub enum CageLabel {
264    /// In neither cage.
265    Water = ffi::SEAMS_CAGE_WATER,
266    /// Hexagonal cage only.
267    Hex = ffi::SEAMS_CAGE_HEX,
268    /// Double-diamond cage only.
269    Cubic = ffi::SEAMS_CAGE_CUBIC,
270    /// Both cages.
271    Both = ffi::SEAMS_CAGE_BOTH,
272}
273
274/// Site-table kind.
275///
276/// ```
277/// assert_eq!(seams::SiteKind::WaterO as i32, 8);
278/// ```
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280#[repr(i32)]
281pub enum SiteKind {
282    /// The table did not name this atom.
283    Unspecified = ffi::SEAMS_SITE_UNSPECIFIED,
284    /// Cation head.
285    Cation = ffi::SEAMS_SITE_CATION,
286    /// Anion.
287    Anion = ffi::SEAMS_SITE_ANION,
288    /// Tail atom.
289    Tail = ffi::SEAMS_SITE_TAIL,
290    /// Donor hydrogen.
291    DonorH = ffi::SEAMS_SITE_DONOR_H,
292    /// Acceptor.
293    Acceptor = ffi::SEAMS_SITE_ACCEPTOR,
294    /// Polar atom.
295    Polar = ffi::SEAMS_SITE_POLAR,
296    /// Apolar atom.
297    Apolar = ffi::SEAMS_SITE_APOLAR,
298    /// Water oxygen.
299    WaterO = ffi::SEAMS_SITE_WATER_O,
300    /// Water hydrogen.
301    WaterH = ffi::SEAMS_SITE_WATER_H,
302    /// Solvent atom.
303    Solvent = ffi::SEAMS_SITE_SOLVENT,
304}
305
306/// Cell axis.
307///
308/// ```
309/// assert_eq!(seams::Axis::Z as i32, 2);
310/// ```
311#[derive(Debug, Clone, Copy, PartialEq, Eq)]
312#[repr(i32)]
313pub enum Axis {
314    /// First cell edge.
315    X = 0,
316    /// Second cell edge.
317    Y = 1,
318    /// Third cell edge.
319    Z = 2,
320}
321
322/// Domain subset. The values match the C API.
323///
324/// ```
325/// assert_eq!(seams::DomainSubset::Polar as i32, 1);
326/// ```
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328#[repr(i32)]
329pub enum DomainSubset {
330    /// Apolar site subset.
331    Apolar = 0,
332    /// Polar site subset.
333    Polar = 1,
334}
335
336/// A failed call. The message is `seams_handle_error` when the call had a handle.
337///
338/// ```
339/// let mut system = seams::System::new()?;
340/// let err = system
341///     .chill_plus(&seams::ChillOptions::default())
342///     .expect_err("an empty frame has no coordinates");
343/// assert_eq!(err.status(), Some(seams::Status::State));
344/// assert!(!err.message().is_empty());
345/// # Ok::<(), seams::Error>(())
346/// ```
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub enum Error {
349    /// The library rejected the call with a known status.
350    Library {
351        /// Status code.
352        status: Status,
353        /// Detail text. May be empty.
354        message: String,
355    },
356    /// The library returned a status this crate does not name.
357    Other {
358        /// Raw status integer.
359        code: i32,
360        /// Detail text.
361        message: String,
362    },
363    /// The argument cannot be passed to the C API.
364    Argument {
365        /// What was wrong.
366        message: String,
367    },
368}
369
370impl Error {
371    fn argument(message: impl Into<String>) -> Self {
372        Self::Argument {
373            message: message.into(),
374        }
375    }
376
377    fn from_status(code: i32, message: String) -> Self {
378        match Status::from_code(code) {
379            Some(status) => Self::Library { status, message },
380            None => Self::Other { code, message },
381        }
382    }
383
384    /// Status when the failure came from the library and the code is known.
385    ///
386    /// ```
387    /// let err = seams::nframes("\0").expect_err("a nul cannot be a path");
388    /// assert_eq!(err.status(), None);
389    /// assert_eq!(err.code(), seams_sys::SEAMS_ERR_ARG);
390    /// ```
391    #[must_use]
392    pub fn status(&self) -> Option<Status> {
393        match self {
394            Self::Library { status, .. } => Some(*status),
395            Self::Other { .. } | Self::Argument { .. } => None,
396        }
397    }
398
399    /// Status integer. An argument error uses `SEAMS_ERR_ARG`.
400    ///
401    /// ```
402    /// let err = seams::nframes("\0").unwrap_err();
403    /// assert_eq!(err.code(), 4);
404    /// ```
405    #[must_use]
406    pub fn code(&self) -> i32 {
407        match self {
408            Self::Library { status, .. } => *status as i32,
409            Self::Other { code, .. } => *code,
410            Self::Argument { .. } => ffi::SEAMS_ERR_ARG,
411        }
412    }
413
414    /// Detail text.
415    ///
416    /// ```
417    /// let err = seams::nframes("\0").unwrap_err();
418    /// assert_eq!(err.message(), "text contains a nul");
419    /// ```
420    #[must_use]
421    pub fn message(&self) -> &str {
422        match self {
423            Self::Library { message, .. }
424            | Self::Other { message, .. }
425            | Self::Argument { message } => message,
426        }
427    }
428}
429
430impl std::fmt::Display for Error {
431    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
432        match self {
433            Self::Library { status, message } => {
434                if message.is_empty() {
435                    write!(f, "{}", status.as_str())
436                } else {
437                    write!(f, "{message} ({})", status.as_str())
438                }
439            }
440            Self::Other { code, message } => {
441                if message.is_empty() {
442                    write!(f, "status {code}")
443                } else {
444                    write!(f, "{message} (status {code})")
445                }
446            }
447            Self::Argument { message } => write!(f, "{message}"),
448        }
449    }
450}
451
452impl std::error::Error for Error {}
453
454fn message_of(handle: *const c_void) -> String {
455    unsafe {
456        let ptr = ffi::seams_handle_error(handle);
457        if ptr.is_null() {
458            return String::new();
459        }
460        CStr::from_ptr(ptr).to_string_lossy().into_owned()
461    }
462}
463
464fn check(code: c_int, handle: *const c_void) -> Result<(), Error> {
465    if code == ffi::SEAMS_OK {
466        return Ok(());
467    }
468    Err(Error::from_status(code, message_of(handle)))
469}
470
471fn c_text(text: &str) -> Result<CString, Error> {
472    CString::new(text).map_err(|_| Error::argument("text contains a nul"))
473}
474
475fn static_text(ptr: *const c_char) -> String {
476    if ptr.is_null() {
477        return String::new();
478    }
479    unsafe { CStr::from_ptr(ptr).to_string_lossy().into_owned() }
480}
481
482fn atom_count(n_coords: usize) -> Result<i32, Error> {
483    if n_coords % 3 != 0 {
484        return Err(Error::argument("coordinates are not a multiple of 3"));
485    }
486    i32::try_from(n_coords / 3).map_err(|_| Error::argument("too many points"))
487}
488
489/// Eight-atom cubic diamond used by the crate examples.
490///
491/// The lattice constant is `2.75 * 4 / sqrt(3)` angstroms. The returned
492/// edge is one cubic cell of that crystal.
493///
494/// ```
495/// let (xyz, edge) = seams::diamond8();
496/// assert_eq!(xyz.len(), 24);
497/// assert!(edge > 3.0);
498/// ```
499#[must_use]
500pub fn diamond8() -> (Vec<f64>, f64) {
501    let a = 2.75 * 4.0 / 3.0_f64.sqrt();
502    let fcc = [
503        [0.0, 0.0, 0.0],
504        [0.5, 0.5, 0.0],
505        [0.5, 0.0, 0.5],
506        [0.0, 0.5, 0.5],
507    ];
508    let basis = [[0.0, 0.0, 0.0], [0.25, 0.25, 0.25]];
509    let mut xyz = Vec::with_capacity(24);
510    for shift in fcc {
511        for site in basis {
512            xyz.push((shift[0] + site[0]) * a);
513            xyz.push((shift[1] + site[1]) * a);
514            xyz.push((shift[2] + site[2]) * a);
515        }
516    }
517    (xyz, a)
518}
519
520/// Library version text, for example `2.14.1`.
521///
522/// ```
523/// assert!(!seams::version().is_empty());
524/// ```
525#[must_use]
526pub fn version() -> String {
527    static_text(unsafe { ffi::seams_version_string() })
528}
529
530/// ABI number compiled into this library. The value is 1.
531///
532/// ```
533/// assert_eq!(seams::abi(), 1);
534/// ```
535#[must_use]
536pub fn abi() -> i32 {
537    unsafe { ffi::seams_abi() }
538}
539
540/// Whether the linked engine reads formats provided by chemfiles, including
541/// PDB and GRO.
542///
543/// ```
544/// let _available = seams::has_chemfiles();
545/// ```
546#[must_use]
547pub fn has_chemfiles() -> bool {
548    env!("DSEAMS_HAS_CHEMFILES") == "1"
549}
550
551/// Whether the linked engine reads `.con` files through readcon-core.
552///
553/// ```
554/// let _available = seams::has_readcon();
555/// ```
556#[must_use]
557pub fn has_readcon() -> bool {
558    env!("DSEAMS_HAS_READCON") == "1"
559}
560
561/// Set the OpenMP width for the next call. Zero restores the library default.
562///
563/// The width is process-global. Do not call this while another thread is
564/// inside the library.
565///
566/// ```
567/// seams::set_num_threads(1)?;
568/// assert_eq!(seams::num_threads(), 1);
569/// # Ok::<(), seams::Error>(())
570/// ```
571pub fn set_num_threads(n: i32) -> Result<(), Error> {
572    check(unsafe { ffi::seams_set_num_threads(n) }, std::ptr::null())
573}
574
575/// OpenMP width the next call will use.
576///
577/// ```
578/// seams::set_num_threads(1)?;
579/// assert_eq!(seams::num_threads(), 1);
580/// # Ok::<(), seams::Error>(())
581/// ```
582#[must_use]
583pub fn num_threads() -> i32 {
584    unsafe { ffi::seams_get_num_threads() }
585}
586
587/// Count frames in a trajectory path.
588///
589/// ```
590/// let err = seams::nframes("\0").expect_err("a nul cannot be a path");
591/// assert_eq!(err.code(), seams_sys::SEAMS_ERR_ARG);
592/// ```
593pub fn nframes(path: &str) -> Result<usize, Error> {
594    let text = c_text(path)?;
595    let mut count = 0usize;
596    check(
597        unsafe { ffi::seams_path_nframes(text.as_ptr(), &mut count) },
598        std::ptr::null(),
599    )?;
600    Ok(count)
601}
602
603/// Short name of a CHILL+ label.
604///
605/// ```
606/// assert_eq!(seams::label_name(seams::Label::Water), "water");
607/// ```
608#[must_use]
609pub fn label_name(label: Label) -> String {
610    static_text(unsafe { ffi::seams_label_name(label as c_int) })
611}
612
613/// Short name of a ring-symmetry code.
614///
615/// ```
616/// assert_eq!(seams::ring_symmetry_name(seams::RingSymmetry::Pentagon), "pentagon");
617/// ```
618#[must_use]
619pub fn ring_symmetry_name(symmetry: RingSymmetry) -> String {
620    static_text(unsafe { ffi::seams_ring_symmetry_name(symmetry as c_int) })
621}
622
623/// Knobs for CHILL and CHILL+.
624///
625/// ```
626/// let options = seams::ChillOptions::default();
627/// assert_eq!(options.cutoff, 3.5);
628/// assert_eq!(options.graph, seams::Graph::Cutoff);
629/// assert_eq!(options.rule, seams::ChillRule::Published);
630/// ```
631#[derive(Debug, Clone, Copy, PartialEq)]
632pub struct ChillOptions {
633    /// Positive cutoff, angstroms.
634    pub cutoff: f64,
635    /// Species filter. Zero keeps every atom.
636    pub species: i32,
637    /// Neighbour graph.
638    pub graph: Graph,
639    /// Threshold table.
640    pub rule: ChillRule,
641}
642
643impl Default for ChillOptions {
644    fn default() -> Self {
645        Self {
646            cutoff: 3.5,
647            species: 0,
648            graph: Graph::Cutoff,
649            rule: ChillRule::Published,
650        }
651    }
652}
653
654/// Knobs for a local Steinhardt parameter on the cutoff shell.
655///
656/// ```
657/// let options = seams::SteinhardtOptions { order: 4, average: true, ..Default::default() };
658/// assert_eq!(options.order, 4);
659/// assert!(options.average);
660/// ```
661#[derive(Debug, Clone, Copy, PartialEq)]
662pub struct SteinhardtOptions {
663    /// Positive cutoff, angstroms.
664    pub cutoff: f64,
665    /// Species filter. Zero keeps every atom.
666    pub species: i32,
667    /// Degree. 3, 4, 6, 8, or 12.
668    pub order: i32,
669    /// Also return the Lechner-Dellago averaged q_l (q_l-bar).
670    pub average: bool,
671}
672
673impl Default for SteinhardtOptions {
674    fn default() -> Self {
675        Self {
676            cutoff: 3.5,
677            species: 0,
678            order: 6,
679            average: false,
680        }
681    }
682}
683
684/// Knobs for q_l on a named graph.
685///
686/// ```
687/// let options = seams::OrderOptions::default();
688/// assert_eq!(options.graph, seams::Graph::Cutoff);
689/// ```
690#[derive(Debug, Clone, Copy, PartialEq)]
691pub struct OrderOptions {
692    /// Positive cutoff, angstroms.
693    pub cutoff: f64,
694    /// Species filter.
695    pub species: i32,
696    /// Degree. 3, 4, 6, 8, or 12.
697    pub order: i32,
698    /// Cutoff or mutual.
699    pub graph: Graph,
700    /// Also return the Lechner-Dellago averaged q_l (q_l-bar).
701    pub average: bool,
702}
703
704impl Default for OrderOptions {
705    fn default() -> Self {
706        Self {
707            cutoff: 3.5,
708            species: 0,
709            order: 6,
710            graph: Graph::Cutoff,
711            average: false,
712        }
713    }
714}
715
716/// Knobs for the q6-bar ice summary.
717///
718/// ```
719/// assert_eq!(seams::Q6BarOptions::default().ice_cut, 0.36);
720/// ```
721#[derive(Debug, Clone, Copy, PartialEq)]
722pub struct Q6BarOptions {
723    /// Positive cutoff, angstroms.
724    pub cutoff: f64,
725    /// Species filter.
726    pub species: i32,
727    /// Finite threshold. The nucleation census uses 0.36.
728    pub ice_cut: f64,
729}
730
731impl Default for Q6BarOptions {
732    fn default() -> Self {
733        Self {
734            cutoff: 3.5,
735            species: 0,
736            ice_cut: 0.36,
737        }
738    }
739}
740
741/// Knobs for a neighbour list.
742///
743/// ```
744/// assert_eq!(seams::NeighbourOptions::default().graph, seams::Graph::Cutoff);
745/// ```
746#[derive(Debug, Clone, Copy, PartialEq)]
747pub struct NeighbourOptions {
748    /// Positive cutoff, angstroms.
749    pub cutoff: f64,
750    /// Species filter.
751    pub species: i32,
752    /// Cutoff or mutual.
753    pub graph: Graph,
754}
755
756impl Default for NeighbourOptions {
757    fn default() -> Self {
758        Self {
759            cutoff: 3.5,
760            species: 0,
761            graph: Graph::Cutoff,
762        }
763    }
764}
765
766/// Knobs for a k-nearest neighbour list.
767///
768/// ```
769/// let options = seams::KnnOptions { k: 4, mutual: true, ..Default::default() };
770/// assert_eq!(options.k, 4);
771/// ```
772#[derive(Debug, Clone, Copy, PartialEq)]
773pub struct KnnOptions {
774    /// Positive neighbour count.
775    pub k: i32,
776    /// Nominal cutoff, angstroms. Candidates lie inside cutoff + 1.5.
777    pub cutoff: f64,
778    /// Species filter.
779    pub species: i32,
780    /// Keep only pairs that name each other.
781    pub mutual: bool,
782}
783
784impl Default for KnnOptions {
785    fn default() -> Self {
786        Self {
787            k: 4,
788            cutoff: 3.5,
789            species: 0,
790            mutual: false,
791        }
792    }
793}
794
795/// Knobs for primitive rings.
796///
797/// ```
798/// assert_eq!(seams::RingOptions::default().max_size, 6);
799/// ```
800#[derive(Debug, Clone, Copy, PartialEq)]
801pub struct RingOptions {
802    /// Positive cutoff, angstroms.
803    pub cutoff: f64,
804    /// Species filter.
805    pub species: i32,
806    /// Cutoff or mutual.
807    pub graph: Graph,
808    /// Largest ring size, from 3 through 12.
809    pub max_size: i32,
810}
811
812impl Default for RingOptions {
813    fn default() -> Self {
814        Self {
815            cutoff: 3.5,
816            species: 0,
817            graph: Graph::Cutoff,
818            max_size: 6,
819        }
820    }
821}
822
823/// Knobs for hexagonal and double-diamond cages.
824///
825/// ```
826/// assert_eq!(seams::CageOptions::default().graph, seams::Graph::Seeded);
827/// ```
828#[derive(Debug, Clone, Copy, PartialEq)]
829pub struct CageOptions {
830    /// Positive cutoff, angstroms.
831    pub cutoff: f64,
832    /// Species filter.
833    pub species: i32,
834    /// Cage graph. Seeded is the usual choice.
835    pub graph: Graph,
836    /// Neighbour count used to seed the graph.
837    pub k: i32,
838    /// Complete partial cages.
839    pub complete: bool,
840}
841
842impl Default for CageOptions {
843    fn default() -> Self {
844        Self {
845            cutoff: 3.5,
846            species: 0,
847            graph: Graph::Seeded,
848            k: 4,
849            complete: false,
850        }
851    }
852}
853
854/// Knobs for a signature cage census.
855///
856/// ```
857/// let options = seams::SignatureOptions { spec: "512".into(), ..Default::default() };
858/// assert_eq!(options.spec, "512");
859/// ```
860#[derive(Debug, Clone, PartialEq)]
861pub struct SignatureOptions {
862    /// Positive cutoff, angstroms.
863    pub cutoff: f64,
864    /// Species filter.
865    pub species: i32,
866    /// Neighbour graph.
867    pub graph: Graph,
868    /// Ring census text, for example `512`.
869    pub spec: String,
870}
871
872impl Default for SignatureOptions {
873    fn default() -> Self {
874        Self {
875            cutoff: 3.5,
876            species: 0,
877            graph: Graph::Cutoff,
878            spec: "512".to_string(),
879        }
880    }
881}
882
883/// Knobs for a partial RDF, its running coordination, or the integral.
884///
885/// ```
886/// let options = seams::DistributionOptions { rmax: 6.0, bins: 8, ..Default::default() };
887/// assert_eq!(options.bins, 8);
888/// ```
889#[derive(Debug, Clone, Copy, PartialEq)]
890pub struct DistributionOptions {
891    /// Outer limit, angstroms.
892    pub rmax: f64,
893    /// Bin count. Zero selects about `rmax / 0.1`.
894    pub bins: i32,
895    /// First species. Zero keeps every atom.
896    pub type_i: i32,
897    /// Second species. Zero keeps every atom.
898    pub type_j: i32,
899}
900
901impl Default for DistributionOptions {
902    fn default() -> Self {
903        Self {
904            rmax: 6.0,
905            bins: 0,
906            type_i: 0,
907            type_j: 0,
908        }
909    }
910}
911
912/// Knobs for a hydrogen-bond count.
913///
914/// ```
915/// let options = seams::BondOptions::default();
916/// assert_eq!(options.distance, 2.42);
917/// assert_eq!(options.angle, 30.0);
918/// ```
919#[derive(Debug, Clone, Copy, PartialEq)]
920pub struct BondOptions {
921    /// Heavy-atom cutoff, angstroms.
922    pub cutoff: f64,
923    /// Heavy-atom species. Zero keeps every non-hydrogen.
924    pub oxygen: i32,
925    /// Hydrogen species. Must be positive.
926    pub hydrogen: i32,
927    /// Acceptor-H distance, angstroms.
928    pub distance: f64,
929    /// O-O-H angle, degrees.
930    pub angle: f64,
931}
932
933impl Default for BondOptions {
934    fn default() -> Self {
935        Self {
936            cutoff: 3.5,
937            oxygen: 1,
938            hydrogen: 2,
939            distance: 2.42,
940            angle: 30.0,
941        }
942    }
943}
944
945/// Geometric settings for a directed donor–hydrogen–acceptor bond.
946#[derive(Debug, Clone, Copy, PartialEq)]
947pub struct DirectedBondOptions {
948    /// Donor–acceptor cutoff, angstroms.
949    pub cutoff: f64,
950    /// Hydrogen species code.
951    pub hydrogen: i32,
952    /// Acceptor–hydrogen cutoff, angstroms.
953    pub distance: f64,
954    /// Acceptor-centred angle cutoff, degrees.
955    pub angle: f64,
956    /// Exclude heavy atoms with the same molecule ID.
957    pub exclude_same_mol: bool,
958}
959
960impl Default for DirectedBondOptions {
961    fn default() -> Self {
962        let options = BondOptions::default();
963        Self {
964            cutoff: options.cutoff,
965            hydrogen: options.hydrogen,
966            distance: options.distance,
967            angle: options.angle,
968            exclude_same_mol: true,
969        }
970    }
971}
972
973/// One directed hydrogen bond in frame order.
974#[derive(Debug, Clone, Copy, PartialEq)]
975pub struct DirectedHbond {
976    /// Zero-based donor heavy-atom index.
977    pub donor: i32,
978    /// Zero-based hydrogen index.
979    pub hydrogen: i32,
980    /// Zero-based acceptor heavy-atom index.
981    pub acceptor: i32,
982    /// Minimum-image acceptor–hydrogen distance, angstroms.
983    pub acceptor_hydrogen_distance: f64,
984    /// Minimum-image donor–acceptor distance, angstroms.
985    pub donor_acceptor_distance: f64,
986    /// Acceptor-centred angle, degrees (zero for a linear bond).
987    pub angle: f64,
988}
989
990/// Correlation of starting hydrogen-bond pairs and their continuous survival.
991#[derive(Debug, Clone, PartialEq)]
992pub struct HbondLifetimeCurve {
993    /// Lag time in the units of the supplied frame spacing.
994    pub lag_time: Vec<f64>,
995    /// Fraction of starting pairs present at the lag, including reformed bonds.
996    pub intermittent: Vec<f64>,
997    /// Fraction of starting pairs present at every saved frame through the lag.
998    pub continuous: Vec<f64>,
999    /// Eligible starting frames at each lag, including empty frames.
1000    pub n_origins: Vec<usize>,
1001}
1002
1003/// Native integrated and single-exponential hydrogen-bond decay times.
1004#[derive(Debug, Clone, Copy, PartialEq)]
1005pub struct HbondLifetimeFit {
1006    /// Intermittent integral through the first non-positive point or final lag.
1007    pub intermittent_integral: f64,
1008    /// Intermittent exponential decay time, NaN if no decay fit is defined.
1009    pub intermittent_exponential: f64,
1010    /// Continuous integral through the first non-positive point or final lag.
1011    pub continuous_integral: f64,
1012    /// Continuous exponential decay time, NaN if no decay fit is defined.
1013    pub continuous_exponential: f64,
1014}
1015
1016/// Streaming native accumulator for consecutive saved frames.
1017///
1018/// Keep the heavy atom identities consistent across frames. Empty frames
1019/// still advance the lag clock. With `directed=false`, either orientation
1020/// represents the same bond pair. Multiple copies of a pair count once.
1021pub struct HbondLifetimeAccumulator {
1022    ptr: std::ptr::NonNull<ffi::seams_hbond_tcf>,
1023}
1024
1025// The handle owns its state and can move between threads, but not be shared.
1026unsafe impl Send for HbondLifetimeAccumulator {}
1027
1028impl Drop for HbondLifetimeAccumulator {
1029    fn drop(&mut self) {
1030        unsafe { ffi::seams_hbond_tcf_destroy(self.ptr.as_ptr()) };
1031    }
1032}
1033
1034impl HbondLifetimeAccumulator {
1035    /// Create a lifetime accumulator.
1036    ///
1037    /// `max_lag` is in frames (zero includes every lag). `origin_stride`
1038    /// is the positive spacing between starting frames. `dt` is the
1039    /// positive, uniform time between consecutive saved frames.
1040    ///
1041    /// ```
1042    /// let mut life = seams::HbondLifetimeAccumulator::new(2, 1, 0.5, true)?;
1043    /// life.push(&[(1, 2)])?;
1044    /// life.push(&[])?;
1045    /// life.push(&[(1, 2)])?;
1046    /// let curve = life.curve()?;
1047    /// assert_eq!(curve.intermittent, [1.0, 0.0, 1.0]);
1048    /// assert_eq!(curve.continuous, [1.0, 0.0, 0.0]);
1049    /// # Ok::<(), seams::Error>(())
1050    /// ```
1051    pub fn new(
1052        max_lag: usize,
1053        origin_stride: usize,
1054        dt: f64,
1055        directed: bool,
1056    ) -> Result<Self, Error> {
1057        let mut raw = std::ptr::null_mut();
1058        check(
1059            unsafe {
1060                ffi::seams_hbond_tcf_create(
1061                    max_lag,
1062                    origin_stride,
1063                    dt,
1064                    i32::from(directed),
1065                    &mut raw,
1066                )
1067            },
1068            std::ptr::null(),
1069        )?;
1070        let ptr = std::ptr::NonNull::new(raw)
1071            .ok_or_else(|| Error::argument("native lifetime handle is null"))?;
1072        Ok(Self { ptr })
1073    }
1074
1075    /// Add one frame's `(donor, acceptor)` pairs, including an empty slice.
1076    pub fn push(&mut self, pairs: &[(i32, i32)]) -> Result<(), Error> {
1077        let (donors, acceptors): (Vec<_>, Vec<_>) = pairs.iter().copied().unzip();
1078        let ptr = self.ptr.as_ptr();
1079        check(
1080            unsafe {
1081                ffi::seams_hbond_tcf_push(ptr, donors.as_ptr(), acceptors.as_ptr(), pairs.len())
1082            },
1083            ptr.cast(),
1084        )
1085    }
1086
1087    /// Copy the current curves; empty starting-bond populations yield NaN.
1088    pub fn curve(&self) -> Result<HbondLifetimeCurve, Error> {
1089        let ptr = self.ptr.as_ptr();
1090        let mut count = 0;
1091        check(
1092            unsafe {
1093                ffi::seams_hbond_tcf_curve(
1094                    ptr,
1095                    std::ptr::null_mut(),
1096                    std::ptr::null_mut(),
1097                    std::ptr::null_mut(),
1098                    std::ptr::null_mut(),
1099                    0,
1100                    &mut count,
1101                )
1102            },
1103            ptr.cast(),
1104        )?;
1105        let mut result = HbondLifetimeCurve {
1106            lag_time: vec![0.0; count],
1107            intermittent: vec![0.0; count],
1108            continuous: vec![0.0; count],
1109            n_origins: vec![0; count],
1110        };
1111        if count > 0 {
1112            check(
1113                unsafe {
1114                    ffi::seams_hbond_tcf_curve(
1115                        ptr,
1116                        result.lag_time.as_mut_ptr(),
1117                        result.intermittent.as_mut_ptr(),
1118                        result.continuous.as_mut_ptr(),
1119                        result.n_origins.as_mut_ptr(),
1120                        count,
1121                        &mut count,
1122                    )
1123                },
1124                ptr.cast(),
1125            )?;
1126        }
1127        Ok(result)
1128    }
1129
1130    /// Fit the exponential decay over the supplied time window.
1131    ///
1132    /// `(0.0, 0.0)` selects the full positive decay range. Integrals
1133    /// extend from zero lag to the first non-positive point or final lag.
1134    pub fn fit(&self, time_start: f64, time_end: f64) -> Result<HbondLifetimeFit, Error> {
1135        let ptr = self.ptr.as_ptr();
1136        let mut result = HbondLifetimeFit {
1137            intermittent_integral: 0.0,
1138            intermittent_exponential: 0.0,
1139            continuous_integral: 0.0,
1140            continuous_exponential: 0.0,
1141        };
1142        check(
1143            unsafe {
1144                ffi::seams_hbond_tcf_fit(
1145                    ptr,
1146                    time_start,
1147                    time_end,
1148                    &mut result.intermittent_integral,
1149                    &mut result.intermittent_exponential,
1150                    &mut result.continuous_integral,
1151                    &mut result.continuous_exponential,
1152                )
1153            },
1154            ptr.cast(),
1155        )?;
1156        Ok(result)
1157    }
1158}
1159
1160/// Knobs for the axial number density.
1161///
1162/// ```
1163/// assert_eq!(seams::DensityOptions::default().axis, seams::Axis::Z);
1164/// ```
1165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1166pub struct DensityOptions {
1167    /// Species filter. Zero keeps every atom.
1168    pub species: i32,
1169    /// Bin count. Zero selects about one bin per 0.1 angstrom.
1170    pub bins: i32,
1171    /// Cell axis.
1172    pub axis: Axis,
1173}
1174
1175impl Default for DensityOptions {
1176    fn default() -> Self {
1177        Self {
1178            species: 0,
1179            bins: 0,
1180            axis: Axis::Z,
1181        }
1182    }
1183}
1184
1185/// Knobs for a topological fingerprint.
1186///
1187/// ```
1188/// assert_eq!(seams::FingerprintOptions::default().hops, 2);
1189/// ```
1190#[derive(Debug, Clone, Copy, PartialEq)]
1191pub struct FingerprintOptions {
1192    /// Positive cutoff, angstroms.
1193    pub cutoff: f64,
1194    /// Species filter.
1195    pub species: i32,
1196    /// Neighbour count on the bonded graph.
1197    pub k: i32,
1198    /// Neighbour graph.
1199    pub graph: Graph,
1200    /// Neighbourhood depth. Zero selects 2.
1201    pub hops: i32,
1202    /// Color vertices by LAMMPS type.
1203    pub color_types: bool,
1204}
1205
1206impl Default for FingerprintOptions {
1207    fn default() -> Self {
1208        Self {
1209            cutoff: 3.5,
1210            species: 0,
1211            k: 4,
1212            graph: Graph::Cutoff,
1213            hops: 2,
1214            color_types: false,
1215        }
1216    }
1217}
1218
1219/// Knobs for a domain search.
1220///
1221/// ```
1222/// let options = seams::DomainOptions { spec: "1=waterO".into(), ..Default::default() };
1223/// assert_eq!(options.subset, seams::DomainSubset::Apolar);
1224/// ```
1225#[derive(Debug, Clone, PartialEq)]
1226pub struct DomainOptions {
1227    /// Positive cutoff, angstroms.
1228    pub cutoff: f64,
1229    /// Site-table text, for example `1=waterO`.
1230    pub spec: String,
1231    /// Which subset to measure.
1232    pub subset: DomainSubset,
1233}
1234
1235impl Default for DomainOptions {
1236    fn default() -> Self {
1237        Self {
1238            cutoff: 3.5,
1239            spec: String::new(),
1240            subset: DomainSubset::Apolar,
1241        }
1242    }
1243}
1244
1245/// Knobs for prism stacks.
1246///
1247/// ```
1248/// assert_eq!(seams::PrismOptions::default().cutoff, 3.5);
1249/// ```
1250#[derive(Debug, Clone, Copy, PartialEq)]
1251pub struct PrismOptions {
1252    /// Positive cutoff, angstroms.
1253    pub cutoff: f64,
1254    /// Species filter.
1255    pub species: i32,
1256}
1257
1258impl Default for PrismOptions {
1259    fn default() -> Self {
1260        Self {
1261            cutoff: 3.5,
1262            species: 0,
1263        }
1264    }
1265}
1266
1267/// Knobs for a monolayer ring histogram.
1268///
1269/// ```
1270/// let options = seams::SheetOptions { sheet_area: 100.0, ..Default::default() };
1271/// assert_eq!(options.max_size, 6);
1272/// ```
1273#[derive(Debug, Clone, Copy, PartialEq)]
1274pub struct SheetOptions {
1275    /// Positive cutoff, angstroms.
1276    pub cutoff: f64,
1277    /// Species filter.
1278    pub species: i32,
1279    /// Largest ring size.
1280    pub max_size: i32,
1281    /// Sheet area, square angstroms. Must be positive.
1282    pub sheet_area: f64,
1283}
1284
1285impl Default for SheetOptions {
1286    fn default() -> Self {
1287        Self {
1288            cutoff: 3.5,
1289            species: 0,
1290            max_size: 6,
1291            sheet_area: 0.0,
1292        }
1293    }
1294}
1295
1296/// Knobs for a planar ice front.
1297///
1298/// ```
1299/// assert_eq!(seams::BrineOptions::default().axis, seams::Axis::Z);
1300/// ```
1301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1302pub struct BrineOptions {
1303    /// Species kept as water, or 0.
1304    pub water_type: i32,
1305    /// Species kept as ions, or 0 for none.
1306    pub ion_type: i32,
1307    /// Bins along the axis. Zero selects 20.
1308    pub bins: i32,
1309    /// Front axis.
1310    pub axis: Axis,
1311}
1312
1313impl Default for BrineOptions {
1314    fn default() -> Self {
1315        Self {
1316            water_type: 0,
1317            ion_type: 0,
1318            bins: 0,
1319            axis: Axis::Z,
1320        }
1321    }
1322}
1323
1324/// CHILL or CHILL+ labels and the nine population counts.
1325///
1326/// `counts[k]` is the number of atoms whose label value is `k`.
1327///
1328/// ```
1329/// let (xyz, edge) = seams::diamond8();
1330/// let mut system = seams::System::new()?;
1331/// system.set_ortho(&xyz, edge, edge, edge)?;
1332/// let ice = system.chill_plus(&seams::ChillOptions::default())?;
1333/// assert_eq!(ice.counts[0], 8);
1334/// assert_eq!(ice.labels.len(), 8);
1335/// # Ok::<(), seams::Error>(())
1336/// ```
1337#[derive(Debug, Clone, PartialEq, Eq)]
1338pub struct Classification {
1339    /// One label code per atom.
1340    pub labels: Vec<i32>,
1341    /// Population in label order.
1342    pub counts: [i32; 9],
1343}
1344
1345/// Local Steinhardt parameter, and the average when it was requested.
1346///
1347/// ```
1348/// let (xyz, edge) = seams::diamond8();
1349/// let mut system = seams::System::new()?;
1350/// system.set_ortho(&xyz, edge, edge, edge)?;
1351/// let q6 = system.steinhardt(&seams::SteinhardtOptions { average: true, ..Default::default() })?;
1352/// assert_eq!(q6.local.len(), 8);
1353/// assert_eq!(q6.average.as_ref().map(Vec::len), Some(8));
1354/// # Ok::<(), seams::Error>(())
1355/// ```
1356#[derive(Debug, Clone, PartialEq)]
1357pub struct Steinhardt {
1358    /// One local q_l per atom. Dimensionless.
1359    pub local: Vec<f64>,
1360    /// Lechner-Dellago averaged q_l (formed from the neighbour-averaged q_lm). `None` when the average was not requested.
1361    pub average: Option<Vec<f64>>,
1362}
1363
1364/// Local q4 and q6 on the cutoff shell.
1365///
1366/// ```
1367/// let (xyz, edge) = seams::diamond8();
1368/// let mut system = seams::System::new()?;
1369/// system.set_ortho(&xyz, edge, edge, edge)?;
1370/// let orders = system.q4q6(3.5)?;
1371/// assert_eq!(orders.q4.len(), orders.q6.len());
1372/// # Ok::<(), seams::Error>(())
1373/// ```
1374#[derive(Debug, Clone, PartialEq)]
1375pub struct Q4Q6 {
1376    /// One local q4 per atom.
1377    pub q4: Vec<f64>,
1378    /// One local q6 per atom.
1379    pub q6: Vec<f64>,
1380}
1381
1382/// Lechner-Dellago q6-bar and the ice count above a cut.
1383///
1384/// ```
1385/// let (xyz, edge) = seams::diamond8();
1386/// let mut system = seams::System::new()?;
1387/// system.set_ortho(&xyz, edge, edge, edge)?;
1388/// let summary = system.q6bar(&seams::Q6BarOptions::default())?;
1389/// assert_eq!(summary.values.len(), 8);
1390/// assert!(summary.mean.is_finite());
1391/// # Ok::<(), seams::Error>(())
1392/// ```
1393#[derive(Debug, Clone, PartialEq)]
1394pub struct Q6Bar {
1395    /// One q6-bar per atom.
1396    pub values: Vec<f64>,
1397    /// Mean of the finite values.
1398    pub mean: f64,
1399    /// Median of the finite values.
1400    pub median: f64,
1401    /// Count strictly above the cut.
1402    pub n_ice: i32,
1403}
1404
1405/// Partial radial distribution.
1406///
1407/// ```
1408/// let (xyz, edge) = seams::diamond8();
1409/// let mut system = seams::System::new()?;
1410/// system.set_ortho(&xyz, edge, edge, edge)?;
1411/// let g = system.rdf(&seams::DistributionOptions { rmax: 6.0, bins: 4, ..Default::default() })?;
1412/// assert!(!g.radius.is_empty());
1413/// assert!(g.volume > 0.0);
1414/// # Ok::<(), seams::Error>(())
1415/// ```
1416#[derive(Debug, Clone, PartialEq)]
1417pub struct Distribution {
1418    /// Bin centers, angstroms.
1419    pub radius: Vec<f64>,
1420    /// g(r), dimensionless.
1421    pub g: Vec<f64>,
1422    /// Pair count in each bin.
1423    pub count: Vec<i32>,
1424    /// Cell volume, cubic angstroms.
1425    pub volume: f64,
1426}
1427
1428/// Running coordination number along a partial RDF.
1429///
1430/// ```
1431/// let (xyz, edge) = seams::diamond8();
1432/// let mut system = seams::System::new()?;
1433/// system.set_ortho(&xyz, edge, edge, edge)?;
1434/// let series = system.running_cn(&seams::DistributionOptions { rmax: 6.0, bins: 4, ..Default::default() })?;
1435/// assert_eq!(series.radius.len(), series.coordination.len());
1436/// # Ok::<(), seams::Error>(())
1437/// ```
1438#[derive(Debug, Clone, PartialEq)]
1439pub struct RunningCoordination {
1440    /// Bin centers, angstroms.
1441    pub radius: Vec<f64>,
1442    /// Running coordination, dimensionless.
1443    pub coordination: Vec<f64>,
1444}
1445
1446/// Disjoint cage populations.
1447///
1448/// ```
1449/// let counts = seams::CageCounts { hexagonal: 1, cubic: 0, water: 2, both: 0 };
1450/// assert_eq!(counts.hexagonal, 1);
1451/// ```
1452#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1453pub struct CageCounts {
1454    /// Hexagonal cage only.
1455    pub hexagonal: i32,
1456    /// Double-diamond cage only.
1457    pub cubic: i32,
1458    /// Neither cage.
1459    pub water: i32,
1460    /// Both cages.
1461    pub both: i32,
1462}
1463
1464/// Closed cages whose ring census matches a signature.
1465///
1466/// ```
1467/// let found = seams::SignatureMatch { cages: 2, atoms: 40 };
1468/// assert_eq!(found.cages, 2);
1469/// ```
1470#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1471pub struct SignatureMatch {
1472    /// Number of closed cages.
1473    pub cages: usize,
1474    /// Distinct atoms in those cages.
1475    pub atoms: usize,
1476}
1477
1478/// Mutual nearest unlike contacts of a site table.
1479///
1480/// ```
1481/// let contacts = seams::Contacts { pairs: 0, cations: 1, anions: 1 };
1482/// assert_eq!(contacts.pairs, 0);
1483/// ```
1484#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1485pub struct Contacts {
1486    /// Contact count.
1487    pub pairs: usize,
1488    /// Cation molecules in the ion cloud.
1489    pub cations: i32,
1490    /// Anion molecules in the ion cloud.
1491    pub anions: i32,
1492}
1493
1494/// Largest polar or apolar domain.
1495///
1496/// ```
1497/// let domain = seams::DomainReport { subset: 8, largest: 8, percolation: 1.0 };
1498/// assert_eq!(domain.largest, 8);
1499/// ```
1500#[derive(Debug, Clone, Copy, PartialEq)]
1501pub struct DomainReport {
1502    /// Atoms in the requested subset.
1503    pub subset: i32,
1504    /// Largest connected component.
1505    pub largest: i32,
1506    /// Percolation measure, dimensionless.
1507    pub percolation: f64,
1508}
1509
1510/// Perfect and imperfect prism counts by ring size.
1511///
1512/// Index is the ring size. Sizes 3 through 6 are filled.
1513///
1514/// ```
1515/// let prisms = seams::PrismCensus::default();
1516/// assert_eq!(prisms.perfect.len(), 7);
1517/// ```
1518#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1519pub struct PrismCensus {
1520    /// Perfect stacks.
1521    pub perfect: [i32; 7],
1522    /// Imperfect stacks.
1523    pub imperfect: [i32; 7],
1524}
1525
1526/// Number density along one cell axis.
1527///
1528/// ```
1529/// let (xyz, edge) = seams::diamond8();
1530/// let mut system = seams::System::new()?;
1531/// system.set_ortho(&xyz, edge, edge, edge)?;
1532/// let rho = system.density(&seams::DensityOptions { bins: 2, ..Default::default() })?;
1533/// assert_eq!(rho.coordinate.len(), rho.density.len());
1534/// # Ok::<(), seams::Error>(())
1535/// ```
1536#[derive(Debug, Clone, PartialEq)]
1537pub struct DensityProfile {
1538    /// Bin centers, angstroms.
1539    pub coordinate: Vec<f64>,
1540    /// Number density.
1541    pub density: Vec<f64>,
1542}
1543
1544/// The two planar crossings of an ice slab.
1545///
1546/// ```
1547/// let fronts = seams::BrineFronts { enter: 1.0, exit: 2.0, thickness: 1.0, found: true };
1548/// assert!(fronts.found);
1549/// ```
1550#[derive(Debug, Clone, Copy, PartialEq)]
1551pub struct BrineFronts {
1552    /// Crossing on entering the ice, angstroms.
1553    pub enter: f64,
1554    /// Crossing on leaving the ice, angstroms.
1555    pub exit: f64,
1556    /// Ice run along the axis, angstroms.
1557    pub thickness: f64,
1558    /// Both crossings exist.
1559    pub found: bool,
1560}
1561
1562/// Molal rejection coefficient.
1563///
1564/// ```
1565/// let rejection = seams::Rejection { ice: 0.0, liquid: 0.0, k: 0.0, defined: false };
1566/// assert!(!rejection.defined);
1567/// ```
1568#[derive(Debug, Clone, Copy, PartialEq)]
1569pub struct Rejection {
1570    /// Bulk ice molality, mol/kg.
1571    pub ice: f64,
1572    /// Bulk liquid molality, mol/kg.
1573    pub liquid: f64,
1574    /// Ratio of the two molalities.
1575    pub k: f64,
1576    /// The ratio is defined.
1577    pub defined: bool,
1578}
1579
1580/// Concentration profile along the brine axis.
1581///
1582/// ```
1583/// let profile = seams::BrineProfile { coordinate: vec![0.0], molality: vec![0.0], ice_fraction: vec![1.0] };
1584/// assert_eq!(profile.coordinate.len(), 1);
1585/// ```
1586#[derive(Debug, Clone, PartialEq)]
1587pub struct BrineProfile {
1588    /// Bin centers, angstroms.
1589    pub coordinate: Vec<f64>,
1590    /// mol/kg.
1591    pub molality: Vec<f64>,
1592    /// Dimensionless ice fraction.
1593    pub ice_fraction: Vec<f64>,
1594}
1595
1596/// Brine pockets trapped in the ice.
1597///
1598/// ```
1599/// let pockets = seams::Pockets { pockets: 0, reservoir_waters: 8 };
1600/// assert_eq!(pockets.reservoir_waters, 8);
1601/// ```
1602#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1603pub struct Pockets {
1604    /// Pocket count, excluding the reservoir.
1605    pub pockets: i32,
1606    /// Waters in the liquid reservoir.
1607    pub reservoir_waters: i32,
1608}
1609
1610/// An owned periodic Voronoi tessellation.
1611///
1612/// Dropping the source frame does not invalidate the result. Geometry
1613/// borrowed through [`Self::view`] remains valid until the result is dropped.
1614pub struct VoronoiCells {
1615    ptr: std::ptr::NonNull<ffi::seams_voronoi>,
1616}
1617
1618// The native result owns its immutable vectors and has no thread-local data.
1619unsafe impl Send for VoronoiCells {}
1620
1621impl Drop for VoronoiCells {
1622    fn drop(&mut self) {
1623        unsafe { ffi::seams_voronoi_destroy(self.ptr.as_ptr()) };
1624    }
1625}
1626
1627impl VoronoiCells {
1628    /// Borrow the cell, face, and vertex arrays without copying.
1629    pub fn view(&self) -> Result<VoronoiView<'_>, Error> {
1630        let mut view = std::mem::MaybeUninit::uninit();
1631        let ptr = self.ptr.as_ptr();
1632        check(
1633            unsafe { ffi::seams_voronoi_get_view(ptr, view.as_mut_ptr()) },
1634            ptr.cast(),
1635        )?;
1636        // The checked call initializes the C view. All arrays are immutable
1637        // and owned by self. C stores each shift and vertex as three consecutive values.
1638        let view = unsafe { view.assume_init() };
1639        Ok(unsafe {
1640            VoronoiView {
1641                volumes: self.borrow_array(view.volumes, view.n_sites),
1642                surface_areas: self.borrow_array(view.surface_areas, view.n_sites),
1643                site_offsets: self.borrow_array(view.site_offsets, view.n_sites + 1),
1644                face_areas: self.borrow_array(view.face_areas, view.n_faces),
1645                neighbours: self.borrow_array(view.neighbours, view.n_faces),
1646                shifts: self.borrow_array(view.shifts.cast(), view.n_faces),
1647                face_offsets: self.borrow_array(view.face_offsets, view.n_faces + 1),
1648                vertex_offsets: self.borrow_array(view.vertex_offsets.cast(), view.n_vertices),
1649            }
1650        })
1651    }
1652
1653    // ptr must address a native result array with the given length and representation.
1654    unsafe fn borrow_array<T>(&self, ptr: *const T, len: usize) -> &[T] {
1655        if len == 0 {
1656            &[]
1657        } else {
1658            unsafe { std::slice::from_raw_parts(ptr, len) }
1659        }
1660    }
1661}
1662
1663/// Borrowed geometry of every cell, in frame order.
1664pub struct VoronoiView<'a> {
1665    /// Cell volumes in cubic angstroms.
1666    pub volumes: &'a [f64],
1667    /// Cell surface areas in square angstroms.
1668    pub surface_areas: &'a [f64],
1669    site_offsets: &'a [usize],
1670    face_areas: &'a [f64],
1671    neighbours: &'a [i32],
1672    shifts: &'a [[i32; 3]],
1673    face_offsets: &'a [usize],
1674    vertex_offsets: &'a [[f64; 3]],
1675}
1676
1677impl<'a> VoronoiView<'a> {
1678    /// Face indices for one zero-based site. Returns `None` outside the frame.
1679    pub fn cell_faces(&self, site: usize) -> Option<std::ops::Range<usize>> {
1680        if site >= self.volumes.len() {
1681            return None;
1682        }
1683        Some(self.site_offsets[site]..self.site_offsets[site + 1])
1684    }
1685
1686    /// The geometry of a face returned by [`Self::cell_faces`].
1687    pub fn face(&self, face: usize) -> Option<VoronoiFace<'a>> {
1688        let area = *self.face_areas.get(face)?;
1689        let vertices = self.face_offsets[face]..self.face_offsets[face + 1];
1690        Some(VoronoiFace {
1691            neighbour: self.neighbours[face],
1692            shift: self.shifts[face],
1693            area,
1694            vertices: &self.vertex_offsets[vertices],
1695        })
1696    }
1697}
1698
1699/// An image-resolved face of a periodic Voronoi cell.
1700pub struct VoronoiFace<'a> {
1701    /// Zero-based index of the neighbouring site in the input frame.
1702    pub neighbour: i32,
1703    /// Integer lattice translation applied to the neighbouring site.
1704    pub shift: [i32; 3],
1705    /// Face area in square angstroms.
1706    pub area: f64,
1707    /// Outward-wound Cartesian vertex offsets from the centre site, in angstroms.
1708    pub vertices: &'a [[f64; 3]],
1709}
1710
1711/// One directed neighbour pair. The self entry is omitted.
1712///
1713/// ```
1714/// let pair = seams::NeighbourPair { atom: 0, neighbour: 1 };
1715/// assert_eq!(pair.neighbour, 1);
1716/// ```
1717#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1718pub struct NeighbourPair {
1719    /// Atom index in the frame.
1720    pub atom: i32,
1721    /// Neighbour index in the frame.
1722    pub neighbour: i32,
1723}
1724
1725/// Iterator of directed neighbour pairs.
1726///
1727/// Yields [`NeighbourPair`]. Created by [`Neighbours::pairs`].
1728pub struct NeighbourPairs<'a> {
1729    offsets: &'a [i32],
1730    cols: &'a [i32],
1731    atom: usize,
1732    cursor: usize,
1733}
1734
1735impl Iterator for NeighbourPairs<'_> {
1736    type Item = NeighbourPair;
1737
1738    fn next(&mut self) -> Option<Self::Item> {
1739        while self.atom + 1 < self.offsets.len() {
1740            let end = self.offsets[self.atom + 1];
1741            let end = usize::try_from(end).unwrap_or(0);
1742            if self.cursor < end {
1743                let index = self.cursor;
1744                self.cursor += 1;
1745                let neighbour = self.cols.get(index).copied().unwrap_or(-1);
1746                if neighbour != i32::try_from(self.atom).unwrap_or(i32::MAX) {
1747                    return Some(NeighbourPair {
1748                        atom: i32::try_from(self.atom).unwrap_or(0),
1749                        neighbour,
1750                    });
1751                }
1752                continue;
1753            }
1754            self.atom += 1;
1755            if self.atom < self.offsets.len() {
1756                self.cursor = usize::try_from(self.offsets[self.atom]).unwrap_or(0);
1757            }
1758        }
1759        None
1760    }
1761}
1762
1763/// Owned neighbour list.
1764///
1765/// The handle is freed on drop. It is [`Send`] and not [`Sync`].
1766///
1767/// ```
1768/// let (xyz, edge) = seams::diamond8();
1769/// let mut system = seams::System::new()?;
1770/// system.set_ortho(&xyz, edge, edge, edge)?;
1771/// let list = system.neighbours(&seams::NeighbourOptions::default())?;
1772/// assert!(list.pairs().all(|pair| pair.atom != pair.neighbour));
1773/// assert!(list.degrees()?.iter().all(|degree| *degree == 4));
1774/// # Ok::<(), seams::Error>(())
1775/// ```
1776pub struct Neighbours {
1777    ptr: *mut ffi::seams_neighbours,
1778    offsets: Vec<i32>,
1779    cols: Vec<i32>,
1780}
1781
1782// Safety: the C++ object is a heap allocation of vectors and a string.
1783// It has no thread-local members. Moving the owner to another thread is
1784// sound. Sharing it is not: the C API requires exclusive use.
1785unsafe impl Send for Neighbours {}
1786
1787impl Drop for Neighbours {
1788    fn drop(&mut self) {
1789        if !self.ptr.is_null() {
1790            unsafe { ffi::seams_neighbours_destroy(self.ptr) };
1791        }
1792    }
1793}
1794
1795impl Neighbours {
1796    fn adopt(ptr: *mut ffi::seams_neighbours) -> Result<Self, Error> {
1797        let handle = ptr as *const c_void;
1798        let mut n_offsets = 0usize;
1799        let mut nnz = 0usize;
1800        check(
1801            unsafe {
1802                ffi::seams_neighbours_copy(
1803                    ptr,
1804                    std::ptr::null_mut(),
1805                    0,
1806                    &mut n_offsets,
1807                    std::ptr::null_mut(),
1808                    0,
1809                    &mut nnz,
1810                )
1811            },
1812            handle,
1813        )?;
1814        let mut offsets = vec![0; n_offsets];
1815        let mut cols = vec![0; nnz];
1816        check(
1817            unsafe {
1818                ffi::seams_neighbours_copy(
1819                    ptr,
1820                    offsets.as_mut_ptr(),
1821                    offsets.len(),
1822                    &mut n_offsets,
1823                    cols.as_mut_ptr(),
1824                    cols.len(),
1825                    &mut nnz,
1826                )
1827            },
1828            handle,
1829        )?;
1830        offsets.truncate(n_offsets);
1831        cols.truncate(nnz);
1832        Ok(Self { ptr, offsets, cols })
1833    }
1834
1835    /// Number of neighbour pairs, omitting self.
1836    ///
1837    /// ```
1838    /// let (xyz, edge) = seams::diamond8();
1839    /// let mut system = seams::System::new()?;
1840    /// system.set_ortho(&xyz, edge, edge, edge)?;
1841    /// let list = system.knn(&seams::KnnOptions { k: 4, mutual: true, ..Default::default() })?;
1842    /// assert!(list.nnz()? > 0);
1843    /// # Ok::<(), seams::Error>(())
1844    /// ```
1845    pub fn nnz(&self) -> Result<usize, Error> {
1846        Ok(self.pairs().count())
1847    }
1848
1849    /// Degree of each atom. The self entry is not counted.
1850    ///
1851    /// ```
1852    /// let (xyz, edge) = seams::diamond8();
1853    /// let mut system = seams::System::new()?;
1854    /// system.set_ortho(&xyz, edge, edge, edge)?;
1855    /// let list = system.neighbours(&seams::NeighbourOptions::default())?;
1856    /// assert_eq!(list.degrees()?.len(), 8);
1857    /// # Ok::<(), seams::Error>(())
1858    /// ```
1859    pub fn degrees(&self) -> Result<Vec<i32>, Error> {
1860        let mut degree = Vec::new();
1861        if self.offsets.len() >= 2 {
1862            for window in self.offsets.windows(2) {
1863                degree.push(window[1] - window[0]);
1864            }
1865        }
1866        Ok(degree)
1867    }
1868
1869    /// Directed pairs. Self is omitted.
1870    ///
1871    /// ```
1872    /// let (xyz, edge) = seams::diamond8();
1873    /// let mut system = seams::System::new()?;
1874    /// system.set_ortho(&xyz, edge, edge, edge)?;
1875    /// let list = system.neighbours(&seams::NeighbourOptions::default())?;
1876    /// assert_eq!(list.pairs().count(), list.nnz()?);
1877    /// # Ok::<(), seams::Error>(())
1878    /// ```
1879    #[must_use]
1880    pub fn pairs(&self) -> NeighbourPairs<'_> {
1881        let cursor = self
1882            .offsets
1883            .first()
1884            .copied()
1885            .and_then(|v| usize::try_from(v).ok())
1886            .unwrap_or(0);
1887        NeighbourPairs {
1888            offsets: &self.offsets,
1889            cols: &self.cols,
1890            atom: 0,
1891            cursor,
1892        }
1893    }
1894}
1895
1896/// Owned primitive-ring set.
1897///
1898/// ```
1899/// let (xyz, edge) = seams::diamond8();
1900/// let mut system = seams::System::new()?;
1901/// system.set_ortho(&xyz, edge, edge, edge)?;
1902/// let rings = system.rings(&seams::RingOptions::default())?;
1903/// assert!(rings.size() > 0);
1904/// assert!(!rings.vertices(0)?.is_empty());
1905/// # Ok::<(), seams::Error>(())
1906/// ```
1907pub struct Rings {
1908    ptr: *mut ffi::seams_rings,
1909}
1910
1911unsafe impl Send for Rings {}
1912
1913impl Drop for Rings {
1914    fn drop(&mut self) {
1915        if !self.ptr.is_null() {
1916            unsafe { ffi::seams_rings_destroy(self.ptr) };
1917        }
1918    }
1919}
1920
1921impl Rings {
1922    /// Find primitive rings in an explicit bond graph.
1923    ///
1924    /// `offsets` contains one compressed sparse row offset per site plus a
1925    /// final offset equal to `columns.len()`. The first offset is zero.
1926    /// `columns` contains zero-based neighbour indices. Either direction
1927    /// records a bond, and self-edges and duplicates are ignored.
1928    /// `max_size` ranges from three to twelve.
1929    ///
1930    /// ```
1931    /// let rings = seams::Rings::from_csr(&[0, 2, 3, 4, 4], &[1, 3, 2, 3], 4)?;
1932    /// assert_eq!(rings.size(), 1);
1933    /// assert_eq!(rings.vertices(0)?, [0, 1, 2, 3]);
1934    /// # Ok::<(), seams::Error>(())
1935    /// ```
1936    pub fn from_csr(offsets: &[i32], columns: &[i32], max_size: i32) -> Result<Self, Error> {
1937        let mut out = std::ptr::null_mut();
1938        check(
1939            unsafe {
1940                ffi::seams_rings_from_csr(
1941                    offsets.as_ptr(),
1942                    offsets.len(),
1943                    columns.as_ptr(),
1944                    columns.len(),
1945                    max_size,
1946                    std::ptr::null(),
1947                    &mut out,
1948                )
1949            },
1950            std::ptr::null(),
1951        )?;
1952        Ok(Self { ptr: out })
1953    }
1954
1955    /// Number of primitive rings.
1956    ///
1957    /// ```
1958    /// let (xyz, edge) = seams::diamond8();
1959    /// let mut system = seams::System::new()?;
1960    /// system.set_ortho(&xyz, edge, edge, edge)?;
1961    /// let rings = system.rings(&seams::RingOptions::default())?;
1962    /// assert_eq!(rings.iter().count(), rings.size() as usize);
1963    /// # Ok::<(), seams::Error>(())
1964    /// ```
1965    #[must_use]
1966    pub fn size(&self) -> i32 {
1967        unsafe { ffi::seams_rings_count(self.ptr) }
1968    }
1969
1970    /// Atom indices of one ring.
1971    ///
1972    /// ```
1973    /// let (xyz, edge) = seams::diamond8();
1974    /// let mut system = seams::System::new()?;
1975    /// system.set_ortho(&xyz, edge, edge, edge)?;
1976    /// let rings = system.rings(&seams::RingOptions::default())?;
1977    /// assert!(!rings.vertices(0)?.is_empty());
1978    /// # Ok::<(), seams::Error>(())
1979    /// ```
1980    pub fn vertices(&self, index: i32) -> Result<Vec<i32>, Error> {
1981        let handle = self.ptr as *const c_void;
1982        let mut n_out = 0usize;
1983        check(
1984            unsafe {
1985                ffi::seams_rings_vertices(self.ptr, index, std::ptr::null_mut(), 0, &mut n_out)
1986            },
1987            handle,
1988        )?;
1989        let mut atoms = vec![0; n_out];
1990        check(
1991            unsafe {
1992                ffi::seams_rings_vertices(self.ptr, index, atoms.as_mut_ptr(), n_out, &mut n_out)
1993            },
1994            handle,
1995        )?;
1996        atoms.truncate(n_out);
1997        Ok(atoms)
1998    }
1999
2000    /// Histogram of ring size. `counts[k]` is the number of rings of size k.
2001    ///
2002    /// ```
2003    /// let (xyz, edge) = seams::diamond8();
2004    /// let mut system = seams::System::new()?;
2005    /// system.set_ortho(&xyz, edge, edge, edge)?;
2006    /// let rings = system.rings(&seams::RingOptions::default())?;
2007    /// let hist = rings.histogram(6)?;
2008    /// assert_eq!(hist.len(), 7);
2009    /// # Ok::<(), seams::Error>(())
2010    /// ```
2011    pub fn histogram(&self, up_to: i32) -> Result<Vec<i32>, Error> {
2012        let len = usize::try_from(up_to).map_err(|_| Error::argument("ring size is negative"))? + 1;
2013        let mut counts = vec![0; len];
2014        check(
2015            unsafe { ffi::seams_rings_histogram(self.ptr, counts.as_mut_ptr(), up_to + 1) },
2016            self.ptr as *const c_void,
2017        )?;
2018        Ok(counts)
2019    }
2020
2021    /// Fraction of atoms that sit on a ring of one size. Zero counts every ring.
2022    ///
2023    /// ```
2024    /// let (xyz, edge) = seams::diamond8();
2025    /// let mut system = seams::System::new()?;
2026    /// system.set_ortho(&xyz, edge, edge, edge)?;
2027    /// let rings = system.rings(&seams::RingOptions::default())?;
2028    /// assert!(rings.fraction(6)?.is_finite());
2029    /// # Ok::<(), seams::Error>(())
2030    /// ```
2031    pub fn fraction(&self, ring_size: i32) -> Result<f64, Error> {
2032        let mut value = 0.0;
2033        check(
2034            unsafe { ffi::seams_rings_fraction(self.ptr, ring_size, &mut value) },
2035            self.ptr as *const c_void,
2036        )?;
2037        Ok(value)
2038    }
2039
2040    /// Walk the rings. Each item is the vertex list of one ring.
2041    ///
2042    /// ```
2043    /// let (xyz, edge) = seams::diamond8();
2044    /// let mut system = seams::System::new()?;
2045    /// system.set_ortho(&xyz, edge, edge, edge)?;
2046    /// let rings = system.rings(&seams::RingOptions::default())?;
2047    /// assert!(rings.iter().all(|ring| ring.is_ok()));
2048    /// # Ok::<(), seams::Error>(())
2049    /// ```
2050    #[must_use]
2051    pub fn iter(&self) -> RingIter<'_> {
2052        RingIter {
2053            rings: self,
2054            index: 0,
2055        }
2056    }
2057}
2058
2059/// Iterator of primitive rings. Each item is a [`Result`] of vertex indices.
2060pub struct RingIter<'a> {
2061    rings: &'a Rings,
2062    index: i32,
2063}
2064
2065impl Iterator for RingIter<'_> {
2066    type Item = Result<Vec<i32>, Error>;
2067
2068    fn next(&mut self) -> Option<Self::Item> {
2069        if self.index >= self.rings.size() {
2070            return None;
2071        }
2072        let index = self.index;
2073        self.index += 1;
2074        Some(self.rings.vertices(index))
2075    }
2076}
2077
2078/// Owned hexagonal and double-diamond membership.
2079///
2080/// ```
2081/// let (xyz, edge) = seams::diamond8();
2082/// let mut system = seams::System::new()?;
2083/// system.set_ortho(&xyz, edge, edge, edge)?;
2084/// let cages = system.cages(&seams::CageOptions::default())?;
2085/// let counts = cages.counts()?;
2086/// assert_eq!(counts.hexagonal + counts.cubic + counts.water + counts.both, 8);
2087/// # Ok::<(), seams::Error>(())
2088/// ```
2089pub struct Cages {
2090    ptr: *mut ffi::seams_cage_set,
2091}
2092
2093unsafe impl Send for Cages {}
2094
2095impl Drop for Cages {
2096    fn drop(&mut self) {
2097        if !self.ptr.is_null() {
2098            unsafe { ffi::seams_cages_destroy(self.ptr) };
2099        }
2100    }
2101}
2102
2103impl Cages {
2104    /// Disjoint population counts.
2105    ///
2106    /// ```
2107    /// let (xyz, edge) = seams::diamond8();
2108    /// let mut system = seams::System::new()?;
2109    /// system.set_ortho(&xyz, edge, edge, edge)?;
2110    /// let cages = system.cages(&seams::CageOptions::default())?;
2111    /// assert!(cages.counts()?.water >= 0);
2112    /// # Ok::<(), seams::Error>(())
2113    /// ```
2114    pub fn counts(&self) -> Result<CageCounts, Error> {
2115        let mut out = CageCounts::default();
2116        check(
2117            unsafe {
2118                ffi::seams_cages_counts(
2119                    self.ptr,
2120                    &mut out.hexagonal,
2121                    &mut out.cubic,
2122                    &mut out.water,
2123                    &mut out.both,
2124                )
2125            },
2126            self.ptr as *const c_void,
2127        )?;
2128        Ok(out)
2129    }
2130
2131    /// One cage code per atom.
2132    ///
2133    /// ```
2134    /// let (xyz, edge) = seams::diamond8();
2135    /// let mut system = seams::System::new()?;
2136    /// system.set_ortho(&xyz, edge, edge, edge)?;
2137    /// let cages = system.cages(&seams::CageOptions::default())?;
2138    /// assert_eq!(cages.labels(8)?.len(), 8);
2139    /// # Ok::<(), seams::Error>(())
2140    /// ```
2141    pub fn labels(&self, n_atoms: usize) -> Result<Vec<i32>, Error> {
2142        let mut per_atom = vec![0; n_atoms];
2143        check(
2144            unsafe { ffi::seams_cages_labels(self.ptr, per_atom.as_mut_ptr(), n_atoms) },
2145            self.ptr as *const c_void,
2146        )?;
2147        Ok(per_atom)
2148    }
2149}
2150
2151/// Owned topological fingerprint.
2152///
2153/// ```
2154/// let (xyz, edge) = seams::diamond8();
2155/// let mut system = seams::System::new()?;
2156/// system.set_ortho(&xyz, edge, edge, edge)?;
2157/// let fp = system.fingerprint(&seams::FingerprintOptions::default())?;
2158/// assert!(!fp.key()?.is_empty());
2159/// assert_eq!(fp.rings()?.len(), 13);
2160/// # Ok::<(), seams::Error>(())
2161/// ```
2162pub struct Fingerprint {
2163    ptr: *mut ffi::seams_topo,
2164}
2165
2166unsafe impl Send for Fingerprint {}
2167
2168impl Drop for Fingerprint {
2169    fn drop(&mut self) {
2170        if !self.ptr.is_null() {
2171            unsafe { ffi::seams_fingerprint_destroy(self.ptr) };
2172        }
2173    }
2174}
2175
2176impl Fingerprint {
2177    /// Frame fingerprint text.
2178    ///
2179    /// ```
2180    /// let (xyz, edge) = seams::diamond8();
2181    /// let mut system = seams::System::new()?;
2182    /// system.set_ortho(&xyz, edge, edge, edge)?;
2183    /// let fp = system.fingerprint(&seams::FingerprintOptions::default())?;
2184    /// assert!(fp.key()?.contains('-') || !fp.key()?.is_empty());
2185    /// # Ok::<(), seams::Error>(())
2186    /// ```
2187    pub fn key(&self) -> Result<String, Error> {
2188        let handle = self.ptr as *const c_void;
2189        let mut n_out = 0usize;
2190        check(
2191            unsafe { ffi::seams_fingerprint_key(self.ptr, std::ptr::null_mut(), 0, &mut n_out) },
2192            handle,
2193        )?;
2194        let mut buf = vec![0u8; n_out + 1];
2195        check(
2196            unsafe {
2197                ffi::seams_fingerprint_key(self.ptr, buf.as_mut_ptr().cast(), buf.len(), &mut n_out)
2198            },
2199            handle,
2200        )?;
2201        buf.truncate(n_out);
2202        Ok(String::from_utf8_lossy(&buf).into_owned())
2203    }
2204
2205    /// Local key of one atom.
2206    ///
2207    /// ```
2208    /// let (xyz, edge) = seams::diamond8();
2209    /// let mut system = seams::System::new()?;
2210    /// system.set_ortho(&xyz, edge, edge, edge)?;
2211    /// let fp = system.fingerprint(&seams::FingerprintOptions::default())?;
2212    /// assert!(!fp.atom(0)?.is_empty());
2213    /// # Ok::<(), seams::Error>(())
2214    /// ```
2215    pub fn atom(&self, index: i32) -> Result<String, Error> {
2216        let handle = self.ptr as *const c_void;
2217        let mut n_out = 0usize;
2218        check(
2219            unsafe {
2220                ffi::seams_fingerprint_atom(self.ptr, index, std::ptr::null_mut(), 0, &mut n_out)
2221            },
2222            handle,
2223        )?;
2224        let mut buf = vec![0u8; n_out + 1];
2225        check(
2226            unsafe {
2227                ffi::seams_fingerprint_atom(
2228                    self.ptr,
2229                    index,
2230                    buf.as_mut_ptr().cast(),
2231                    buf.len(),
2232                    &mut n_out,
2233                )
2234            },
2235            handle,
2236        )?;
2237        buf.truncate(n_out);
2238        Ok(String::from_utf8_lossy(&buf).into_owned())
2239    }
2240
2241    /// Primitive-ring census stored on the fingerprint.
2242    ///
2243    /// `counts[k]` is the number of rings of size k.
2244    ///
2245    /// ```
2246    /// let (xyz, edge) = seams::diamond8();
2247    /// let mut system = seams::System::new()?;
2248    /// system.set_ortho(&xyz, edge, edge, edge)?;
2249    /// let fp = system.fingerprint(&seams::FingerprintOptions::default())?;
2250    /// assert!(fp.rings()?.iter().sum::<i32>() > 0);
2251    /// # Ok::<(), seams::Error>(())
2252    /// ```
2253    pub fn rings(&self) -> Result<Vec<i32>, Error> {
2254        let mut counts = vec![0; 13];
2255        check(
2256            unsafe { ffi::seams_fingerprint_rings(self.ptr, counts.as_mut_ptr(), counts.len()) },
2257            self.ptr as *const c_void,
2258        )?;
2259        Ok(counts)
2260    }
2261}
2262
2263/// Owned planar ice-front measurement.
2264///
2265/// ```
2266/// let (xyz, edge) = seams::diamond8();
2267/// let mut system = seams::System::new()?;
2268/// system.set_ortho(&xyz, edge, edge, edge)?;
2269/// let ice = vec![1; 8];
2270/// let front = system.brine(&ice, &seams::BrineOptions::default())?;
2271/// let pockets = front.pockets()?;
2272/// assert!(pockets.pockets >= 0);
2273/// # Ok::<(), seams::Error>(())
2274/// ```
2275pub struct Brine {
2276    ptr: *mut ffi::seams_brine,
2277}
2278
2279unsafe impl Send for Brine {}
2280
2281impl Drop for Brine {
2282    fn drop(&mut self) {
2283        if !self.ptr.is_null() {
2284            unsafe { ffi::seams_brine_destroy(self.ptr) };
2285        }
2286    }
2287}
2288
2289impl Brine {
2290    /// The two planar crossings. Lengths are angstroms.
2291    ///
2292    /// ```
2293    /// let (xyz, edge) = seams::diamond8();
2294    /// let mut system = seams::System::new()?;
2295    /// system.set_ortho(&xyz, edge, edge, edge)?;
2296    /// let front = system.brine(&[1; 8], &seams::BrineOptions::default())?;
2297    /// let crossings = front.fronts()?;
2298    /// assert!(crossings.thickness.is_finite());
2299    /// # Ok::<(), seams::Error>(())
2300    /// ```
2301    pub fn fronts(&self) -> Result<BrineFronts, Error> {
2302        let mut out = BrineFronts {
2303            enter: 0.0,
2304            exit: 0.0,
2305            thickness: 0.0,
2306            found: false,
2307        };
2308        let mut found = 0;
2309        check(
2310            unsafe {
2311                ffi::seams_brine_fronts(
2312                    self.ptr,
2313                    &mut out.enter,
2314                    &mut out.exit,
2315                    &mut out.thickness,
2316                    &mut found,
2317                )
2318            },
2319            self.ptr as *const c_void,
2320        )?;
2321        out.found = found != 0;
2322        Ok(out)
2323    }
2324
2325    /// Molal rejection coefficient. Molality is mol/kg.
2326    ///
2327    /// ```
2328    /// let (xyz, edge) = seams::diamond8();
2329    /// let mut system = seams::System::new()?;
2330    /// system.set_ortho(&xyz, edge, edge, edge)?;
2331    /// let front = system.brine(&[1; 8], &seams::BrineOptions::default())?;
2332    /// let rejection = front.rejection()?;
2333    /// assert!(rejection.k.is_finite() || !rejection.defined);
2334    /// # Ok::<(), seams::Error>(())
2335    /// ```
2336    pub fn rejection(&self) -> Result<Rejection, Error> {
2337        let mut out = Rejection {
2338            ice: 0.0,
2339            liquid: 0.0,
2340            k: 0.0,
2341            defined: false,
2342        };
2343        let mut defined = 0;
2344        check(
2345            unsafe {
2346                ffi::seams_brine_rejection(
2347                    self.ptr,
2348                    &mut out.ice,
2349                    &mut out.liquid,
2350                    &mut out.k,
2351                    &mut defined,
2352                )
2353            },
2354            self.ptr as *const c_void,
2355        )?;
2356        out.defined = defined != 0;
2357        Ok(out)
2358    }
2359
2360    /// Concentration profile along the front axis.
2361    ///
2362    /// ```
2363    /// let (xyz, edge) = seams::diamond8();
2364    /// let mut system = seams::System::new()?;
2365    /// system.set_ortho(&xyz, edge, edge, edge)?;
2366    /// let front = system.brine(&[1; 8], &seams::BrineOptions::default())?;
2367    /// let profile = front.profile()?;
2368    /// assert_eq!(profile.coordinate.len(), profile.molality.len());
2369    /// # Ok::<(), seams::Error>(())
2370    /// ```
2371    pub fn profile(&self) -> Result<BrineProfile, Error> {
2372        let handle = self.ptr as *const c_void;
2373        let mut n_out = 0usize;
2374        check(
2375            unsafe {
2376                ffi::seams_brine_profile(
2377                    self.ptr,
2378                    std::ptr::null_mut(),
2379                    std::ptr::null_mut(),
2380                    std::ptr::null_mut(),
2381                    0,
2382                    &mut n_out,
2383                )
2384            },
2385            handle,
2386        )?;
2387        let mut coordinate = vec![0.0; n_out];
2388        let mut molality = vec![0.0; n_out];
2389        let mut ice_fraction = vec![0.0; n_out];
2390        check(
2391            unsafe {
2392                ffi::seams_brine_profile(
2393                    self.ptr,
2394                    coordinate.as_mut_ptr(),
2395                    molality.as_mut_ptr(),
2396                    ice_fraction.as_mut_ptr(),
2397                    n_out,
2398                    &mut n_out,
2399                )
2400            },
2401            handle,
2402        )?;
2403        coordinate.truncate(n_out);
2404        molality.truncate(n_out);
2405        ice_fraction.truncate(n_out);
2406        Ok(BrineProfile {
2407            coordinate,
2408            molality,
2409            ice_fraction,
2410        })
2411    }
2412
2413    /// Pockets trapped in the ice, and the liquid reservoir.
2414    ///
2415    /// ```
2416    /// let (xyz, edge) = seams::diamond8();
2417    /// let mut system = seams::System::new()?;
2418    /// system.set_ortho(&xyz, edge, edge, edge)?;
2419    /// let front = system.brine(&[1; 8], &seams::BrineOptions::default())?;
2420    /// assert!(front.pockets()?.reservoir_waters >= 0);
2421    /// # Ok::<(), seams::Error>(())
2422    /// ```
2423    pub fn pockets(&self) -> Result<Pockets, Error> {
2424        let mut out = Pockets::default();
2425        check(
2426            unsafe {
2427                ffi::seams_brine_pockets(self.ptr, &mut out.pockets, &mut out.reservoir_waters)
2428            },
2429            self.ptr as *const c_void,
2430        )?;
2431        Ok(out)
2432    }
2433}
2434
2435/// One frame: coordinates, a cell, and the analyses that read them.
2436///
2437/// The handle is freed on drop. It is [`Send`] and not [`Sync`].
2438///
2439/// ```
2440/// let mut system = seams::System::new()?;
2441/// assert_eq!(system.count(), 0);
2442/// let err = system.read("missing-trajectory.lammpstrj", 1, -1).expect_err("no such file");
2443/// assert!(!err.message().is_empty());
2444/// # Ok::<(), seams::Error>(())
2445/// ```
2446pub struct System {
2447    ptr: *mut ffi::seams_system,
2448}
2449
2450unsafe impl Send for System {}
2451
2452impl Drop for System {
2453    fn drop(&mut self) {
2454        if !self.ptr.is_null() {
2455            unsafe { ffi::seams_system_destroy(self.ptr) };
2456        }
2457    }
2458}
2459
2460impl System {
2461    /// Allocate an empty frame.
2462    ///
2463    /// ```
2464    /// let system = seams::System::new()?;
2465    /// assert_eq!(system.count(), 0);
2466    /// # Ok::<(), seams::Error>(())
2467    /// ```
2468    pub fn new() -> Result<Self, Error> {
2469        let ptr = unsafe { ffi::seams_system_create() };
2470        if ptr.is_null() {
2471            return Err(Error::from_status(
2472                ffi::SEAMS_ERR_NOMEM,
2473                message_of(std::ptr::null()),
2474            ));
2475        }
2476        Ok(Self { ptr })
2477    }
2478
2479    fn handle(&self) -> *const c_void {
2480        self.ptr as *const c_void
2481    }
2482
2483    /// Store points in an orthorhombic cell whose origin is zero.
2484    ///
2485    /// ```
2486    /// let (xyz, edge) = seams::diamond8();
2487    /// let mut system = seams::System::new()?;
2488    /// system.set_ortho(&xyz, edge, edge, edge)?;
2489    /// assert_eq!(system.count(), 8);
2490    /// # Ok::<(), seams::Error>(())
2491    /// ```
2492    pub fn set_ortho(&mut self, xyz: &[f64], lx: f64, ly: f64, lz: f64) -> Result<(), Error> {
2493        let n = atom_count(xyz.len())?;
2494        check(
2495            unsafe {
2496                ffi::seams_system_set_ortho(
2497                    self.ptr,
2498                    xyz.as_ptr(),
2499                    n,
2500                    0.0,
2501                    0.0,
2502                    0.0,
2503                    lx,
2504                    ly,
2505                    lz,
2506                    std::ptr::null(),
2507                    std::ptr::null(),
2508                )
2509            },
2510            self.handle(),
2511        )
2512    }
2513
2514    /// Store points and a general nine-number cell.
2515    ///
2516    /// ```
2517    /// let (xyz, edge) = seams::diamond8();
2518    /// let mut box9 = [0.0; 9];
2519    /// box9[3] = edge;
2520    /// box9[4] = edge;
2521    /// box9[5] = edge;
2522    /// box9[6] = 0.3;
2523    /// let mut system = seams::System::new()?;
2524    /// system.set_frame(&xyz, &box9)?;
2525    /// assert_eq!(system.count(), 8);
2526    /// # Ok::<(), seams::Error>(())
2527    /// ```
2528    pub fn set_frame(&mut self, xyz: &[f64], box9: &[f64; 9]) -> Result<(), Error> {
2529        let n = atom_count(xyz.len())?;
2530        check(
2531            unsafe {
2532                ffi::seams_system_set_frame(
2533                    self.ptr,
2534                    xyz.as_ptr(),
2535                    n,
2536                    box9.as_ptr(),
2537                    std::ptr::null(),
2538                    std::ptr::null(),
2539                )
2540            },
2541            self.handle(),
2542        )
2543    }
2544
2545    /// Store points, a cell, and optional species and ids.
2546    ///
2547    /// `box9` is `ox, oy, oz, lx, ly, lz, xy, xz, yz`. Empty `types` and
2548    /// `ids` leave those columns unset.
2549    ///
2550    /// ```
2551    /// let (xyz, edge) = seams::diamond8();
2552    /// let box9 = [0.0, 0.0, 0.0, edge, edge, edge, 0.0, 0.0, 0.0];
2553    /// let types = [1; 8];
2554    /// let mut system = seams::System::new()?;
2555    /// system.set_atoms(&xyz, &box9, &types, &[])?;
2556    /// assert_eq!(system.count(), 8);
2557    /// # Ok::<(), seams::Error>(())
2558    /// ```
2559    pub fn set_atoms(
2560        &mut self,
2561        xyz: &[f64],
2562        box9: &[f64],
2563        types: &[i32],
2564        ids: &[i32],
2565    ) -> Result<(), Error> {
2566        if xyz.len() % 3 != 0 {
2567            return Err(Error::argument("coordinates are not a multiple of 3"));
2568        }
2569        let n = xyz.len() / 3;
2570        if !types.is_empty() && types.len() != n {
2571            return Err(Error::argument(
2572                "types length does not match the atom count",
2573            ));
2574        }
2575        if !ids.is_empty() && ids.len() != n {
2576            return Err(Error::argument("ids length does not match the atom count"));
2577        }
2578        check(
2579            unsafe {
2580                ffi::seams_system_set_atoms(
2581                    self.ptr,
2582                    xyz.as_ptr(),
2583                    n,
2584                    box9.as_ptr(),
2585                    box9.len(),
2586                    if types.is_empty() {
2587                        std::ptr::null()
2588                    } else {
2589                        types.as_ptr()
2590                    },
2591                    if ids.is_empty() {
2592                        std::ptr::null()
2593                    } else {
2594                        ids.as_ptr()
2595                    },
2596                )
2597            },
2598            self.handle(),
2599        )
2600    }
2601
2602    /// Read one frame from a trajectory path.
2603    ///
2604    /// `frame` is 1-based. A negative `type_filter` keeps every atom.
2605    /// The path may be XYZ, CON, a chemfiles format, or a LAMMPS dump.
2606    ///
2607    /// ```
2608    /// let mut system = seams::System::new()?;
2609    /// let err = system.read("no-such-frame.xyz", 1, -1).unwrap_err();
2610    /// assert!(!err.message().is_empty());
2611    /// # Ok::<(), seams::Error>(())
2612    /// ```
2613    pub fn read(&mut self, path: &str, frame: i32, type_filter: i32) -> Result<(), Error> {
2614        let text = c_text(path)?;
2615        check(
2616            unsafe { ffi::seams_system_read(self.ptr, text.as_ptr(), frame, type_filter) },
2617            self.handle(),
2618        )
2619    }
2620
2621    /// Number of points in the frame.
2622    ///
2623    /// ```
2624    /// let system = seams::System::new()?;
2625    /// assert_eq!(system.count(), 0);
2626    /// # Ok::<(), seams::Error>(())
2627    /// ```
2628    #[must_use]
2629    pub fn count(&self) -> i32 {
2630        unsafe { ffi::seams_system_count(self.ptr) }
2631    }
2632
2633    /// Original CHILL labels and nine population counts.
2634    ///
2635    /// ```
2636    /// let (xyz, edge) = seams::diamond8();
2637    /// let mut system = seams::System::new()?;
2638    /// system.set_ortho(&xyz, edge, edge, edge)?;
2639    /// let ice = system.chill(&seams::ChillOptions::default())?;
2640    /// assert_eq!(ice.labels.len(), 8);
2641    /// # Ok::<(), seams::Error>(())
2642    /// ```
2643    pub fn chill(&mut self, options: &ChillOptions) -> Result<Classification, Error> {
2644        self.classify(false, options)
2645    }
2646
2647    /// CHILL+ labels and nine population counts.
2648    ///
2649    /// ```
2650    /// let (xyz, edge) = seams::diamond8();
2651    /// let mut system = seams::System::new()?;
2652    /// system.set_ortho(&xyz, edge, edge, edge)?;
2653    /// let ice = system.chill_plus(&seams::ChillOptions {
2654    ///     graph: seams::Graph::Mutual,
2655    ///     rule: seams::ChillRule::Ovito,
2656    ///     ..seams::ChillOptions::default()
2657    /// })?;
2658    /// assert_eq!(ice.counts.iter().sum::<i32>() as usize, ice.labels.len());
2659    /// # Ok::<(), seams::Error>(())
2660    /// ```
2661    pub fn chill_plus(&mut self, options: &ChillOptions) -> Result<Classification, Error> {
2662        self.classify(true, options)
2663    }
2664
2665    /// Local q_l on the cutoff shell.
2666    ///
2667    /// ```
2668    /// let (xyz, edge) = seams::diamond8();
2669    /// let mut system = seams::System::new()?;
2670    /// system.set_ortho(&xyz, edge, edge, edge)?;
2671    /// let q3 = system.steinhardt(&seams::SteinhardtOptions { order: 3, ..Default::default() })?;
2672    /// assert!(q3.average.is_none());
2673    /// assert_eq!(q3.local.len(), 8);
2674    /// # Ok::<(), seams::Error>(())
2675    /// ```
2676    pub fn steinhardt(&mut self, options: &SteinhardtOptions) -> Result<Steinhardt, Error> {
2677        let n = self.count() as usize;
2678        let mut local = vec![0.0; n];
2679        let mut average = vec![0.0; n];
2680        let bar = if options.average {
2681            average.as_mut_ptr()
2682        } else {
2683            std::ptr::null_mut()
2684        };
2685        check(
2686            unsafe {
2687                ffi::seams_steinhardt(
2688                    self.ptr,
2689                    options.cutoff,
2690                    options.species,
2691                    options.order,
2692                    local.as_mut_ptr(),
2693                    n,
2694                    bar,
2695                    n,
2696                )
2697            },
2698            self.handle(),
2699        )?;
2700        Ok(Steinhardt {
2701            local,
2702            average: if options.average { Some(average) } else { None },
2703        })
2704    }
2705
2706    /// Local q_l on a named graph.
2707    ///
2708    /// ```
2709    /// let (xyz, edge) = seams::diamond8();
2710    /// let mut system = seams::System::new()?;
2711    /// system.set_ortho(&xyz, edge, edge, edge)?;
2712    /// let q4 = system.ql(&seams::OrderOptions { order: 4, ..Default::default() })?;
2713    /// assert_eq!(q4.local.len(), 8);
2714    /// # Ok::<(), seams::Error>(())
2715    /// ```
2716    pub fn ql(&mut self, options: &OrderOptions) -> Result<Steinhardt, Error> {
2717        let n = self.count() as usize;
2718        let mut local = vec![0.0; n];
2719        let mut average = vec![0.0; n];
2720        let bar = if options.average {
2721            average.as_mut_ptr()
2722        } else {
2723            std::ptr::null_mut()
2724        };
2725        check(
2726            unsafe {
2727                ffi::seams_ql(
2728                    self.ptr,
2729                    options.cutoff,
2730                    options.species,
2731                    options.order,
2732                    options.graph as c_int,
2733                    local.as_mut_ptr(),
2734                    n,
2735                    bar,
2736                    n,
2737                )
2738            },
2739            self.handle(),
2740        )?;
2741        Ok(Steinhardt {
2742            local,
2743            average: if options.average { Some(average) } else { None },
2744        })
2745    }
2746
2747    /// Local q4 and q6 on the cutoff shell.
2748    ///
2749    /// ```
2750    /// let (xyz, edge) = seams::diamond8();
2751    /// let mut system = seams::System::new()?;
2752    /// system.set_ortho(&xyz, edge, edge, edge)?;
2753    /// let orders = system.q4q6(3.5)?;
2754    /// let mean = orders.q6.iter().sum::<f64>() / orders.q6.len() as f64;
2755    /// assert!(mean > 0.3);
2756    /// # Ok::<(), seams::Error>(())
2757    /// ```
2758    pub fn q4q6(&mut self, cutoff: f64) -> Result<Q4Q6, Error> {
2759        let n = self.count() as usize;
2760        let mut q4 = vec![0.0; n];
2761        let mut q6 = vec![0.0; n];
2762        check(
2763            unsafe { ffi::seams_q4q6(self.ptr, cutoff, 0, q4.as_mut_ptr(), q6.as_mut_ptr()) },
2764            self.handle(),
2765        )?;
2766        Ok(Q4Q6 { q4, q6 })
2767    }
2768
2769    /// q6-bar, its mean and median, and the ice count above the cut.
2770    ///
2771    /// ```
2772    /// let (xyz, edge) = seams::diamond8();
2773    /// let mut system = seams::System::new()?;
2774    /// system.set_ortho(&xyz, edge, edge, edge)?;
2775    /// let summary = system.q6bar(&seams::Q6BarOptions::default())?;
2776    /// assert!(summary.n_ice >= 0);
2777    /// # Ok::<(), seams::Error>(())
2778    /// ```
2779    pub fn q6bar(&mut self, options: &Q6BarOptions) -> Result<Q6Bar, Error> {
2780        let n = self.count() as usize;
2781        let mut values = vec![0.0; n];
2782        let mut mean = 0.0;
2783        let mut median = 0.0;
2784        let mut n_ice = 0;
2785        check(
2786            unsafe {
2787                ffi::seams_q6bar(
2788                    self.ptr,
2789                    options.cutoff,
2790                    options.species,
2791                    options.ice_cut,
2792                    values.as_mut_ptr(),
2793                    n,
2794                    &mut mean,
2795                    &mut median,
2796                    &mut n_ice,
2797                )
2798            },
2799            self.handle(),
2800        )?;
2801        Ok(Q6Bar {
2802            values,
2803            mean,
2804            median,
2805            n_ice,
2806        })
2807    }
2808
2809    /// Tessellate the selected sites of a fully periodic frame.
2810    ///
2811    /// Pass `None` to choose a search radius from the site density or
2812    /// supply an initial radius in angstroms. The result owns its geometry.
2813    pub fn voronoi(&mut self, seed_radius: Option<f64>) -> Result<VoronoiCells, Error> {
2814        let mut out = std::ptr::null_mut();
2815        check(
2816            unsafe { ffi::seams_voronoi_find(self.ptr, seed_radius.unwrap_or(0.0), &mut out) },
2817            self.handle(),
2818        )?;
2819        let ptr = std::ptr::NonNull::new(out).ok_or_else(|| {
2820            Error::from_status(ffi::SEAMS_ERR_INTERNAL, "Voronoi result is null".into())
2821        })?;
2822        Ok(VoronoiCells { ptr })
2823    }
2824
2825    /// Cutoff or mutual neighbour list.
2826    ///
2827    /// ```
2828    /// let (xyz, edge) = seams::diamond8();
2829    /// let mut system = seams::System::new()?;
2830    /// system.set_ortho(&xyz, edge, edge, edge)?;
2831    /// let list = system.neighbours(&seams::NeighbourOptions::default())?;
2832    /// assert_eq!(list.degrees()?.iter().sum::<i32>(), list.nnz()? as i32);
2833    /// # Ok::<(), seams::Error>(())
2834    /// ```
2835    pub fn neighbours(&mut self, options: &NeighbourOptions) -> Result<Neighbours, Error> {
2836        let mut out = std::ptr::null_mut();
2837        check(
2838            unsafe {
2839                ffi::seams_neighbours_build(
2840                    self.ptr,
2841                    options.cutoff,
2842                    options.species,
2843                    options.graph as c_int,
2844                    &mut out,
2845                )
2846            },
2847            self.handle(),
2848        )?;
2849        Neighbours::adopt(out)
2850    }
2851
2852    /// k-nearest neighbour list.
2853    ///
2854    /// ```
2855    /// let (xyz, edge) = seams::diamond8();
2856    /// let mut system = seams::System::new()?;
2857    /// system.set_ortho(&xyz, edge, edge, edge)?;
2858    /// let list = system.knn(&seams::KnnOptions { mutual: true, ..Default::default() })?;
2859    /// assert!(list.nnz()? > 0);
2860    /// # Ok::<(), seams::Error>(())
2861    /// ```
2862    pub fn knn(&mut self, options: &KnnOptions) -> Result<Neighbours, Error> {
2863        let mut out = std::ptr::null_mut();
2864        check(
2865            unsafe {
2866                ffi::seams_neighbours_knn(
2867                    self.ptr,
2868                    options.k,
2869                    options.cutoff,
2870                    options.species,
2871                    i32::from(options.mutual),
2872                    &mut out,
2873                )
2874            },
2875            self.handle(),
2876        )?;
2877        Neighbours::adopt(out)
2878    }
2879
2880    /// Degree of each atom on the cutoff graph.
2881    ///
2882    /// ```
2883    /// let (xyz, edge) = seams::diamond8();
2884    /// let mut system = seams::System::new()?;
2885    /// system.set_ortho(&xyz, edge, edge, edge)?;
2886    /// let degree = system.neighbour_degree(3.5)?;
2887    /// assert!(degree.iter().all(|d| *d == 4));
2888    /// # Ok::<(), seams::Error>(())
2889    /// ```
2890    pub fn neighbour_degree(&mut self, cutoff: f64) -> Result<Vec<i32>, Error> {
2891        self.neighbours(&NeighbourOptions {
2892            cutoff,
2893            ..NeighbourOptions::default()
2894        })?
2895        .degrees()
2896    }
2897
2898    /// Primitive rings up to a maximum size.
2899    ///
2900    /// ```
2901    /// let (xyz, edge) = seams::diamond8();
2902    /// let mut system = seams::System::new()?;
2903    /// system.set_ortho(&xyz, edge, edge, edge)?;
2904    /// let rings = system.rings(&seams::RingOptions::default())?;
2905    /// assert!(rings.fraction(0)?.is_finite());
2906    /// # Ok::<(), seams::Error>(())
2907    /// ```
2908    pub fn rings(&mut self, options: &RingOptions) -> Result<Rings, Error> {
2909        let mut out = std::ptr::null_mut();
2910        check(
2911            unsafe {
2912                ffi::seams_rings_find(
2913                    self.ptr,
2914                    options.cutoff,
2915                    options.species,
2916                    options.graph as c_int,
2917                    options.max_size,
2918                    &mut out,
2919                )
2920            },
2921            self.handle(),
2922        )?;
2923        Ok(Rings { ptr: out })
2924    }
2925
2926    /// Count of six-rings and the fraction of atoms that sit on one.
2927    ///
2928    /// ```
2929    /// let (xyz, edge) = seams::diamond8();
2930    /// let mut system = seams::System::new()?;
2931    /// system.set_ortho(&xyz, edge, edge, edge)?;
2932    /// let (six, fraction) = system.six_ring_fraction(3.5)?;
2933    /// assert!(six >= 0);
2934    /// assert!(fraction.is_finite());
2935    /// # Ok::<(), seams::Error>(())
2936    /// ```
2937    pub fn six_ring_fraction(&mut self, cutoff: f64) -> Result<(i32, f64), Error> {
2938        let rings = self.rings(&RingOptions {
2939            cutoff,
2940            max_size: 6,
2941            ..RingOptions::default()
2942        })?;
2943        let hist = rings.histogram(6)?;
2944        let fraction = rings.fraction(6)?;
2945        Ok((hist[6], fraction))
2946    }
2947
2948    /// Hexagonal and double-diamond cage membership.
2949    ///
2950    /// ```
2951    /// let (xyz, edge) = seams::diamond8();
2952    /// let mut system = seams::System::new()?;
2953    /// system.set_ortho(&xyz, edge, edge, edge)?;
2954    /// let cages = system.cages(&seams::CageOptions::default())?;
2955    /// let _ = cages.counts()?;
2956    /// # Ok::<(), seams::Error>(())
2957    /// ```
2958    pub fn cages(&mut self, options: &CageOptions) -> Result<Cages, Error> {
2959        let mut out = std::ptr::null_mut();
2960        check(
2961            unsafe {
2962                ffi::seams_cages(
2963                    self.ptr,
2964                    options.cutoff,
2965                    options.species,
2966                    options.graph as c_int,
2967                    options.k,
2968                    i32::from(options.complete),
2969                    &mut out,
2970                )
2971            },
2972            self.handle(),
2973        )?;
2974        Ok(Cages { ptr: out })
2975    }
2976
2977    /// Closed cages of one ring census.
2978    ///
2979    /// ```
2980    /// let (xyz, edge) = seams::diamond8();
2981    /// let mut system = seams::System::new()?;
2982    /// system.set_ortho(&xyz, edge, edge, edge)?;
2983    /// let err = system.signature_cages(&seams::SignatureOptions::default()).unwrap_err();
2984    /// assert_eq!(err.status(), Some(seams::Status::Argument));
2985    /// # Ok::<(), seams::Error>(())
2986    /// ```
2987    pub fn signature_cages(&mut self, options: &SignatureOptions) -> Result<SignatureMatch, Error> {
2988        let text = c_text(&options.spec)?;
2989        let mut out = SignatureMatch::default();
2990        check(
2991            unsafe {
2992                ffi::seams_signature_cages(
2993                    self.ptr,
2994                    options.cutoff,
2995                    options.species,
2996                    options.graph as c_int,
2997                    text.as_ptr(),
2998                    &mut out.cages,
2999                    &mut out.atoms,
3000                )
3001            },
3002            self.handle(),
3003        )?;
3004        Ok(out)
3005    }
3006
3007    /// Partial radial distribution and the cell volume.
3008    ///
3009    /// ```
3010    /// let (xyz, edge) = seams::diamond8();
3011    /// let mut system = seams::System::new()?;
3012    /// system.set_ortho(&xyz, edge, edge, edge)?;
3013    /// let g = system.rdf(&seams::DistributionOptions { rmax: 6.0, bins: 4, ..Default::default() })?;
3014    /// assert_eq!(g.radius.len(), g.g.len());
3015    /// # Ok::<(), seams::Error>(())
3016    /// ```
3017    pub fn rdf(&mut self, options: &DistributionOptions) -> Result<Distribution, Error> {
3018        let mut n_out = 0usize;
3019        let mut volume = 0.0;
3020        check(
3021            unsafe {
3022                ffi::seams_rdf(
3023                    self.ptr,
3024                    options.rmax,
3025                    options.bins,
3026                    options.type_i,
3027                    options.type_j,
3028                    std::ptr::null_mut(),
3029                    std::ptr::null_mut(),
3030                    std::ptr::null_mut(),
3031                    0,
3032                    &mut n_out,
3033                    &mut volume,
3034                )
3035            },
3036            self.handle(),
3037        )?;
3038        let mut radius = vec![0.0; n_out];
3039        let mut g = vec![0.0; n_out];
3040        let mut count = vec![0; n_out];
3041        check(
3042            unsafe {
3043                ffi::seams_rdf(
3044                    self.ptr,
3045                    options.rmax,
3046                    options.bins,
3047                    options.type_i,
3048                    options.type_j,
3049                    radius.as_mut_ptr(),
3050                    g.as_mut_ptr(),
3051                    count.as_mut_ptr(),
3052                    n_out,
3053                    &mut n_out,
3054                    std::ptr::null_mut(),
3055                )
3056            },
3057            self.handle(),
3058        )?;
3059        radius.truncate(n_out);
3060        g.truncate(n_out);
3061        count.truncate(n_out);
3062        Ok(Distribution {
3063            radius,
3064            g,
3065            count,
3066            volume,
3067        })
3068    }
3069
3070    /// Running coordination number along the partial RDF.
3071    ///
3072    /// ```
3073    /// let (xyz, edge) = seams::diamond8();
3074    /// let mut system = seams::System::new()?;
3075    /// system.set_ortho(&xyz, edge, edge, edge)?;
3076    /// let series = system.running_cn(&seams::DistributionOptions { rmax: 6.0, bins: 4, ..Default::default() })?;
3077    /// assert!(!series.coordination.is_empty());
3078    /// # Ok::<(), seams::Error>(())
3079    /// ```
3080    pub fn running_cn(
3081        &mut self,
3082        options: &DistributionOptions,
3083    ) -> Result<RunningCoordination, Error> {
3084        let mut n_out = 0usize;
3085        check(
3086            unsafe {
3087                ffi::seams_running_cn(
3088                    self.ptr,
3089                    options.rmax,
3090                    options.bins,
3091                    options.type_i,
3092                    options.type_j,
3093                    std::ptr::null_mut(),
3094                    std::ptr::null_mut(),
3095                    0,
3096                    &mut n_out,
3097                )
3098            },
3099            self.handle(),
3100        )?;
3101        let mut radius = vec![0.0; n_out];
3102        let mut coordination = vec![0.0; n_out];
3103        check(
3104            unsafe {
3105                ffi::seams_running_cn(
3106                    self.ptr,
3107                    options.rmax,
3108                    options.bins,
3109                    options.type_i,
3110                    options.type_j,
3111                    radius.as_mut_ptr(),
3112                    coordination.as_mut_ptr(),
3113                    n_out,
3114                    &mut n_out,
3115                )
3116            },
3117            self.handle(),
3118        )?;
3119        radius.truncate(n_out);
3120        coordination.truncate(n_out);
3121        Ok(RunningCoordination {
3122            radius,
3123            coordination,
3124        })
3125    }
3126
3127    /// Coordination number integrated to rmax.
3128    ///
3129    /// ```
3130    /// let (xyz, edge) = seams::diamond8();
3131    /// let mut system = seams::System::new()?;
3132    /// system.set_ortho(&xyz, edge, edge, edge)?;
3133    /// let cn = system.coordination(&seams::DistributionOptions { rmax: 3.5, bins: 8, ..Default::default() })?;
3134    /// assert!(cn.is_finite());
3135    /// # Ok::<(), seams::Error>(())
3136    /// ```
3137    pub fn coordination(&mut self, options: &DistributionOptions) -> Result<f64, Error> {
3138        let mut cn = 0.0;
3139        check(
3140            unsafe {
3141                ffi::seams_coordination(
3142                    self.ptr,
3143                    options.rmax,
3144                    options.bins,
3145                    options.type_i,
3146                    options.type_j,
3147                    &mut cn,
3148                )
3149            },
3150            self.handle(),
3151        )?;
3152        Ok(cn)
3153    }
3154
3155    /// Hydrogen-bond count.
3156    ///
3157    /// ```
3158    /// let (xyz, edge) = seams::diamond8();
3159    /// let mut system = seams::System::new()?;
3160    /// system.set_ortho(&xyz, edge, edge, edge)?;
3161    /// let bonds = system.hbonds(&seams::BondOptions::default())?;
3162    /// assert_eq!(bonds, 0);
3163    /// # Ok::<(), seams::Error>(())
3164    /// ```
3165    pub fn hbonds(&mut self, options: &BondOptions) -> Result<i32, Error> {
3166        let mut n_bonds = 0;
3167        check(
3168            unsafe {
3169                ffi::seams_hbonds(
3170                    self.ptr,
3171                    options.cutoff,
3172                    options.oxygen,
3173                    options.hydrogen,
3174                    options.distance,
3175                    options.angle,
3176                    &mut n_bonds,
3177                )
3178            },
3179            self.handle(),
3180        )?;
3181        Ok(n_bonds)
3182    }
3183
3184    /// Enumerate directed donor–hydrogen–acceptor bonds in the current frame.
3185    ///
3186    /// Hydrogen assignment uses the molecule IDs from the trajectory. Donor
3187    /// and acceptor type sets may differ, for example to select water donors
3188    /// and framework acceptors. Indices are zero-based positions in the frame;
3189    /// keep the same atom order and selection when tracking pairs over time.
3190    pub fn directed_hbonds(
3191        &mut self,
3192        donor_types: &[i32],
3193        acceptor_types: &[i32],
3194        options: &DirectedBondOptions,
3195    ) -> Result<Vec<DirectedHbond>, Error> {
3196        let call = |edges, cap, count: &mut usize| unsafe {
3197            ffi::seams_directed_hbonds(
3198                self.ptr,
3199                options.cutoff,
3200                options.distance,
3201                options.angle,
3202                donor_types.as_ptr(),
3203                donor_types.len(),
3204                acceptor_types.as_ptr(),
3205                acceptor_types.len(),
3206                options.hydrogen,
3207                i32::from(options.exclude_same_mol),
3208                edges,
3209                cap,
3210                count,
3211            )
3212        };
3213        let mut count = 0usize;
3214        check(call(std::ptr::null_mut(), 0, &mut count), self.handle())?;
3215        let mut rows = Vec::with_capacity(count);
3216        rows.resize_with(count, || ffi::seams_directed_hbond {
3217            size: std::mem::size_of::<ffi::seams_directed_hbond>() as u32,
3218            donor: 0,
3219            hydrogen: 0,
3220            acceptor: 0,
3221            d_AH: 0.0,
3222            d_DA: 0.0,
3223            angle: 0.0,
3224        });
3225        if count > 0 {
3226            check(
3227                call(rows.as_mut_ptr(), rows.len(), &mut count),
3228                self.handle(),
3229            )?;
3230        }
3231        rows.truncate(count);
3232        let index = |value| {
3233            i32::try_from(value).map_err(|_| {
3234                Error::from_status(
3235                    ffi::SEAMS_ERR_INTERNAL,
3236                    "native site index exceeds i32".into(),
3237                )
3238            })
3239        };
3240        rows.into_iter()
3241            .map(|row| {
3242                Ok(DirectedHbond {
3243                    donor: index(row.donor)?,
3244                    hydrogen: index(row.hydrogen)?,
3245                    acceptor: index(row.acceptor)?,
3246                    acceptor_hydrogen_distance: row.d_AH,
3247                    donor_acceptor_distance: row.d_DA,
3248                    angle: row.angle,
3249                })
3250            })
3251            .collect()
3252    }
3253
3254    /// Number density along one cell axis.
3255    ///
3256    /// ```
3257    /// let (xyz, edge) = seams::diamond8();
3258    /// let mut system = seams::System::new()?;
3259    /// system.set_ortho(&xyz, edge, edge, edge)?;
3260    /// let rho = system.density(&seams::DensityOptions { bins: 2, ..Default::default() })?;
3261    /// assert_eq!(rho.density.len(), 2);
3262    /// # Ok::<(), seams::Error>(())
3263    /// ```
3264    pub fn density(&mut self, options: &DensityOptions) -> Result<DensityProfile, Error> {
3265        let mut n_out = 0usize;
3266        check(
3267            unsafe {
3268                ffi::seams_density_axis(
3269                    self.ptr,
3270                    options.species,
3271                    options.bins,
3272                    options.axis as c_int,
3273                    std::ptr::null_mut(),
3274                    std::ptr::null_mut(),
3275                    0,
3276                    &mut n_out,
3277                )
3278            },
3279            self.handle(),
3280        )?;
3281        let mut coordinate = vec![0.0; n_out];
3282        let mut density = vec![0.0; n_out];
3283        check(
3284            unsafe {
3285                ffi::seams_density_axis(
3286                    self.ptr,
3287                    options.species,
3288                    options.bins,
3289                    options.axis as c_int,
3290                    coordinate.as_mut_ptr(),
3291                    density.as_mut_ptr(),
3292                    n_out,
3293                    &mut n_out,
3294                )
3295            },
3296            self.handle(),
3297        )?;
3298        coordinate.truncate(n_out);
3299        density.truncate(n_out);
3300        Ok(DensityProfile {
3301            coordinate,
3302            density,
3303        })
3304    }
3305
3306    /// Topological fingerprint of the bonded graph.
3307    ///
3308    /// ```
3309    /// let (xyz, edge) = seams::diamond8();
3310    /// let mut system = seams::System::new()?;
3311    /// system.set_ortho(&xyz, edge, edge, edge)?;
3312    /// let fp = system.fingerprint(&seams::FingerprintOptions::default())?;
3313    /// assert!(!fp.key()?.is_empty());
3314    /// # Ok::<(), seams::Error>(())
3315    /// ```
3316    pub fn fingerprint(&mut self, options: &FingerprintOptions) -> Result<Fingerprint, Error> {
3317        let mut out = std::ptr::null_mut();
3318        check(
3319            unsafe {
3320                ffi::seams_fingerprint(
3321                    self.ptr,
3322                    options.cutoff,
3323                    options.species,
3324                    options.k,
3325                    options.graph as c_int,
3326                    options.hops,
3327                    i32::from(options.color_types),
3328                    &mut out,
3329                )
3330            },
3331            self.handle(),
3332        )?;
3333        Ok(Fingerprint { ptr: out })
3334    }
3335
3336    /// Mutual nearest unlike contacts. `spec` is site-table text.
3337    ///
3338    /// ```
3339    /// let (xyz, edge) = seams::diamond8();
3340    /// let mut system = seams::System::new()?;
3341    /// system.set_ortho(&xyz, edge, edge, edge)?;
3342    /// let contacts = system.contact_pairs("1=cationHead")?;
3343    /// assert_eq!(contacts.pairs, 0);
3344    /// # Ok::<(), seams::Error>(())
3345    /// ```
3346    pub fn contact_pairs(&mut self, spec: &str) -> Result<Contacts, Error> {
3347        let text = c_text(spec)?;
3348        let mut out = Contacts::default();
3349        check(
3350            unsafe {
3351                ffi::seams_contact_pairs(
3352                    self.ptr,
3353                    text.as_ptr(),
3354                    &mut out.pairs,
3355                    &mut out.cations,
3356                    &mut out.anions,
3357                )
3358            },
3359            self.handle(),
3360        )?;
3361        Ok(out)
3362    }
3363
3364    /// Largest polar or apolar domain.
3365    ///
3366    /// ```
3367    /// let (xyz, edge) = seams::diamond8();
3368    /// let mut system = seams::System::new()?;
3369    /// system.set_ortho(&xyz, edge, edge, edge)?;
3370    /// let domain = system.domains(&seams::DomainOptions { spec: "1=waterO".into(), ..Default::default() })?;
3371    /// assert!(domain.largest >= 0);
3372    /// # Ok::<(), seams::Error>(())
3373    /// ```
3374    pub fn domains(&mut self, options: &DomainOptions) -> Result<DomainReport, Error> {
3375        let text = c_text(&options.spec)?;
3376        let mut subset = 0;
3377        let mut largest = 0;
3378        let mut percolation = 0.0;
3379        check(
3380            unsafe {
3381                ffi::seams_domains(
3382                    self.ptr,
3383                    options.cutoff,
3384                    text.as_ptr(),
3385                    options.subset as c_int,
3386                    &mut subset,
3387                    &mut largest,
3388                    &mut percolation,
3389                )
3390            },
3391            self.handle(),
3392        )?;
3393        Ok(DomainReport {
3394            subset,
3395            largest,
3396            percolation,
3397        })
3398    }
3399
3400    /// Perfect and imperfect prism counts by ring size.
3401    ///
3402    /// ```
3403    /// let (xyz, edge) = seams::diamond8();
3404    /// let mut system = seams::System::new()?;
3405    /// system.set_ortho(&xyz, edge, edge, edge)?;
3406    /// let prisms = system.prisms(&seams::PrismOptions::default())?;
3407    /// assert_eq!(prisms.perfect.len(), 7);
3408    /// # Ok::<(), seams::Error>(())
3409    /// ```
3410    pub fn prisms(&mut self, options: &PrismOptions) -> Result<PrismCensus, Error> {
3411        let mut out = PrismCensus::default();
3412        check(
3413            unsafe {
3414                ffi::seams_prisms(
3415                    self.ptr,
3416                    options.cutoff,
3417                    options.species,
3418                    out.perfect.as_mut_ptr(),
3419                    out.imperfect.as_mut_ptr(),
3420                    out.perfect.len(),
3421                )
3422            },
3423            self.handle(),
3424        )?;
3425        Ok(out)
3426    }
3427
3428    /// Primitive-ring histogram of a monolayer.
3429    ///
3430    /// `counts[k]` is the number of rings of size k.
3431    ///
3432    /// ```
3433    /// let (xyz, edge) = seams::diamond8();
3434    /// let mut system = seams::System::new()?;
3435    /// system.set_ortho(&xyz, edge, edge, edge)?;
3436    /// let sheet = system.monolayer(&seams::SheetOptions { sheet_area: 10.0, ..Default::default() })?;
3437    /// assert_eq!(sheet.len(), 7);
3438    /// # Ok::<(), seams::Error>(())
3439    /// ```
3440    pub fn monolayer(&mut self, options: &SheetOptions) -> Result<Vec<i32>, Error> {
3441        let len = usize::try_from(options.max_size)
3442            .map_err(|_| Error::argument("ring size is negative"))?
3443            + 1;
3444        let mut counts = vec![0; len];
3445        check(
3446            unsafe {
3447                ffi::seams_monolayer(
3448                    self.ptr,
3449                    options.cutoff,
3450                    options.species,
3451                    options.max_size,
3452                    options.sheet_area,
3453                    counts.as_mut_ptr(),
3454                    len,
3455                )
3456            },
3457            self.handle(),
3458        )?;
3459        Ok(counts)
3460    }
3461
3462    /// Per-atom site kind. `spec` is site-table text such as `1=waterO`.
3463    ///
3464    /// ```
3465    /// let (xyz, edge) = seams::diamond8();
3466    /// let mut system = seams::System::new()?;
3467    /// system.set_ortho(&xyz, edge, edge, edge)?;
3468    /// let kinds = system.site_table("1=waterO")?;
3469    /// assert_eq!(kinds.len(), 8);
3470    /// # Ok::<(), seams::Error>(())
3471    /// ```
3472    pub fn site_table(&mut self, spec: &str) -> Result<Vec<i32>, Error> {
3473        let text = c_text(spec)?;
3474        let n = self.count() as usize;
3475        let mut kinds = vec![0; n];
3476        check(
3477            unsafe { ffi::seams_site_table(self.ptr, text.as_ptr(), kinds.as_mut_ptr(), n) },
3478            self.handle(),
3479        )?;
3480        Ok(kinds)
3481    }
3482
3483    /// Per-atom ice-shell label.
3484    ///
3485    /// A non-positive `shell_rmsd` selects the library ceiling. The label
3486    /// is 0 for ice Ih, 1 for ice Ic, 2 for stacking disorder, or -1 when
3487    /// the shell does not match.
3488    ///
3489    /// ```
3490    /// let (xyz, edge) = seams::diamond8();
3491    /// let mut system = seams::System::new()?;
3492    /// system.set_ortho(&xyz, edge, edge, edge)?;
3493    /// let labels = system.symmetry(0.0)?;
3494    /// assert_eq!(labels.len(), 8);
3495    /// # Ok::<(), seams::Error>(())
3496    /// ```
3497    pub fn symmetry(&mut self, shell_rmsd: f64) -> Result<Vec<i32>, Error> {
3498        let n = self.count() as usize;
3499        let mut labels = vec![0; n];
3500        check(
3501            unsafe { ffi::seams_system_symmetry(self.ptr, shell_rmsd, labels.as_mut_ptr(), n) },
3502            self.handle(),
3503        )?;
3504        Ok(labels)
3505    }
3506
3507    /// Planar ice front from an ice assignment.
3508    ///
3509    /// `ice[i]` is non-zero when atom i is ice. The slice length must
3510    /// equal [`count`](Self::count).
3511    ///
3512    /// ```
3513    /// let (xyz, edge) = seams::diamond8();
3514    /// let mut system = seams::System::new()?;
3515    /// system.set_ortho(&xyz, edge, edge, edge)?;
3516    /// let front = system.brine(&[1; 8], &seams::BrineOptions::default())?;
3517    /// let _ = front.profile()?;
3518    /// # Ok::<(), seams::Error>(())
3519    /// ```
3520    pub fn brine(&mut self, ice: &[i32], options: &BrineOptions) -> Result<Brine, Error> {
3521        let mut out = std::ptr::null_mut();
3522        check(
3523            unsafe {
3524                ffi::seams_brine_analyse(
3525                    self.ptr,
3526                    ice.as_ptr(),
3527                    ice.len(),
3528                    options.water_type,
3529                    options.ion_type,
3530                    options.bins,
3531                    options.axis as c_int,
3532                    &mut out,
3533                )
3534            },
3535            self.handle(),
3536        )?;
3537        Ok(Brine { ptr: out })
3538    }
3539
3540    fn classify(&mut self, plus: bool, options: &ChillOptions) -> Result<Classification, Error> {
3541        let n = self.count() as usize;
3542        let mut labels = vec![0; n];
3543        let mut counts = [0; 9];
3544        if plus {
3545            check(
3546                unsafe {
3547                    ffi::seams_chill_plus(
3548                        self.ptr,
3549                        options.cutoff,
3550                        options.species,
3551                        options.graph as c_int,
3552                        options.rule as c_int,
3553                        labels.as_mut_ptr(),
3554                        counts.as_mut_ptr(),
3555                    )
3556                },
3557                self.handle(),
3558            )?;
3559        } else {
3560            check(
3561                unsafe {
3562                    ffi::seams_chill(
3563                        self.ptr,
3564                        options.cutoff,
3565                        options.species,
3566                        options.graph as c_int,
3567                        options.rule as c_int,
3568                        labels.as_mut_ptr(),
3569                        n,
3570                        counts.as_mut_ptr(),
3571                    )
3572                },
3573                self.handle(),
3574            )?;
3575        }
3576        Ok(Classification { labels, counts })
3577    }
3578}