use crate::containers::field::MapValues;
use crate::error::Result;
macro_rules! field_unary {
($(#[$doc:meta])* $name:ident, $f:expr) => {
$(#[$doc])*
pub fn $name<T: MapValues>(field: &T) -> Result<T> {
field.map_values($f)
}
};
}
field_unary!(
abs, f64::abs
);
field_unary!(
sqrt, f64::sqrt
);
field_unary!(
exp, f64::exp
);
field_unary!(
log, f64::ln
);
field_unary!(
log10, f64::log10
);
field_unary!(
cos, f64::cos
);
field_unary!(
sin, f64::sin
);
field_unary!(
tan, f64::tan
);
field_unary!(
sinh, f64::sinh
);
field_unary!(
cosh, f64::cosh
);
field_unary!(
tanh, f64::tanh
);
#[cfg(test)]
mod tests {
use super::*;
use crate::atoms::{ElementType, Node, NodeId};
use crate::containers::mesh::SubMesh;
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::coords::Coords;
use crate::store::insert;
fn make_field(values: &[f64]) -> (SubNodeField, Vec<NodeId>) {
let coords = insert(Coords::new(1).unwrap());
let nodes: Vec<Node> = (0..values.len())
.map(|i| Node::create_in(coords.clone(), &[i as f64]).unwrap())
.collect();
let ids: Vec<NodeId> = nodes.iter().map(|n| n.id()).collect();
let sm = {
let mut sm = SubMesh::new(coords, ElementType::POI1);
for n in &nodes {
sm.add_cell(&[n.id()]).unwrap();
}
insert(sm)
};
let mut f = SubNodeField::from_poi1(&sm, vec!["T".into()]).unwrap();
for (i, &v) in values.iter().enumerate() {
f.set(i, 0, v).unwrap();
}
(f, ids)
}
#[test]
fn cos_on_subfield_maps_every_value() {
let (f, ids) = make_field(&[0.0, std::f64::consts::PI]);
let g = cos(&f).unwrap();
assert!((g.value(ids[0], "T").unwrap() - 1.0).abs() < 1e-12);
assert!((g.value(ids[1], "T").unwrap() + 1.0).abs() < 1e-12);
assert_eq!(f.value(ids[0], "T").unwrap(), 0.0);
}
#[test]
fn sqrt_and_exp_and_log() {
let (f, ids) = make_field(&[4.0, 1.0]);
assert!((sqrt(&f).unwrap().value(ids[0], "T").unwrap() - 2.0).abs() < 1e-12);
assert!((exp(&f).unwrap().value(ids[1], "T").unwrap() - std::f64::consts::E).abs() < 1e-12);
assert!(log(&f).unwrap().value(ids[1], "T").unwrap().abs() < 1e-12); }
#[test]
fn unguarded_log_of_negative_is_nan() {
let (f, ids) = make_field(&[-1.0]);
assert!(log(&f).unwrap().value(ids[0], "T").unwrap().is_nan());
}
#[test]
fn works_on_aggregate() {
let (sub, ids) = make_field(&[0.0]);
let agg = NodeField::from_sub(sub);
let g = cos(&agg).unwrap();
assert!((g.value(ids[0], "T").unwrap() - 1.0).abs() < 1e-12);
}
}