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