use crate::atoms::NodeId;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
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,
frame: CoordinateFrame,
configs: Vec<Vec<f64>>,
config_names: Vec<String>,
active: usize,
#[serde(skip)]
refcount: Vec<u32>,
permutation: Option<Vec<u32>>,
}
pub(crate) fn ensure_same_coords(a: &Handle<Coords>, b: &Handle<Coords>) -> Result<()> {
if a.same_object(b) {
Ok(())
} else {
Err(PyrucastError::Message("mismatched Coords".into()))
}
}
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,
refcount: Vec::new(),
permutation: None,
})
}
pub fn axisymmetric() -> Self {
Self {
dim: 2,
frame: CoordinateFrame::Axisymmetric,
configs: vec![Vec::new()],
config_names: vec!["default".into()],
active: 0,
refcount: Vec::new(),
permutation: None,
}
}
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(Self::negative_radius(what, coords[0]));
}
Ok(())
}
fn check_radii(&self, what: &str, flat: &[f64]) -> Result<()> {
if !self.frame.is_axisymmetric() {
return Ok(());
}
match flat.chunks_exact(self.dim as usize).find(|p| p[0] < 0.0) {
Some(p) => Err(Self::negative_radius(what, p[0])),
None => Ok(()),
}
}
fn negative_radius(what: &str, x: f64) -> PyrucastError {
PyrucastError::Message(format!(
"{what}: negative radius x = {x} in an axisymmetric Coords \
(x = r ≥ 0, y = z along the axis of revolution)"
))
}
fn check_bulk(&self, what: &str, ids: &[NodeId], values: &[f64]) -> Result<()> {
let d = self.dim as usize;
if values.len() != ids.len() * d {
return Err(PyrucastError::Message(format!(
"{what}: {} value(s) for {} node(s) in dimension {d}",
values.len(),
ids.len()
)));
}
self.ensure_all_alive(ids)
}
pub fn node_count(&self) -> usize {
self.configs[0].len() / self.dim as usize
}
pub(crate) fn contains(&self, id: NodeId) -> bool {
(id.0 as usize) < self.node_count()
}
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.node_count() as u32;
for set in &mut self.configs {
set.extend_from_slice(coords);
}
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()
)));
}
self.check_radii("add_nodes", flat)?;
let start = self.node_count() as u32;
let n = flat.len() / d;
for set in &mut self.configs {
set.extend_from_slice(flat);
}
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.node_count();
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.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 {
self.refcount.get(id.0 as usize).copied().unwrap_or(0)
}
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.contains(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(())
}
pub fn set_positions(&mut self, ids: &[NodeId], positions: &[f64]) -> Result<()> {
self.check_bulk("set_positions", ids, positions)?;
self.check_radii("set_positions", positions)?;
let d = self.dim as usize;
let set = &mut self.configs[self.active];
for (&id, x) in ids.iter().zip(positions.chunks_exact(d)) {
let s = id.0 as usize * d;
set[s..s + d].copy_from_slice(x);
}
Ok(())
}
fn ensure_alive(&self, id: NodeId) -> Result<()> {
if !self.contains(id) {
return Err(PyrucastError::Message(format!("unknown node {}", id.0)));
}
Ok(())
}
pub fn iter_live(&self) -> impl Iterator<Item = NodeId> + '_ {
(0..self.node_count() as u32).map(NodeId)
}
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 displace_from(
&mut self,
reference: usize,
target: usize,
ids: &[NodeId],
increments: &[f64],
) -> Result<()> {
let n_configs = self.configs.len();
if reference >= n_configs || target >= n_configs {
return Err(PyrucastError::Message(format!(
"displace_from: configurations {reference} and {target}, of {n_configs}"
)));
}
if reference == target {
return Err(PyrucastError::Message(format!(
"displace_from: target {target} is the reference itself — it would be lost; \
add a configuration (add_config) to lay the displaced one in"
)));
}
self.check_bulk("displace_from", ids, increments)?;
self.check_moved_radii("displace_from", reference, ids, increments)?;
let d = self.dim as usize;
let (src, dst) = if reference < target {
let (low, high) = self.configs.split_at_mut(target);
(&low[reference], &mut high[0])
} else {
let (low, high) = self.configs.split_at_mut(reference);
(&high[0], &mut low[target])
};
dst.copy_from_slice(src);
for (&id, inc) in ids.iter().zip(increments.chunks_exact(d)) {
let s = id.0 as usize * d;
for (x, du) in dst[s..s + d].iter_mut().zip(inc) {
*x += du;
}
}
Ok(())
}
pub fn displace(&mut self, ids: &[NodeId], increments: &[f64]) -> Result<()> {
self.check_bulk("displace", ids, increments)?;
self.check_moved_radii("displace", self.active, ids, increments)?;
let d = self.dim as usize;
let set = &mut self.configs[self.active];
for (&id, inc) in ids.iter().zip(increments.chunks_exact(d)) {
let s = id.0 as usize * d;
for (x, du) in set[s..s + d].iter_mut().zip(inc) {
*x += du;
}
}
Ok(())
}
fn check_moved_radii(
&self,
what: &str,
from: usize,
ids: &[NodeId],
increments: &[f64],
) -> Result<()> {
if !self.frame.is_axisymmetric() {
return Ok(());
}
let d = self.dim as usize;
let set = &self.configs[from];
let negative = ids
.iter()
.zip(increments.chunks_exact(d))
.map(|(&id, inc)| set[id.0 as usize * d] + inc[0])
.find(|&r| r < 0.0);
match negative {
Some(r) => Err(Self::negative_radius(what, r)),
None => 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 n = self.node_count();
if perm.len() != n {
return Err(PyrucastError::Message(format!(
"set_permutation: length {} ≠ node count {}",
perm.len(),
n
)));
}
let n_u = n as u32;
let mut seen = vec![false; n];
for &v in &perm {
if v >= n_u {
return Err(PyrucastError::Message(format!(
"set_permutation: value {} ≥ node count {}",
v, n_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("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 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={}, permutation: {}",
self.dim,
frame_label,
self.configs.len(),
active_name,
self.node_count(),
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.node_count()];
}
}
#[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);
}
#[test]
fn cartesian_by_default_axisymmetric_on_demand() {
assert!(!Coords::new(2).unwrap().is_axisymmetric());
let c = Coords::axisymmetric();
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();
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 displace_refuses_a_negative_radius_before_any_node_moves() {
let mut c = Coords::axisymmetric();
let a = c.add_node(&[1.0, 0.0]).unwrap();
let b = c.add_node(&[0.5, 0.0]).unwrap();
let err = c.displace(&[a, b], &[1.0, 1.0, -1.0, 0.0]).unwrap_err();
assert!(format!("{err}").contains("negative radius"));
assert_eq!(c.position(a).unwrap(), &[1.0, 0.0]);
assert_eq!(c.position(b).unwrap(), &[0.5, 0.0]);
assert!(c.displace(&[a], &[1.0]).is_err());
assert_eq!(c.position(a).unwrap(), &[1.0, 0.0]);
let current = c.add_config("current");
assert!(c.displace_from(0, current, &[b], &[-1.0, 0.0]).is_err());
}
#[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.contains(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 an_unreferenced_node_stays() {
let mut c = Coords::new(1).unwrap();
let a = c.add_node(&[3.0]).unwrap();
c.incref(a).unwrap(); c.decref(a).unwrap(); c.decref(a).unwrap(); assert_eq!(c.refcount(a), 0);
assert_eq!(c.position(a).unwrap(), &[3.0]);
c.incref(a).unwrap();
assert_eq!(c.refcount(a), 1);
let b = c.add_node(&[1.0]).unwrap();
assert_eq!((b.0, c.node_count()), (1, 2));
}
#[test]
fn an_unknown_id_is_an_error() {
let mut c = Coords::new(1).unwrap();
c.add_node(&[42.0]).unwrap();
let ghost = NodeId(1);
let err = c.position(ghost).unwrap_err();
assert!(format!("{err}").contains("unknown node 1"));
assert!(c.set_position(ghost, &[0.0]).is_err());
assert!(c.incref(ghost).is_err());
assert!(c.decref(ghost).is_err());
assert_eq!(c.refcount(ghost), 0);
}
#[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_walks_every_node() {
let mut c = Coords::new(1).unwrap();
c.add_node(&[0.0]).unwrap();
let b = c.add_node(&[1.0]).unwrap();
c.add_node(&[2.0]).unwrap();
c.decref(b).unwrap();
let ids: Vec<u32> = c.iter_live().map(|n| n.0).collect();
assert_eq!(ids, vec![0, 1, 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)");
}
}