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