Skip to main content

seams/
lib.rs

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