use crate::aggregate::Aggregate;
use crate::containers::element_field::{ElementField, SubElementField};
use crate::containers::field::{Field, SubField};
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::mesh::SubMesh;
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::parallel::*;
use serde::{Deserialize, Serialize};
use std::fmt;
pub type ScalarSeriesSet = Vec<(String, Vec<(f64, f64)>)>;
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum OutOfRange {
#[default]
Error,
Clamp,
Extrapolate,
}
impl OutOfRange {
pub fn name(self) -> &'static str {
match self {
OutOfRange::Error => "error",
OutOfRange::Clamp => "clamp",
OutOfRange::Extrapolate => "extrapolate",
}
}
}
impl crate::named::Named for OutOfRange {
const LABEL: &'static str = "out_of_range policy";
const VALUES: &'static [Self] = &[Self::Error, Self::Clamp, Self::Extrapolate];
fn name(self) -> &'static str {
OutOfRange::name(self)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ValueKind {
Scalar,
Node,
Element,
}
impl ValueKind {
fn label(self) -> &'static str {
match self {
ValueKind::Scalar => "scalar",
ValueKind::Node => "node",
ValueKind::Element => "element",
}
}
}
#[derive(Serialize, Deserialize, Clone)]
pub enum SubValue {
Scalar(f64),
Node(SubNodeField),
Element(SubElementField),
}
impl SubValue {
pub fn kind(&self) -> ValueKind {
match self {
SubValue::Scalar(_) => ValueKind::Scalar,
SubValue::Node(_) => ValueKind::Node,
SubValue::Element(_) => ValueKind::Element,
}
}
}
pub trait Abscissa {
fn coordinates(self) -> Vec<f64>;
}
impl Abscissa for f64 {
fn coordinates(self) -> Vec<f64> {
vec![self]
}
}
impl Abscissa for Vec<f64> {
fn coordinates(self) -> Vec<f64> {
self
}
}
impl<const N: usize> Abscissa for [f64; N] {
fn coordinates(self) -> Vec<f64> {
self.to_vec()
}
}
pub const MAX_ABSCISSAS: usize = 4;
struct Weights {
index: [usize; 1 << MAX_ABSCISSAS],
weight: [f64; 1 << MAX_ABSCISSAS],
len: usize,
}
impl Weights {
fn new() -> Self {
Self {
index: [0; 1 << MAX_ABSCISSAS],
weight: [0.0; 1 << MAX_ABSCISSAS],
len: 0,
}
}
fn push(&mut self, index: usize, weight: f64) {
self.index[self.len] = index;
self.weight[self.len] = weight;
self.len += 1;
}
fn iter(&self) -> impl Iterator<Item = (usize, f64)> + '_ {
self.index[..self.len]
.iter()
.copied()
.zip(self.weight[..self.len].iter().copied())
}
}
fn blend(values: &[SubValue], weights: &Weights) -> Result<SubValue> {
let mut acc: Option<SubValue> = None;
for (i, w) in weights.iter() {
let term = match &values[i] {
SubValue::Scalar(v) => SubValue::Scalar(v * w),
SubValue::Node(f) => SubValue::Node(f.map_all(|v| v * w)),
SubValue::Element(f) => SubValue::Element(f.map_all(|v| v * w)),
};
acc = Some(match (acc, term) {
(None, t) => t,
(Some(SubValue::Scalar(a)), SubValue::Scalar(b)) => SubValue::Scalar(a + b),
(Some(SubValue::Node(a)), SubValue::Node(b)) => {
a.check_same_components(&b)?;
SubValue::Node(a.merge_components(&b, |x, y| x + y)?)
}
(Some(SubValue::Element(a)), SubValue::Element(b)) => {
a.check_same_components(&b)?;
SubValue::Element(a.merge_components(&b, |x, y| x + y)?)
}
_ => {
return Err(PyrucastError::Message(
"evolution: cannot interpolate between values of different kinds".into(),
))
}
});
}
Ok(acc.expect("a query weighs in at least one sample"))
}
#[derive(Serialize, Deserialize, Clone)]
pub struct SubEvolution {
abscissas: Vec<f64>,
dims: usize,
values: Vec<SubValue>,
out_of_range: OutOfRange,
abscissa_type: Vec<String>,
ordinate_type: Option<String>,
}
impl SubEvolution {
pub fn new<A: Abscissa>(samples: Vec<(A, SubValue)>, out_of_range: OutOfRange) -> Result<Self> {
if samples.is_empty() {
return Err(PyrucastError::Message(
"SubEvolution requires at least one sample".into(),
));
}
let mut samples: Vec<(Vec<f64>, SubValue)> = samples
.into_iter()
.map(|(x, v)| (x.coordinates(), v))
.collect();
let dims = samples[0].0.len();
if dims == 0 || dims > MAX_ABSCISSAS {
return Err(PyrucastError::Message(format!(
"SubEvolution: an abscissa has between 1 and {MAX_ABSCISSAS} variables, \
not {dims}"
)));
}
for (x, _) in &samples {
if x.len() != dims {
return Err(PyrucastError::Message(format!(
"SubEvolution: every abscissa must have {dims} variable(s) like the first, \
one has {}",
x.len()
)));
}
if x.iter().any(|c| c.is_nan()) {
return Err(PyrucastError::Message("SubEvolution: NaN abscissa".into()));
}
}
samples.sort_by(|a, b| {
a.0.iter()
.zip(&b.0)
.map(|(x, y)| x.partial_cmp(y).expect("non-NaN abscissas"))
.find(|o| o.is_ne())
.unwrap_or(std::cmp::Ordering::Equal)
});
for w in samples.windows(2) {
if w[0].0 == w[1].0 {
return Err(PyrucastError::Message(format!(
"SubEvolution: duplicate abscissa {:?}",
w[0].0
)));
}
}
let kind = samples[0].1.kind();
for (_, v) in &samples[1..] {
if v.kind() != kind {
return Err(PyrucastError::Message(format!(
"SubEvolution: mixed value kinds ({} and {})",
kind.label(),
v.kind().label()
)));
}
}
let (abscissas, values): (Vec<Vec<f64>>, Vec<SubValue>) = samples.into_iter().unzip();
check_same_support(&values)?;
Ok(SubEvolution {
abscissas: abscissas.concat(),
dims,
values,
out_of_range,
abscissa_type: Vec::new(),
ordinate_type: None,
})
}
pub fn abscissa_types(&self) -> &[String] {
&self.abscissa_type
}
pub fn dims(&self) -> usize {
self.dims
}
pub fn ordinate_type(&self) -> Option<&str> {
self.ordinate_type.as_deref()
}
pub fn set_abscissa_types(&mut self, types: Vec<String>) -> Result<()> {
if !types.is_empty() && types.len() != self.dims {
return Err(PyrucastError::Message(format!(
"abscissa types: {} given for an abscissa of {} variable(s) — one per variable",
types.len(),
self.dims
)));
}
self.abscissa_type = types;
Ok(())
}
pub fn set_ordinate_type(&mut self, t: Option<String>) -> Result<()> {
if t.is_some() && self.kind() != ValueKind::Scalar {
return Err(PyrucastError::Message(format!(
"ordinate type applies to scalar evolutions only (this one is {})",
self.kind().label()
)));
}
self.ordinate_type = t;
Ok(())
}
pub fn with_abscissa_types(mut self, types: Vec<String>) -> Result<Self> {
self.set_abscissa_types(types)?;
Ok(self)
}
pub fn with_ordinate_type(mut self, t: Option<String>) -> Result<Self> {
self.set_ordinate_type(t)?;
Ok(self)
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
pub fn abscissas(&self) -> &[f64] {
&self.abscissas
}
pub fn kind(&self) -> ValueKind {
self.values[0].kind()
}
pub fn out_of_range(&self) -> OutOfRange {
self.out_of_range
}
pub fn scalar_series(&self) -> Result<Vec<(f64, f64)>> {
if self.kind() != ValueKind::Scalar {
return Err(PyrucastError::Message(
"scalar_series: this evolution carries fields, not scalars".into(),
));
}
if self.dims != 1 {
return Err(PyrucastError::Message(format!(
"scalar_series: a table of {} variables is not an X-Y curve",
self.dims
)));
}
Ok(self
.abscissas
.iter()
.zip(&self.values)
.map(|(x, v)| match v {
SubValue::Scalar(s) => (*x, *s),
_ => unreachable!("kind checked above"),
})
.collect())
}
pub fn value_at(&self, k: usize) -> Result<SubValue> {
self.values.get(k).cloned().ok_or_else(|| {
PyrucastError::Message(format!(
"SubEvolution: frame {} out of range (len={})",
k,
self.values.len()
))
})
}
#[cfg(feature = "viz")]
#[allow(clippy::too_many_arguments)]
pub fn plot(
&self,
view: crate::viz::View,
save: Option<&std::path::Path>,
mesh: Option<&crate::containers::mesh::Mesh>,
component: Option<&str>,
scale: crate::viz::ColorScale,
smooth: usize,
frame: Option<usize>,
x_label: Option<&str>,
y_label: Option<&str>,
title: Option<&str>,
) -> Result<()> {
let evo = Evolution {
subs: vec![Handle::new(self.clone())],
out_of_range: self.out_of_range,
};
evo.plot(
view, save, mesh, component, scale, smooth, frame, x_label, y_label, title,
)
}
pub fn interpolate(&self, x: f64, policy: Option<OutOfRange>) -> Result<SubValue> {
self.interpolate_at(&[x], policy)
}
pub fn interpolate_at(&self, x: &[f64], policy: Option<OutOfRange>) -> Result<SubValue> {
self.check_arity(x)?;
let weights = self.weights(x, policy.unwrap_or(self.out_of_range))?;
blend(&self.values, &weights)
}
fn check_arity(&self, x: &[f64]) -> Result<()> {
if x.len() != self.dims {
return Err(PyrucastError::Message(format!(
"evolution: this {} takes {} variable(s), {} given",
if self.dims == 1 { "curve" } else { "table" },
self.dims,
x.len()
)));
}
Ok(())
}
fn weights(&self, x: &[f64], policy: OutOfRange) -> Result<Weights> {
let mut out = Weights::new();
self.gather(0, 0, self.values.len(), x, policy, 1.0, &mut out)?;
Ok(out)
}
fn coordinate(&self, i: usize, level: usize) -> f64 {
self.abscissas[i * self.dims + level]
}
fn partition(&self, level: usize, lo: usize, hi: usize, keep: impl Fn(f64) -> bool) -> usize {
let (mut lo, mut hi) = (lo, hi);
while lo < hi {
let mid = lo + (hi - lo) / 2;
if keep(self.coordinate(mid, level)) {
lo = mid + 1;
} else {
hi = mid;
}
}
lo
}
#[allow(clippy::too_many_arguments)]
fn gather(
&self,
level: usize,
s: usize,
e: usize,
x: &[f64],
policy: OutOfRange,
w: f64,
out: &mut Weights,
) -> Result<()> {
let at = |i: usize| self.coordinate(i, level);
let group_end = |i: usize| self.partition(level, i, e, |v| v <= at(i));
let group_start = |i: usize| self.partition(level, s, i, |v| v < at(i));
let first = (s, group_end(s));
let last = (group_start(e - 1), e);
let xl = x[level];
if first.1 == e && level > 0 {
return self.descend(level, first, x, policy, w, out);
}
let k = self.partition(level, s, e, |v| v < xl);
let (lo, hi, t) = if k < e && at(k) == xl {
return self.descend(level, (k, group_end(k)), x, policy, w, out);
} else if k == s || k == e {
let below = k == s;
match policy {
OutOfRange::Error => {
return Err(PyrucastError::Message(format!(
"evolution: abscissa {xl}{} is outside the tabulated range [{}, {}]",
match self.abscissa_type.get(level) {
Some(name) if self.dims > 1 => format!(" ({name})"),
_ => String::new(),
},
at(s),
at(e - 1)
)))
}
OutOfRange::Clamp => {
let g = if below { first } else { last };
return self.descend(level, g, x, policy, w, out);
}
OutOfRange::Extrapolate => {
if first.1 == e {
return self.descend(level, first, x, policy, w, out);
}
let (a, b) = if below {
(first, (first.1, group_end(first.1)))
} else {
((group_start(last.0 - 1), last.0), last)
};
(a, b, (xl - at(a.0)) / (at(b.0) - at(a.0)))
}
}
} else {
let lo = (group_start(k - 1), k);
let hi = (k, group_end(k));
(lo, hi, (xl - at(lo.0)) / (at(hi.0) - at(lo.0)))
};
self.descend(level, lo, x, policy, w * (1.0 - t), out)?;
self.descend(level, hi, x, policy, w * t, out)
}
fn descend(
&self,
level: usize,
g: (usize, usize),
x: &[f64],
policy: OutOfRange,
w: f64,
out: &mut Weights,
) -> Result<()> {
if level + 1 == self.dims {
out.push(g.0, w);
Ok(())
} else {
self.gather(level + 1, g.0, g.1, x, policy, w, out)
}
}
pub fn eval_scalar(&self, x: f64, policy: Option<OutOfRange>) -> Result<f64> {
self.eval_scalar_at(&[x], policy)
}
pub fn eval_scalar_at(&self, x: &[f64], policy: Option<OutOfRange>) -> Result<f64> {
if self.kind() != ValueKind::Scalar {
return Err(PyrucastError::Message(
"evolution: a field can only be mapped through a scalar-valued evolution".into(),
));
}
self.check_arity(x)?;
self.scalar_at(x, policy.unwrap_or(self.out_of_range))
}
fn scalar_at(&self, x: &[f64], policy: OutOfRange) -> Result<f64> {
let weights = self.weights(x, policy)?;
Ok(weights
.iter()
.map(|(i, w)| match self.values[i] {
SubValue::Scalar(v) => v * w,
_ => unreachable!("a scalar curve, checked by the caller"),
})
.sum())
}
pub fn interpolate_field<F>(&self, field: &F, policy: Option<OutOfRange>) -> Result<F>
where
F: SubField + Clone,
{
map_through(std::slice::from_ref(self), field, policy)
}
}
fn map_through<F>(curves: &[SubEvolution], field: &F, policy: Option<OutOfRange>) -> Result<F>
where
F: SubField + Clone,
{
let mut names: Vec<String> = Vec::with_capacity(curves.len());
let mut reads: Vec<(Vec<usize>, OutOfRange)> = Vec::with_capacity(curves.len());
for curve in curves {
if curve.kind() != ValueKind::Scalar {
return Err(PyrucastError::Message(
"evolution: a field can only be mapped through a scalar-valued evolution".into(),
));
}
if curve.abscissa_type.is_empty() {
return Err(PyrucastError::Message(
"evolution: set the abscissa type to map a field \
(it selects which field component to look up)"
.into(),
));
}
let mut idx = Vec::with_capacity(curve.dims);
for name in &curve.abscissa_type {
idx.push(field.component_index(name).ok_or_else(|| {
PyrucastError::Message(format!(
"evolution: the field has no component '{name}' matching the abscissa type"
))
})?);
}
let name = curve
.ordinate_type
.clone()
.unwrap_or_else(|| "value".to_string());
if names.contains(&name) {
return Err(PyrucastError::Message(format!(
"evolution: two curves produce the component '{name}' — give each its own \
ordinate type"
)));
}
names.push(name);
reads.push((idx, policy.unwrap_or(curve.out_of_range)));
}
let nc = field.component_count();
let k = curves.len();
let mut out = field.same_support_with(names)?;
field
.values()
.par_chunks(nc)
.zip(out.values_mut().par_chunks_mut(k))
.with_min_len((MIN_PARALLEL_LEN / nc.max(1)).max(1))
.try_for_each(|(row, slot)| -> Result<()> {
let mut x = [0.0_f64; MAX_ABSCISSAS];
for (j, (curve, (idx, policy))) in curves.iter().zip(&reads).enumerate() {
for (v, &i) in idx.iter().enumerate() {
x[v] = row[i];
}
slot[j] = curve.scalar_at(&x[..idx.len()], *policy)?;
}
Ok(())
})?;
Ok(out)
}
fn check_same_support(samples: &[SubValue]) -> Result<()> {
match &samples[0] {
SubValue::Scalar(_) => Ok(()),
SubValue::Node(f0) => {
for v in &samples[1..] {
if let SubValue::Node(f) = v
&& (!f.same_support(f0) || f.component_count() != f0.component_count())
{
return Err(PyrucastError::Message(
"SubEvolution: node values must share the same support and components"
.into(),
));
}
}
Ok(())
}
SubValue::Element(f0) => {
for v in &samples[1..] {
if let SubValue::Element(f) = v
&& (!f.same_support(f0) || f.component_count() != f0.component_count())
{
return Err(PyrucastError::Message(
"SubEvolution: element values must share the same support and components"
.into(),
));
}
}
Ok(())
}
}
}
impl fmt::Debug for SubEvolution {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SubEvolution")
.field("samples", &self.values.len())
.field("dims", &self.dims)
.field("kind", &self.kind().label())
.field("out_of_range", &self.out_of_range.name())
.finish()
}
}
impl fmt::Display for SubEvolution {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"SubEvolution: {} sample(s), {} value(s), out_of_range={}",
self.values.len(),
self.kind().label(),
self.out_of_range.name()
)
}
}
impl crate::dump::Dump for SubEvolution {
fn render(&self, opts: &crate::dump::DumpOptions) -> String {
use crate::dump::{fmt_float, table};
let headers = vec!["abscissa".to_string(), "value".to_string()];
let rows: Vec<Vec<String>> = self
.abscissas
.chunks(self.dims)
.zip(&self.values)
.map(|(x, v)| {
let cell = match v {
SubValue::Scalar(s) => fmt_float(*s, opts.precision),
SubValue::Node(f) => {
format!("SubNodeField({} node(s))", f.node_count())
}
SubValue::Element(f) => format!("SubElementField({} cell(s))", f.cell_count()),
};
let abscissa = match x {
[one] => fmt_float(*one, opts.precision),
tuple => format!(
"({})",
tuple
.iter()
.map(|c| fmt_float(*c, opts.precision))
.collect::<Vec<_>>()
.join(", ")
),
};
vec![abscissa, cell]
})
.collect();
format!("{self}\n{}", table(&headers, &rows, opts))
}
}
#[derive(Serialize, Deserialize, Default)]
pub struct Evolution {
subs: Vec<Handle<SubEvolution>>,
out_of_range: OutOfRange,
}
crate::impl_aggregate!(
Evolution,
SubEvolution,
sub_evolution,
"sub-evolution(s)",
{
fn check_push(&self, h: &Handle<SubEvolution>) -> Result<()> {
if self.subs.is_empty() {
return Ok(());
}
let k0 = self.subs[0].read().kind();
let k = h.read().kind();
if k != k0 {
return Err(PyrucastError::Message(format!(
"Evolution: cannot mix {} and {} sub-evolutions",
k0.label(),
k.label()
)));
}
Ok(())
}
}
);
crate::impl_aggregate_dump!(Evolution);
pub enum Interpolated {
Scalars(Vec<f64>),
Node(NodeField),
Element(ElementField),
}
impl Evolution {
pub fn out_of_range(&self) -> OutOfRange {
self.out_of_range
}
pub fn interpolate(&self, x: f64, policy: Option<OutOfRange>) -> Result<Interpolated> {
self.interpolate_at(&[x], policy)
}
pub fn interpolate_at(&self, x: &[f64], policy: Option<OutOfRange>) -> Result<Interpolated> {
if self.subs.is_empty() {
return Err(PyrucastError::Message(
"Evolution: cannot interpolate an empty evolution".into(),
));
}
let policy = Some(policy.unwrap_or(self.out_of_range));
match self.subs[0].read().kind() {
ValueKind::Scalar => {
let mut out = Vec::with_capacity(self.subs.len());
for h in &self.subs {
match h.read().interpolate_at(x, policy)? {
SubValue::Scalar(v) => out.push(v),
_ => return Err(mixed_kind_err()),
}
}
Ok(Interpolated::Scalars(out))
}
ValueKind::Node => {
let mut field = NodeField::default();
for h in &self.subs {
match h.read().interpolate_at(x, policy)? {
SubValue::Node(sf) => field.add_sub(Handle::new(sf))?,
_ => return Err(mixed_kind_err()),
}
}
Ok(Interpolated::Node(field))
}
ValueKind::Element => {
let mut field = ElementField::default();
for h in &self.subs {
match h.read().interpolate_at(x, policy)? {
SubValue::Element(sf) => field.add_sub(Handle::new(sf))?,
_ => return Err(mixed_kind_err()),
}
}
Ok(Interpolated::Element(field))
}
}
}
pub fn abscissa_types(&self) -> Vec<String> {
match self.subs.first() {
Some(h) => h.read().abscissa_types().to_vec(),
None => Vec::new(),
}
}
pub fn ordinate_type(&self) -> Result<Option<String>> {
match self.subs.first() {
Some(h) => Ok(h.read().ordinate_type().map(str::to_string)),
None => Ok(None),
}
}
pub fn set_abscissa_types(&mut self, types: Vec<String>) -> Result<()> {
for h in &self.subs {
h.write().set_abscissa_types(types.clone())?;
}
Ok(())
}
pub fn set_ordinate_type(&mut self, t: Option<String>) -> Result<()> {
for h in &self.subs {
h.write().set_ordinate_type(t.clone())?;
}
Ok(())
}
fn scalar_curves(&self) -> Result<Vec<SubEvolution>> {
if self.subs.is_empty() {
return Err(PyrucastError::Message(
"evolution: an empty evolution maps no field".into(),
));
}
self.subs
.iter()
.map(|h| {
let sub = h.read();
if sub.kind() != ValueKind::Scalar {
return Err(PyrucastError::Message(
"evolution: a field can only be mapped through a scalar-valued evolution"
.into(),
));
}
Ok((*sub).clone())
})
.collect()
}
pub fn interpolate_node_field(
&self,
field: &NodeField,
policy: Option<OutOfRange>,
) -> Result<NodeField> {
let curves = self.scalar_curves()?;
let policy = Some(policy.unwrap_or(self.out_of_range));
field.map_subs(move |s| map_through(&curves, s, policy))
}
pub fn interpolate_element_field(
&self,
field: &ElementField,
policy: Option<OutOfRange>,
) -> Result<ElementField> {
let curves = self.scalar_curves()?;
let policy = Some(policy.unwrap_or(self.out_of_range));
field.map_subs(move |s| map_through(&curves, s, policy))
}
pub fn kind(&self) -> Result<ValueKind> {
if self.subs.is_empty() {
return Err(PyrucastError::Message("Evolution: empty evolution".into()));
}
Ok(self.subs[0].read().kind())
}
pub fn shared_abscissas(&self) -> Result<Vec<f64>> {
if self.subs.is_empty() {
return Err(PyrucastError::Message("Evolution: empty evolution".into()));
}
if self.subs.iter().any(|h| h.read().dims() != 1) {
return Err(PyrucastError::Message(
"Evolution: a table of several variables has no frame sequence".into(),
));
}
let first = self.subs[0].read().abscissas().to_vec();
for h in &self.subs[1..] {
if h.read().abscissas() != first.as_slice() {
return Err(PyrucastError::Message(
"Evolution: sub-evolutions have different abscissa grids — \
a frame index is ambiguous"
.into(),
));
}
}
Ok(first)
}
pub fn frame_count(&self) -> Result<usize> {
Ok(self.shared_abscissas()?.len())
}
pub fn node_frame(&self, k: usize) -> Result<NodeField> {
let mut field = NodeField::default();
for h in &self.subs {
match h.read().value_at(k)? {
SubValue::Node(sf) => field.add_sub(Handle::new(sf))?,
_ => return Err(not_node_err()),
}
}
Ok(field)
}
pub fn element_frame(&self, k: usize) -> Result<ElementField> {
let mut field = ElementField::default();
for h in &self.subs {
match h.read().value_at(k)? {
SubValue::Element(sf) => field.add_sub(Handle::new(sf))?,
_ => return Err(not_element_err()),
}
}
Ok(field)
}
pub fn scalar_series_set(&self) -> Result<ScalarSeriesSet> {
let mut out = Vec::with_capacity(self.subs.len());
for (i, h) in self.subs.iter().enumerate() {
let label = if self.subs.len() == 1 {
"value".to_string()
} else {
format!("zone {i}")
};
out.push((label, h.read().scalar_series()?));
}
Ok(out)
}
#[cfg(feature = "viz")]
#[allow(clippy::too_many_arguments)]
pub fn plot(
&self,
view: crate::viz::View,
save: Option<&std::path::Path>,
mesh: Option<&crate::containers::mesh::Mesh>,
component: Option<&str>,
scale: crate::viz::ColorScale,
smooth: usize,
frame: Option<usize>,
x_label: Option<&str>,
y_label: Option<&str>,
title: Option<&str>,
) -> Result<()> {
let abscissa_label = match x_label {
Some(s) => s.to_string(),
None => self
.abscissa_types()
.first()
.cloned()
.unwrap_or_else(|| "variable".into()),
};
match self.kind()? {
ValueKind::Scalar => {
let y = match y_label {
Some(s) => s.to_string(),
None => self.ordinate_type()?.unwrap_or_else(|| "value".into()),
};
crate::viz::render_curve(
self.scalar_series_set()?,
&abscissa_label,
&y,
title.unwrap_or(""),
view,
save,
)
}
ValueKind::Node => {
let abscissas = self.shared_abscissas()?;
let frames: Vec<crate::viz::FrameField> = (0..abscissas.len())
.map(|k| Ok(crate::viz::FrameField::Node(self.node_frame(k)?)))
.collect::<Result<_>>()?;
crate::viz::render_evolution_field(
mesh,
&frames,
&abscissas,
&abscissa_label,
component,
scale,
smooth,
frame,
view,
save,
title,
)
}
ValueKind::Element => {
let abscissas = self.shared_abscissas()?;
let frames: Vec<crate::viz::FrameField> = (0..abscissas.len())
.map(|k| Ok(crate::viz::FrameField::Element(self.element_frame(k)?)))
.collect::<Result<_>>()?;
let reconstructed = match (mesh, frames.first()) {
(None, Some(crate::viz::FrameField::Element(ef))) => {
Some(element_support_mesh(ef)?)
}
_ => None,
};
let geom = mesh.or(reconstructed.as_ref());
crate::viz::render_evolution_field(
geom,
&frames,
&abscissas,
&abscissa_label,
component,
scale,
smooth,
frame,
view,
save,
title,
)
}
}
}
pub fn from_scalars<A: Abscissa>(
samples: Vec<(A, f64)>,
out_of_range: OutOfRange,
) -> Result<Self> {
let pairs = samples
.into_iter()
.map(|(x, v)| (x, SubValue::Scalar(v)))
.collect();
let sub = SubEvolution::new(pairs, out_of_range)?;
Ok(Evolution {
subs: vec![Handle::new(sub)],
out_of_range,
})
}
pub fn from_node_fields<A: Abscissa + Clone>(
samples: &[(A, &NodeField)],
out_of_range: OutOfRange,
) -> Result<Self> {
if samples.is_empty() {
return Err(PyrucastError::Message(
"Evolution::from_node_fields: no sample".into(),
));
}
let first = samples[0].1;
if first.is_empty() {
return Err(PyrucastError::Message(
"Evolution::from_node_fields: the first field has no zone".into(),
));
}
let mut evolution = Evolution {
subs: Vec::with_capacity(first.len()),
out_of_range,
};
for z in 0..first.len() {
let support = first.get(z)?.read().support();
let mut curve = Vec::with_capacity(samples.len());
for (x, field) in samples {
curve.push((x.clone(), SubValue::Node(node_sub_on(field, &support)?)));
}
evolution
.subs
.push(Handle::new(SubEvolution::new(curve, out_of_range)?));
}
Ok(evolution)
}
pub fn from_element_fields<A: Abscissa + Clone>(
samples: &[(A, &ElementField)],
out_of_range: OutOfRange,
) -> Result<Self> {
if samples.is_empty() {
return Err(PyrucastError::Message(
"Evolution::from_element_fields: no sample".into(),
));
}
let first = samples[0].1;
if first.is_empty() {
return Err(PyrucastError::Message(
"Evolution::from_element_fields: the first field has no zone".into(),
));
}
let mut evolution = Evolution {
subs: Vec::with_capacity(first.len()),
out_of_range,
};
for z in 0..first.len() {
let support = first.get(z)?.read().support();
let mut curve = Vec::with_capacity(samples.len());
for (x, field) in samples {
curve.push((
x.clone(),
SubValue::Element(element_sub_on(field, &support)?),
));
}
evolution
.subs
.push(Handle::new(SubEvolution::new(curve, out_of_range)?));
}
Ok(evolution)
}
}
fn mixed_kind_err() -> PyrucastError {
PyrucastError::Message("Evolution: inconsistent value kinds across sub-evolutions".into())
}
fn not_node_err() -> PyrucastError {
PyrucastError::Message("Evolution: expected node-field values".into())
}
fn not_element_err() -> PyrucastError {
PyrucastError::Message("Evolution: expected element-field values".into())
}
#[cfg(feature = "viz")]
fn element_support_mesh(field: &ElementField) -> Result<crate::containers::mesh::Mesh> {
use crate::containers::field::SubField;
let mut mesh = crate::containers::mesh::Mesh::empty();
for h in field.iter() {
let sub = h.read();
let fes = sub.support().read();
mesh.add_sub(fes.submesh())?;
}
Ok(mesh)
}
fn node_sub_on(field: &NodeField, support: &Handle<SubMesh>) -> Result<SubNodeField> {
for h in field.iter() {
let s = h.read();
if s.support().same_object(support) {
return Ok((*s).clone());
}
}
Err(PyrucastError::Message(
"Evolution::from_node_fields: a step is missing a zone present in the first step".into(),
))
}
fn element_sub_on(
field: &ElementField,
support: &Handle<SubFiniteElementSpace>,
) -> Result<SubElementField> {
for h in field.iter() {
let s = h.read();
if s.support().same_object(support) {
return Ok((*s).clone());
}
}
Err(PyrucastError::Message(
"Evolution::from_element_fields: a step is missing a zone present in the first step".into(),
))
}
impl crate::archive::Archivable for SubEvolution {
const TAG: &'static str = "SubEvolution";
}
impl crate::archive::Archivable for Evolution {
const TAG: &'static str = "Evolution";
}
#[cfg(test)]
mod tests {
use super::*;
use crate::atoms::{ElementType, Node};
use crate::containers::mesh::SubMesh;
use crate::coords::Coords;
use crate::handle::Handle;
fn scalar_curve(samples: &[(f64, f64)], oor: OutOfRange) -> SubEvolution {
SubEvolution::new(
samples
.iter()
.map(|&(x, v)| (x, SubValue::Scalar(v)))
.collect(),
oor,
)
.unwrap()
}
fn poi1(n: usize) -> Handle<SubMesh> {
let coords = Handle::new(Coords::new(1).unwrap());
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
for i in 0..n {
let nd = Node::create_in(coords.clone(), &[i as f64]).unwrap();
sm.add_cell(&[nd.id()]).unwrap();
}
Handle::new(sm)
}
fn node_field(sm: &Handle<SubMesh>, vals: &[f64]) -> SubNodeField {
let mut f = SubNodeField::from_poi1(sm, vec!["T".into()]).unwrap();
for (i, &v) in vals.iter().enumerate() {
f.set(i, 0, v).unwrap();
}
f
}
fn as_scalar(v: SubValue) -> f64 {
match v {
SubValue::Scalar(s) => s,
_ => panic!("expected a scalar"),
}
}
#[test]
fn scalar_interpolation_midpoint_and_exact() {
let se = scalar_curve(&[(0.0, 10.0), (1.0, 20.0)], OutOfRange::Error);
assert_eq!(as_scalar(se.interpolate(0.5, None).unwrap()), 15.0);
assert_eq!(as_scalar(se.interpolate(0.0, None).unwrap()), 10.0);
assert_eq!(as_scalar(se.interpolate(1.0, None).unwrap()), 20.0);
assert_eq!(as_scalar(se.interpolate(0.25, None).unwrap()), 12.5);
}
#[test]
fn samples_are_sorted_and_duplicates_rejected() {
let se = scalar_curve(&[(2.0, 30.0), (0.0, 10.0), (1.0, 20.0)], OutOfRange::Error);
assert_eq!(se.abscissas(), &[0.0, 1.0, 2.0]);
assert_eq!(as_scalar(se.interpolate(1.5, None).unwrap()), 25.0);
assert!(SubEvolution::new(
vec![(0.0, SubValue::Scalar(1.0)), (0.0, SubValue::Scalar(2.0))],
OutOfRange::Error
)
.is_err());
}
#[test]
fn out_of_range_policies() {
let se = scalar_curve(&[(0.0, 10.0), (1.0, 20.0)], OutOfRange::Error);
assert!(se.interpolate(2.0, None).is_err());
assert!(se.interpolate(-1.0, None).is_err());
assert_eq!(
as_scalar(se.interpolate(2.0, Some(OutOfRange::Clamp)).unwrap()),
20.0
);
assert_eq!(
as_scalar(se.interpolate(-1.0, Some(OutOfRange::Clamp)).unwrap()),
10.0
);
assert_eq!(
as_scalar(se.interpolate(2.0, Some(OutOfRange::Extrapolate)).unwrap()),
30.0
);
assert_eq!(
as_scalar(se.interpolate(-1.0, Some(OutOfRange::Extrapolate)).unwrap()),
0.0
);
}
#[test]
fn stored_policy_used_and_overridable() {
let se = scalar_curve(&[(0.0, 10.0), (1.0, 20.0)], OutOfRange::Clamp);
assert_eq!(as_scalar(se.interpolate(2.0, None).unwrap()), 20.0);
assert!(se.interpolate(2.0, Some(OutOfRange::Error)).is_err());
}
#[test]
fn node_field_interpolation_blends_per_node() {
let sm = poi1(2);
let a = node_field(&sm, &[0.0, 10.0]);
let b = node_field(&sm, &[2.0, 20.0]);
let se = SubEvolution::new(
vec![(0.0, SubValue::Node(a)), (1.0, SubValue::Node(b))],
OutOfRange::Error,
)
.unwrap();
match se.interpolate(0.5, None).unwrap() {
SubValue::Node(f) => {
assert_eq!(f.get(0, 0).unwrap(), 1.0); assert_eq!(f.get(1, 0).unwrap(), 15.0); }
_ => panic!("expected a node value"),
}
}
#[test]
fn node_values_on_different_supports_rejected() {
let a = node_field(&poi1(2), &[0.0, 0.0]);
let b = node_field(&poi1(2), &[1.0, 1.0]); assert!(SubEvolution::new(
vec![(0.0, SubValue::Node(a)), (1.0, SubValue::Node(b))],
OutOfRange::Error
)
.is_err());
}
#[test]
fn aggregate_scalar_interpolation_returns_list() {
let e = Evolution::from_scalars(vec![(0.0, 10.0), (1.0, 20.0)], OutOfRange::Error).unwrap();
match e.interpolate(0.5, None).unwrap() {
Interpolated::Scalars(v) => assert_eq!(v, vec![15.0]),
_ => panic!("expected scalars"),
}
}
#[test]
fn aggregate_rejects_mixed_kinds() {
let scalar = Handle::new(scalar_curve(&[(0.0, 1.0)], OutOfRange::Error));
let node = Handle::new(
SubEvolution::new(
vec![(0.0, SubValue::Node(node_field(&poi1(1), &[1.0])))],
OutOfRange::Error,
)
.unwrap(),
);
let mut e = Evolution::default();
e.add_sub(scalar).unwrap();
assert!(e.add_sub(node).is_err());
}
#[test]
fn union_collects_sub_evolutions() {
let e0 = Evolution::from_scalars(vec![(0.0, 1.0), (1.0, 2.0)], OutOfRange::Error).unwrap();
let e1 = Evolution::from_scalars(vec![(0.0, 3.0), (1.0, 4.0)], OutOfRange::Error).unwrap();
let u = e0.union(&e1).unwrap();
assert_eq!(u.len(), 2);
match u.interpolate(0.5, None).unwrap() {
Interpolated::Scalars(v) => assert_eq!(v, vec![1.5, 3.5]),
_ => panic!("expected scalars"),
}
}
#[test]
fn scalar_series_set_labels_zones() {
let e0 = Evolution::from_scalars(vec![(0.0, 1.0), (1.0, 2.0)], OutOfRange::Error).unwrap();
let series = e0.scalar_series_set().unwrap();
assert_eq!(series.len(), 1);
assert_eq!(series[0].0, "value");
assert_eq!(series[0].1, vec![(0.0, 1.0), (1.0, 2.0)]);
let e1 = Evolution::from_scalars(vec![(0.0, 3.0), (1.0, 4.0)], OutOfRange::Error).unwrap();
let u = e0.union(&e1).unwrap();
let s = u.scalar_series_set().unwrap();
assert_eq!(s.len(), 2);
assert_eq!(s[0].0, "zone 0");
assert_eq!(s[1].0, "zone 1");
}
#[test]
fn shared_abscissas_validates_grid() {
let sm = poi1(2);
let a = node_field(&sm, &[0.0, 0.0]);
let b = node_field(&sm, &[10.0, 20.0]);
let f0 = NodeField::from_sub(a);
let f1 = NodeField::from_sub(b);
let e = Evolution::from_node_fields(&[(0.0, &f0), (2.0, &f1)], OutOfRange::Error).unwrap();
assert_eq!(e.shared_abscissas().unwrap(), vec![0.0, 2.0]);
assert_eq!(e.frame_count().unwrap(), 2);
let frame = e.node_frame(1).unwrap();
let sub = frame.get(0).unwrap().read();
assert_eq!(sub.get(0, 0).unwrap(), 10.0);
assert_eq!(sub.get(1, 0).unwrap(), 20.0);
}
#[test]
fn from_node_fields_transposes_per_zone() {
let sm = poi1(2);
let f0 = NodeField::from_sub(node_field(&sm, &[0.0, 0.0]));
let f1 = NodeField::from_sub(node_field(&sm, &[10.0, 20.0]));
let e = Evolution::from_node_fields(&[(0.0, &f0), (1.0, &f1)], OutOfRange::Error).unwrap();
assert_eq!(e.len(), 1);
match e.interpolate(0.5, None).unwrap() {
Interpolated::Node(field) => {
let sub = field.get(0).unwrap().read();
assert_eq!(sub.get(0, 0).unwrap(), 5.0);
assert_eq!(sub.get(1, 0).unwrap(), 10.0);
}
_ => panic!("expected a node field"),
}
}
fn typed_curve() -> SubEvolution {
scalar_curve(&[(0.0, 0.0), (10.0, 20.0)], OutOfRange::Error)
.with_abscissa_types(vec!["T".into()])
.unwrap()
.with_ordinate_type(Some("E".into()))
.unwrap()
}
#[test]
fn ordinate_type_rejected_on_field_curve() {
let mut se = SubEvolution::new(
vec![(0.0, SubValue::Node(node_field(&poi1(1), &[1.0])))],
OutOfRange::Error,
)
.unwrap();
assert!(se.set_ordinate_type(Some("E".into())).is_err());
assert!(se.set_ordinate_type(None).is_ok());
}
#[test]
fn interpolate_field_maps_component_pointwise() {
let se = typed_curve();
let sm = poi1(3);
let input = node_field(&sm, &[0.0, 5.0, 10.0]);
let out = se.interpolate_field(&input, None).unwrap();
assert_eq!(out.components(), &["E".to_string()]);
assert_eq!(out.get(0, 0).unwrap(), 0.0); assert_eq!(out.get(1, 0).unwrap(), 10.0); assert_eq!(out.get(2, 0).unwrap(), 20.0); }
#[test]
fn interpolate_field_checks_type_correspondence() {
let se = scalar_curve(&[(0.0, 0.0), (1.0, 1.0)], OutOfRange::Error)
.with_abscissa_types(vec!["P".into()])
.unwrap();
let input = node_field(&poi1(1), &[0.5]);
assert!(se.interpolate_field(&input, None).is_err());
}
#[test]
fn interpolate_field_requires_abscissa_type() {
let se = scalar_curve(&[(0.0, 0.0), (1.0, 1.0)], OutOfRange::Error);
let input = node_field(&poi1(1), &[0.5]);
assert!(se.interpolate_field(&input, None).is_err());
}
#[test]
fn interpolate_field_out_of_range_honours_policy() {
let se = typed_curve(); let input = node_field(&poi1(1), &[15.0]); assert!(se.interpolate_field(&input, None).is_err());
assert_eq!(
se.interpolate_field(&input, Some(OutOfRange::Clamp))
.unwrap()
.get(0, 0)
.unwrap(),
20.0
);
}
#[test]
fn aggregate_interpolate_node_field_end_to_end() {
let mut e =
Evolution::from_scalars(vec![(0.0, 0.0), (10.0, 20.0)], OutOfRange::Error).unwrap();
e.set_abscissa_types(vec!["T".into()]).unwrap();
e.set_ordinate_type(Some("E".into())).unwrap();
let sm = poi1(2);
let input = NodeField::from_sub(node_field(&sm, &[0.0, 10.0]));
let out = e.interpolate_node_field(&input, None).unwrap();
let sub = out.get(0).unwrap().read();
assert_eq!(sub.components(), &["E".to_string()]);
assert_eq!(sub.get(0, 0).unwrap(), 0.0);
assert_eq!(sub.get(1, 0).unwrap(), 20.0);
}
#[test]
fn two_curves_writing_one_component_are_refused() {
let e0 = Evolution::from_scalars(vec![(0.0, 0.0), (1.0, 1.0)], OutOfRange::Error).unwrap();
let e1 = Evolution::from_scalars(vec![(0.0, 0.0), (1.0, 1.0)], OutOfRange::Error).unwrap();
let mut two = e0.union(&e1).unwrap();
two.set_abscissa_types(vec!["T".into()]).unwrap();
let input = NodeField::from_sub(node_field(&poi1(1), &[0.5]));
assert!(two.interpolate_node_field(&input, None).is_err());
}
#[test]
fn curves_of_different_variables_map_one_field() {
let e = scalar_curve(&[(0.0, 1.0), (10.0, 3.0)], OutOfRange::Error)
.with_abscissa_types(vec!["T".into()])
.unwrap()
.with_ordinate_type(Some("E".into()))
.unwrap();
let table = SubEvolution::new(
vec![
([0.0, 0.0], SubValue::Scalar(0.0)),
([0.0, 1.0], SubValue::Scalar(1.0)),
([10.0, 0.0], SubValue::Scalar(10.0)),
([10.0, 1.0], SubValue::Scalar(11.0)),
],
OutOfRange::Error,
)
.unwrap()
.with_abscissa_types(vec!["T".into(), "phi".into()])
.unwrap()
.with_ordinate_type(Some("s".into()))
.unwrap();
let mut laws = Evolution::default();
laws.add_sub(Handle::new(e)).unwrap();
laws.add_sub(Handle::new(table)).unwrap();
let sm = poi1(2);
let mut input = SubNodeField::from_poi1(&sm, vec!["phi".into(), "T".into()]).unwrap();
input.set(0, 0, 0.5).unwrap();
input.set(0, 1, 5.0).unwrap();
input.set(1, 0, 1.0).unwrap();
input.set(1, 1, 10.0).unwrap();
let out = laws
.interpolate_node_field(&NodeField::from_sub(input), None)
.unwrap();
let z = out.get(0).unwrap().read();
assert_eq!(z.components(), &["E".to_string(), "s".to_string()]);
assert!((z.get(0, 0).unwrap() - 2.0).abs() < 1e-12); assert!((z.get(0, 1).unwrap() - 5.5).abs() < 1e-12); assert!((z.get(1, 1).unwrap() - 11.0).abs() < 1e-12);
}
#[test]
fn a_table_reproduces_a_bilinear_function() {
let f = |x: f64, y: f64| 1.0 + 2.0 * x + 3.0 * y + 4.0 * x * y;
let grid: Vec<([f64; 2], SubValue)> = [0.0, 1.0, 3.0]
.iter()
.flat_map(|&x| [0.0, 2.0].map(move |y| ([x, y], SubValue::Scalar(f(x, y)))))
.collect();
let irregular: Vec<([f64; 2], SubValue)> = [
[0.0, 0.0],
[0.0, 0.7],
[0.0, 2.0],
[1.0, 0.0],
[1.0, 2.0],
[3.0, 0.0],
[3.0, 1.2],
[3.0, 1.5],
[3.0, 2.0],
]
.iter()
.rev() .map(|&[x, y]| ([x, y], SubValue::Scalar(f(x, y))))
.collect();
for samples in [grid, irregular] {
let t = SubEvolution::new(samples, OutOfRange::Error).unwrap();
for (x, y) in [(0.3, 0.4), (1.0, 1.9), (2.2, 0.05), (3.0, 2.0), (0.0, 0.0)] {
let got = t.eval_scalar_at(&[x, y], None).unwrap();
assert!((got - f(x, y)).abs() < 1e-12, "f({x}, {y}): {got}");
}
}
}
#[test]
fn a_table_honours_ranges_and_single_values() {
let t = SubEvolution::new(
vec![
([0.0, 0.0], SubValue::Scalar(1.0)),
([0.0, 1.0], SubValue::Scalar(2.0)),
([1.0, 0.5], SubValue::Scalar(7.0)), ],
OutOfRange::Error,
)
.unwrap();
assert_eq!(t.eval_scalar_at(&[1.0, 0.9], None).unwrap(), 7.0);
assert!((t.eval_scalar_at(&[0.5, 0.5], None).unwrap() - 4.25).abs() < 1e-12);
assert!(t.eval_scalar_at(&[0.0, 1.5], None).is_err());
assert_eq!(
t.eval_scalar_at(&[0.0, 1.5], Some(OutOfRange::Clamp))
.unwrap(),
2.0
);
assert!(
(t.eval_scalar_at(&[2.0, 0.5], Some(OutOfRange::Extrapolate))
.unwrap()
- 12.5)
.abs()
< 1e-12
);
assert!(t.eval_scalar_at(&[0.5], None).is_err());
}
#[test]
fn a_table_validates_its_abscissas() {
assert!(SubEvolution::new(
vec![
(vec![0.0, 0.0], SubValue::Scalar(1.0)),
(vec![1.0], SubValue::Scalar(2.0)),
],
OutOfRange::Error,
)
.is_err());
assert!(SubEvolution::new(
vec![
([0.0, 1.0], SubValue::Scalar(1.0)),
([0.0, 1.0], SubValue::Scalar(2.0)),
],
OutOfRange::Error,
)
.is_err());
}
#[test]
fn types_round_trip_on_aggregate() {
let mut e =
Evolution::from_scalars(vec![(0.0, 0.0), (1.0, 1.0)], OutOfRange::Error).unwrap();
e.set_abscissa_types(vec!["time".into()]).unwrap();
e.set_ordinate_type(Some("force".into())).unwrap();
assert_eq!(e.abscissa_types(), ["time"]);
assert_eq!(e.ordinate_type().unwrap().as_deref(), Some("force"));
}
}