use crate::atoms::NodeId;
use crate::error::{PyrucastError, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum CoordinateFrame {
#[default]
Cartesian,
Axisymmetric,
}
impl CoordinateFrame {
pub fn is_axisymmetric(self) -> bool {
self == Self::Axisymmetric
}
}
impl fmt::Display for CoordinateFrame {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Cartesian => "cartesian",
Self::Axisymmetric => "axisymmetric",
})
}
}
#[derive(Serialize, Deserialize)]
pub struct Coords {
dim: u8,
#[serde(default)]
frame: CoordinateFrame,
configs: Vec<Vec<f64>>,
config_names: Vec<String>,
active: usize,
alive: Vec<bool>,
#[serde(skip)]
refcount: Vec<u32>,
permutation: Option<Vec<u32>>,
}
impl Coords {
pub fn new(dim: u8) -> Result<Self> {
if dim == 0 {
return Err(PyrucastError::Message("dim must be ≥ 1".into()));
}
Ok(Self {
dim,
frame: CoordinateFrame::Cartesian,
configs: vec![Vec::new()],
config_names: vec!["default".into()],
active: 0,
alive: Vec::new(),
refcount: Vec::new(),
permutation: None,
})
}
pub fn axisymmetric() -> Result<Self> {
Ok(Self {
frame: CoordinateFrame::Axisymmetric,
..Self::new(2)?
})
}
pub fn dim(&self) -> u8 {
self.dim
}
pub fn frame(&self) -> CoordinateFrame {
self.frame
}
pub fn is_axisymmetric(&self) -> bool {
self.frame.is_axisymmetric()
}
fn check_radius(&self, what: &str, coords: &[f64]) -> Result<()> {
if self.frame.is_axisymmetric() && coords[0] < 0.0 {
return Err(PyrucastError::Message(format!(
"{what}: negative radius x = {} in an axisymmetric Coords \
(x = r ≥ 0, y = z along the axis of revolution)",
coords[0]
)));
}
Ok(())
}
pub fn node_count(&self) -> usize {
self.alive.iter().filter(|&&a| a).count()
}
pub fn capacity(&self) -> usize {
self.alive.len()
}
pub fn is_alive(&self, id: NodeId) -> bool {
self.alive.get(id.0 as usize).copied().unwrap_or(false)
}
pub fn add_node(&mut self, coords: &[f64]) -> Result<NodeId> {
if coords.len() != self.dim as usize {
return Err(PyrucastError::Message(format!(
"add_node: expected {} coordinates, got {}",
self.dim,
coords.len()
)));
}
self.check_radius("add_node", coords)?;
let id = self.alive.len() as u32;
for set in &mut self.configs {
set.extend_from_slice(coords);
}
self.alive.push(true);
self.refcount.push(1);
if let Some(perm) = &mut self.permutation {
perm.push(id);
}
Ok(NodeId(id))
}
pub fn add_nodes(&mut self, flat: &[f64]) -> Result<std::ops::Range<u32>> {
let d = self.dim as usize;
if !flat.len().is_multiple_of(d) {
return Err(PyrucastError::Message(format!(
"add_nodes: buffer of {} values is not a multiple of dim = {d}",
flat.len()
)));
}
for p in flat.chunks(d) {
self.check_radius("add_nodes", p)?;
}
let start = self.alive.len() as u32;
let n = flat.len() / d;
for set in &mut self.configs {
set.extend_from_slice(flat);
}
self.alive.resize(self.alive.len() + n, true);
self.refcount.resize(self.refcount.len() + n, 1);
if let Some(perm) = &mut self.permutation {
perm.extend(start..start + n as u32);
}
Ok(start..start + n as u32)
}
pub(crate) fn add_counted_nodes(
&mut self,
refcounts: &[u32],
fill: impl FnOnce(&mut [f64]),
) -> Result<std::ops::Range<u32>> {
let d = self.dim as usize;
let n = refcounts.len();
let start = self.alive.len();
let base = start * d;
let (first, rest) = self.configs.split_at_mut(1);
let first = &mut first[0];
first.resize(base + n * d, 0.0);
fill(&mut first[base..]);
if self.frame.is_axisymmetric()
&& let Some(p) = first[base..].chunks_exact(d).find(|p| p[0] < 0.0)
{
let msg = format!(
"add_nodes: negative radius x = {} in an axisymmetric Coords \
(x = r ≥ 0, y = z along the axis of revolution)",
p[0]
);
first.truncate(base);
return Err(PyrucastError::Message(msg));
}
for set in rest {
set.extend_from_slice(&first[base..]);
}
self.alive.resize(start + n, true);
self.refcount.extend_from_slice(refcounts);
let (start, end) = (start as u32, (start + n) as u32);
if let Some(perm) = &mut self.permutation {
perm.extend(start..end);
}
Ok(start..end)
}
pub(crate) fn positions_of(&self, ids: &[NodeId], out: &mut [f64]) {
let d = self.dim as usize;
let set = &self.configs[self.active];
for (dst, id) in out.chunks_exact_mut(d).zip(ids) {
let at = id.0 as usize * d;
dst.copy_from_slice(&set[at..at + d]);
}
}
pub fn incref(&mut self, id: NodeId) -> Result<()> {
self.ensure_alive(id)?;
let r = &mut self.refcount[id.0 as usize];
*r = r.saturating_add(1);
Ok(())
}
pub fn decref(&mut self, id: NodeId) -> Result<()> {
self.ensure_alive(id)?;
let r = &mut self.refcount[id.0 as usize];
if *r == 0 {
return Err(PyrucastError::Message(format!(
"decref: refcount already zero for node {}",
id.0
)));
}
*r -= 1;
Ok(())
}
pub fn incref_all(&mut self, ids: &[NodeId]) -> Result<()> {
self.ensure_all_alive(ids)?;
for &id in ids {
let r = &mut self.refcount[id.0 as usize];
*r = r.saturating_add(1);
}
Ok(())
}
pub fn decref_all(&mut self, ids: &[NodeId]) -> Result<()> {
self.ensure_all_alive(ids)?;
for (done, &id) in ids.iter().enumerate() {
let r = &mut self.refcount[id.0 as usize];
if *r == 0 {
for &m in &ids[..done] {
self.refcount[m.0 as usize] += 1;
}
return Err(PyrucastError::Message(format!(
"decref_all: refcount already zero for node {}",
id.0
)));
}
*r -= 1;
}
Ok(())
}
pub fn refcount(&self, id: NodeId) -> u32 {
if self.is_alive(id) {
self.refcount[id.0 as usize]
} else {
0
}
}
pub fn gc(&mut self) -> usize {
let mut collected = 0;
for i in 0..self.alive.len() {
if self.alive[i] && self.refcount[i] == 0 {
self.alive[i] = false;
collected += 1;
}
}
collected
}
pub fn position(&self, id: NodeId) -> Result<&[f64]> {
self.ensure_alive(id)?;
let d = self.dim as usize;
let s = id.0 as usize * d;
Ok(&self.configs[self.active][s..s + d])
}
pub fn ensure_all_alive(&self, ids: &[NodeId]) -> Result<()> {
use crate::parallel::*;
match ids
.par_iter()
.with_min_len(MIN_PARALLEL_LEN)
.find_any(|&&id| !self.is_alive(id))
{
Some(&id) => self.ensure_alive(id),
None => Ok(()),
}
}
pub(crate) fn position_alive(&self, id: NodeId) -> &[f64] {
let d = self.dim as usize;
let s = id.0 as usize * d;
&self.configs[self.active][s..s + d]
}
pub fn set_position(&mut self, id: NodeId, coords: &[f64]) -> Result<()> {
self.ensure_alive(id)?;
if coords.len() != self.dim as usize {
return Err(PyrucastError::Message(format!(
"set_position: expected {} coordinates, got {}",
self.dim,
coords.len()
)));
}
self.check_radius("set_position", coords)?;
let d = self.dim as usize;
let s = id.0 as usize * d;
self.configs[self.active][s..s + d].copy_from_slice(coords);
Ok(())
}
fn ensure_alive(&self, id: NodeId) -> Result<()> {
if !self.is_alive(id) {
return Err(PyrucastError::Message(format!(
"node {} not found or collected",
id.0
)));
}
Ok(())
}
pub fn iter_live(&self) -> impl Iterator<Item = NodeId> + '_ {
self.alive
.iter()
.enumerate()
.filter_map(|(i, &a)| a.then_some(NodeId(i as u32)))
}
pub fn add_config(&mut self, name: impl Into<String>) -> usize {
let copy = self.configs[self.active].clone();
self.configs.push(copy);
self.config_names.push(name.into());
self.configs.len() - 1
}
pub fn select(&mut self, config: usize) -> Result<()> {
if config >= self.configs.len() {
return Err(PyrucastError::Message(format!(
"select: index {} ≥ configuration count ({})",
config,
self.configs.len()
)));
}
self.active = config;
Ok(())
}
pub fn active(&self) -> usize {
self.active
}
pub fn names(&self) -> &[String] {
&self.config_names
}
pub fn permutation(&self) -> Option<&[u32]> {
self.permutation.as_deref()
}
pub fn set_permutation(&mut self, perm: Vec<u32>) -> Result<()> {
let cap = self.capacity();
if perm.len() != cap {
return Err(PyrucastError::Message(format!(
"set_permutation: length {} ≠capacity {}",
perm.len(),
cap
)));
}
let cap_u = cap as u32;
let mut seen = vec![false; cap];
for &v in &perm {
if v >= cap_u {
return Err(PyrucastError::Message(format!(
"set_permutation: value {} ≥ capacity {}",
v, cap_u
)));
}
let i = v as usize;
if seen[i] {
return Err(PyrucastError::Message(format!(
"set_permutation: duplicate value {}",
v
)));
}
seen[i] = true;
}
self.permutation = Some(perm);
Ok(())
}
pub fn clear_permutation(&mut self) {
self.permutation = None;
}
}
impl fmt::Debug for Coords {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Coords")
.field("dim", &self.dim)
.field("frame", &self.frame)
.field("configs", &self.config_names)
.field("active", &self.active)
.field("node_count", &self.node_count())
.field("capacity", &self.capacity())
.field("permutation", &self.permutation.is_some())
.finish()
}
}
impl fmt::Display for Coords {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let active_name = &self.config_names[self.active];
let collected = self.capacity() - self.node_count();
let perm_label = if self.permutation.is_some() {
"custom"
} else {
"identity"
};
let frame_label = match self.frame {
CoordinateFrame::Cartesian => String::new(),
f => format!(" ({f})"),
};
write!(
f,
"Coords: dim={}{}, configs={} (active=\"{}\"), nodes={} ({} collected), permutation: {}",
self.dim,
frame_label,
self.configs.len(),
active_name,
self.node_count(),
collected,
perm_label
)
}
}
impl crate::dump::Dump for Coords {
fn render(&self, opts: &crate::dump::DumpOptions) -> String {
use crate::dump::{fmt_float, table};
let dim = self.dim as usize;
const AXES: [&str; 3] = ["x", "y", "z"];
const AXES_AXI: [&str; 2] = ["r", "z"];
let axes: &[&str] = if self.frame.is_axisymmetric() {
&AXES_AXI
} else {
&AXES
};
let mut headers = vec!["node".to_string()];
headers.extend((0..dim).map(|i| axes.get(i).copied().unwrap_or("?").to_string()));
headers.push("refs".to_string());
let rows: Vec<Vec<String>> = self
.iter_live()
.map(|id| {
let mut row = vec![id.to_string()];
match self.position(id) {
Ok(c) => row.extend(c.iter().map(|v| fmt_float(*v, opts.precision))),
Err(_) => row.extend((0..dim).map(|_| "?".to_string())),
}
row.push(self.refcount(id).to_string());
row
})
.collect();
format!("{self}\n{}", table(&headers, &rows, opts))
}
}
impl crate::archive::Archivable for Coords {
const TAG: &'static str = "Coords";
fn on_load(&mut self) {
self.refcount = vec![0; self.alive.len()];
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_and_dim() {
let c = Coords::new(3).unwrap();
assert_eq!(c.dim(), 3);
assert_eq!(c.node_count(), 0);
assert_eq!(c.capacity(), 0);
}
#[test]
fn cartesian_by_default_axisymmetric_on_demand() {
assert!(!Coords::new(2).unwrap().is_axisymmetric());
let c = Coords::axisymmetric().unwrap();
assert_eq!(c.dim(), 2);
assert_eq!(c.frame(), CoordinateFrame::Axisymmetric);
assert!(c.is_axisymmetric());
assert!(Coords::new(2).unwrap().to_string().contains("dim=2,"));
assert!(c.to_string().contains("dim=2 (axisymmetric)"));
}
#[test]
fn axisymmetric_rejects_a_negative_radius() {
let mut c = Coords::axisymmetric().unwrap();
let err = c.add_node(&[-1.0, 0.0]).unwrap_err();
assert!(format!("{err}").contains("negative radius"));
let id = c.add_node(&[0.0, 2.0]).unwrap();
assert!(c.set_position(id, &[-0.5, 2.0]).is_err());
c.set_position(id, &[0.5, 2.0]).unwrap();
assert!(Coords::new(2).unwrap().add_node(&[-1.0, 0.0]).is_ok());
}
#[test]
fn dim_zero_rejected() {
let err = Coords::new(0).unwrap_err();
assert!(matches!(err, PyrucastError::Message(_)));
}
#[test]
fn add_node_initializes_refcount_to_one() {
let mut c = Coords::new(2).unwrap();
let a = c.add_node(&[0.0, 0.0]).unwrap();
assert_eq!(c.refcount(a), 1);
assert!(c.is_alive(a));
}
#[test]
fn add_node_invalid_dim() {
let mut c = Coords::new(3).unwrap();
let err = c.add_node(&[1.0, 2.0]).unwrap_err();
assert!(matches!(err, PyrucastError::Message(_)));
}
#[test]
fn gc_does_not_collect_referenced_nodes() {
let mut c = Coords::new(2).unwrap();
let a = c.add_node(&[0.0, 0.0]).unwrap();
assert_eq!(c.gc(), 0);
assert!(c.is_alive(a));
c.decref(a).unwrap();
assert_eq!(c.refcount(a), 0);
assert_eq!(c.gc(), 1);
assert!(!c.is_alive(a));
}
#[test]
fn incref_protects_from_gc() {
let mut c = Coords::new(1).unwrap();
let a = c.add_node(&[3.0]).unwrap();
c.incref(a).unwrap(); c.decref(a).unwrap(); assert_eq!(c.gc(), 0);
c.decref(a).unwrap(); assert_eq!(c.gc(), 1);
}
#[test]
fn id_not_reused_after_gc() {
let mut c = Coords::new(1).unwrap();
let a = c.add_node(&[0.0]).unwrap();
c.decref(a).unwrap();
c.gc();
let b = c.add_node(&[1.0]).unwrap();
assert_ne!(a.0, b.0);
assert_eq!(b.0, 1);
assert_eq!(c.capacity(), 2);
}
#[test]
fn coord_after_gc_is_error() {
let mut c = Coords::new(1).unwrap();
let a = c.add_node(&[42.0]).unwrap();
c.decref(a).unwrap();
c.gc();
assert!(c.position(a).is_err());
assert!(c.set_position(a, &[0.0]).is_err());
assert!(c.incref(a).is_err());
assert!(c.decref(a).is_err());
}
#[test]
fn decref_at_zero_is_error() {
let mut c = Coords::new(1).unwrap();
let a = c.add_node(&[0.0]).unwrap();
c.decref(a).unwrap();
let err = c.decref(a).unwrap_err();
assert!(matches!(err, PyrucastError::Message(_)));
}
#[test]
fn set_position_modifies_active_config() {
let mut c = Coords::new(2).unwrap();
let a = c.add_node(&[0.0, 0.0]).unwrap();
c.set_position(a, &[3.0, 4.0]).unwrap();
assert_eq!(c.position(a).unwrap(), &[3.0, 4.0]);
}
#[test]
fn multiple_configs_and_select() {
let mut c = Coords::new(2).unwrap();
let a = c.add_node(&[0.0, 0.0]).unwrap();
let s2 = c.add_config("deformed");
assert_eq!(s2, 1);
c.select(s2).unwrap();
c.set_position(a, &[10.0, 20.0]).unwrap();
c.select(0).unwrap();
assert_eq!(c.position(a).unwrap(), &[0.0, 0.0]);
c.select(1).unwrap();
assert_eq!(c.position(a).unwrap(), &[10.0, 20.0]);
assert_eq!(c.names(), &["default".to_string(), "deformed".to_string()]);
}
#[test]
fn select_invalid() {
let mut c = Coords::new(2).unwrap();
assert!(c.select(5).is_err());
}
#[test]
fn iter_live_skips_collected() {
let mut c = Coords::new(1).unwrap();
let a = c.add_node(&[0.0]).unwrap();
let b = c.add_node(&[1.0]).unwrap();
let _cc = c.add_node(&[2.0]).unwrap();
c.decref(b).unwrap();
c.gc();
let live: Vec<u32> = c.iter_live().map(|n| n.0).collect();
assert_eq!(live, vec![a.0, 2]);
}
#[test]
fn permutation_validation_and_invariant() {
let mut c = Coords::new(1).unwrap();
for k in 0..4 {
c.add_node(&[k as f64]).unwrap();
}
c.set_permutation(vec![3, 2, 1, 0]).unwrap();
assert_eq!(c.permutation(), Some(&[3u32, 2, 1, 0][..]));
assert!(c.set_permutation(vec![0, 0, 1, 2]).is_err());
assert!(c.set_permutation(vec![0, 1, 2, 99]).is_err());
assert!(c.set_permutation(vec![0, 1, 2]).is_err());
c.clear_permutation();
assert!(c.permutation().is_none());
}
#[test]
fn permutation_extended_by_add_node() {
let mut c = Coords::new(1).unwrap();
for k in 0..3 {
c.add_node(&[k as f64]).unwrap();
}
c.set_permutation(vec![2, 1, 0]).unwrap();
c.add_node(&[42.0]).unwrap();
let perm = c.permutation().unwrap();
assert_eq!(perm.len(), 4);
let mut sorted = perm.to_vec();
sorted.sort();
assert_eq!(sorted, vec![0, 1, 2, 3]);
}
#[test]
fn debug_display() {
let mut c = Coords::new(2).unwrap();
c.add_node(&[0.0, 0.0]).unwrap();
c.add_node(&[1.0, 1.0]).unwrap();
let d = format!("{:?}", c);
assert!(d.contains("Coords"));
assert!(d.contains("dim"));
let s = format!("{}", c);
assert!(s.contains("dim=2"));
assert!(s.contains("nodes=2"));
assert!(s.contains("identity"));
}
#[test]
fn nodeid_display_and_debug() {
let n = NodeId(7);
assert_eq!(format!("{}", n), "7");
assert_eq!(format!("{:?}", n), "NodeId(7)");
}
}