use std::collections::HashMap;
use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::element_field::ElementField;
use crate::containers::field::{Field, SubField};
use crate::containers::mesh::Mesh;
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::ops::element_field::fit::CellFit;
use crate::ops::geom::{locate_points, Location};
use crate::parallel::*;
pub fn project_node(field: &NodeField, mesh: &Mesh, target: &Mesh, tol: f64) -> Result<NodeField> {
let components = Field::components(field);
if components.is_empty() || target.is_empty() {
return Ok(NodeField::default());
}
if !mesh.is_empty() {
if !mesh.coords()?.same_object(&field.coords()?) {
return Err(PyrucastError::Message(
"project: `field` and `mesh` hang from different Coords — the cells of \
`mesh` interpolate the field from its own nodes"
.into(),
));
}
same_dimension(mesh, target)?;
}
let (index, points) = distinct_points(target)?;
let locations = locate_points(mesh, &points, tol)?;
let n_comp = components.len();
let view = field.view();
let reads = view.resolve_reads(&components);
let mut values = vec![0.0; points.len() * n_comp];
values
.par_chunks_mut(n_comp)
.zip(locations.par_iter())
.with_min_len(MIN_PARALLEL_LEN)
.for_each_init(Vec::new, |cell, (out, location)| {
if let Some(Location { weights, nodes, .. }) = location {
cell.resize(nodes.len() * n_comp, 0.0);
view.gather_cell(nodes, &reads, cell);
for (k, w) in weights.iter().enumerate() {
for (o, v) in out.iter_mut().zip(&cell[k * n_comp..(k + 1) * n_comp]) {
*o += w * v;
}
}
}
});
on_target(target, &components, &index, &values)
}
pub fn project_element(
field: &ElementField,
mesh: &Mesh,
target: &Mesh,
tol: f64,
) -> Result<NodeField> {
let components = Field::components(field);
if components.is_empty() || target.is_empty() {
return Ok(NodeField::default());
}
if !mesh.is_empty() {
same_dimension(mesh, target)?;
}
struct Host<'v> {
values: &'v [f64],
stride: usize,
n_gauss: usize,
fit: CellFit,
reads: Vec<(usize, usize)>,
}
let view = field.view();
let mut hosts = Vec::with_capacity(mesh.len());
for (s, sm) in mesh.into_iter().enumerate() {
let zone = view.zone_for_submesh(sm).ok_or_else(|| {
PyrucastError::Message(format!(
"project: submesh {s} of `mesh` carries no zone of the field — `mesh` must be \
the cells the field lives on"
))
})?;
let fit = CellFit::for_space(&zone.support().read())?;
let reads = components
.iter()
.enumerate()
.filter_map(|(k, c)| zone.component_index(c).map(|i| (k, i)))
.collect();
hosts.push(Host {
values: zone.values(),
stride: zone.components().len(),
n_gauss: zone.gauss_count(),
fit,
reads,
});
}
let (index, points) = distinct_points(target)?;
let locations = locate_points(mesh, &points, tol)?;
let n_comp = components.len();
let max_gauss = hosts.iter().map(|h| h.n_gauss).max().unwrap_or(0);
let max_nodes = hosts
.iter()
.map(|h| h.fit.nodes_per_cell())
.max()
.unwrap_or(0);
let mut values = vec![0.0; points.len() * n_comp];
values
.par_chunks_mut(n_comp)
.zip(locations.par_iter())
.with_min_len(MIN_PARALLEL_LEN)
.for_each_init(
|| (vec![0.0; max_gauss], vec![0.0; max_nodes]),
|(gauss_buffer, nodal_buffer), (out, location)| {
if let Some(Location {
submesh,
cell,
weights,
..
}) = location
{
let host = &hosts[*submesh];
let gauss = &mut gauss_buffer[..host.n_gauss];
let nodal = &mut nodal_buffer[..host.fit.nodes_per_cell()];
let first = cell * host.n_gauss * host.stride;
for &(k, i) in &host.reads {
for (g, slot) in gauss.iter_mut().enumerate() {
*slot = host.values[first + g * host.stride + i];
}
host.fit.nodal_values_into(gauss, nodal);
out[k] = weights.iter().zip(nodal.iter()).map(|(w, v)| w * v).sum();
}
}
},
);
on_target(target, &components, &index, &values)
}
fn same_dimension(mesh: &Mesh, target: &Mesh) -> Result<()> {
let (dim, target_dim) = (mesh.coords()?.read().dim(), target.coords()?.read().dim());
if dim != target_dim {
return Err(PyrucastError::Message(format!(
"project: `mesh` is {dim}-D and `target` {target_dim}-D"
)));
}
Ok(())
}
#[allow(clippy::type_complexity)]
fn distinct_points(target: &Mesh) -> Result<(HashMap<NodeId, usize>, Vec<Vec<f64>>)> {
let target_coords = target.coords()?;
let mut index: HashMap<NodeId, usize> = HashMap::new();
let mut points: Vec<Vec<f64>> = Vec::new();
let c = target_coords.read();
for sm in target {
for &nid in sm.read().connectivity() {
if let std::collections::hash_map::Entry::Vacant(e) = index.entry(nid) {
e.insert(points.len());
points.push(c.position(nid)?.to_vec());
}
}
}
Ok((index, points))
}
fn on_target(
target: &Mesh,
components: &[String],
index: &HashMap<NodeId, usize>,
values: &[f64],
) -> Result<NodeField> {
let n_comp = components.len();
let mut out = NodeField::default();
for sm in target {
let mut sub = SubNodeField::from_support(sm, components.to_vec())?;
let nodes = sub.node_ids();
for (row, nid) in sub.values_mut().chunks_mut(n_comp).zip(&nodes) {
let at = index[nid] * n_comp;
row.copy_from_slice(&values[at..at + n_comp]);
}
out.add_sub(Handle::new(sub))?;
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::atoms::{ElementType, Node};
use crate::containers::mesh::SubMesh;
use crate::coords::Coords;
use crate::ops::mesh::poi1_from_nodes;
fn square(n: usize) -> (Mesh, Vec<Node>) {
let coords = Handle::new(Coords::new(2).unwrap());
let nodes: Vec<Node> = (0..=n)
.flat_map(|j| (0..=n).map(move |i| (i, j)))
.map(|(i, j)| {
Node::create_in(coords.clone(), &[i as f64 / n as f64, j as f64 / n as f64])
.unwrap()
})
.collect();
let at = |i: usize, j: usize| nodes[j * (n + 1) + i].id();
let mut sm = SubMesh::new(coords, ElementType::QUA4);
for j in 0..n {
for i in 0..n {
sm.add_cell(&[at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)])
.unwrap();
}
}
(Mesh::from_submesh(sm), nodes)
}
fn sampled(mesh: &Mesh, nodes: &[Node], f: impl Fn(f64, f64) -> f64) -> NodeField {
let field = NodeField::new(mesh, vec!["a".into(), "b".into()]).unwrap();
{
let mut z = field.get(0).unwrap().write();
for n in nodes {
let p = n.position().unwrap();
z.set_value(n.id(), "a", f(p[0], p[1])).unwrap();
z.set_value(n.id(), "b", -f(p[0], p[1])).unwrap();
}
}
field
}
fn points(at: &[[f64; 2]]) -> (Mesh, Vec<Node>) {
let coords = Handle::new(Coords::new(2).unwrap());
let nodes: Vec<Node> = at
.iter()
.map(|p| Node::create_in(coords.clone(), p).unwrap())
.collect();
(poi1_from_nodes(&nodes).unwrap(), nodes)
}
#[test]
fn a_linear_field_comes_back_exactly() {
let (mesh, nodes) = square(3);
let f = |x: f64, y: f64| 2.0 + 3.0 * x - 5.0 * y;
let field = sampled(&mesh, &nodes, f);
let at = [[0.1, 0.2], [0.5, 0.5], [0.97, 0.33], [1.0, 1.0], [1.5, 0.5]];
let (target, targets) = points(&at);
let carried = project_node(&field, &mesh, &target, 1e-6).unwrap();
let z = carried.get(0).unwrap().read();
for (node, p) in targets.iter().zip(&at[..4]) {
assert!((z.value(node.id(), "a").unwrap() - f(p[0], p[1])).abs() < 1e-12);
assert!((z.value(node.id(), "b").unwrap() + f(p[0], p[1])).abs() < 1e-12);
}
assert_eq!(z.value(targets[4].id(), "a").unwrap(), 0.0);
}
#[test]
fn quadratic_cells_interpolate_quadratically() {
let coords = Handle::new(Coords::new(2).unwrap());
let corners = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.0]];
let mids = [[1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
let nodes: Vec<Node> = corners
.iter()
.chain(&mids)
.map(|p| Node::create_in(coords.clone(), p).unwrap())
.collect();
let mut sm = SubMesh::new(coords, ElementType::TRI6);
let ids: Vec<NodeId> = nodes.iter().map(Node::id).collect();
sm.add_cell(&ids).unwrap();
let mesh = Mesh::from_submesh(sm);
let f = |x: f64, y: f64| x * x + x * y - 3.0 * y * y + 1.0;
let field = sampled(&mesh, &nodes, f);
let at = [[0.3, 0.4], [1.2, 0.5], [0.1, 1.7]];
let (target, targets) = points(&at);
let carried = project_node(&field, &mesh, &target, 1e-6).unwrap();
let z = carried.get(0).unwrap().read();
for (node, p) in targets.iter().zip(&at) {
assert!((z.value(node.id(), "a").unwrap() - f(p[0], p[1])).abs() < 1e-12);
}
}
#[test]
fn the_tolerance_catches_a_point_just_outside() {
let (mesh, nodes) = square(1);
let field = sampled(&mesh, &nodes, |x, _| 1.0 + x);
let (target, targets) = points(&[[1.0 + 2e-7, 0.5]]);
let caught = project_node(&field, &mesh, &target, 1e-6).unwrap();
let value = caught.get(0).unwrap().read().value(targets[0].id(), "a");
assert!((value.unwrap() - 2.0).abs() < 1e-6);
let missed = project_node(&field, &mesh, &target, 1e-8).unwrap();
let value = missed.get(0).unwrap().read().value(targets[0].id(), "a");
assert_eq!(value.unwrap(), 0.0);
}
#[test]
fn zones_on_both_sides() {
let (mesh, nodes) = square(1);
let ones = NodeField::new(&mesh, vec!["a".into()]).unwrap();
for n in &nodes {
ones.get(0)
.unwrap()
.write()
.set_value(n.id(), "a", 1.0)
.unwrap();
}
let left = poi1_from_nodes(&[nodes[0].clone(), nodes[2].clone()]).unwrap();
let threes = NodeField::new(&left, vec!["a".into()]).unwrap();
for n in [&nodes[0], &nodes[2]] {
threes
.get(0)
.unwrap()
.write()
.set_value(n.id(), "a", 3.0)
.unwrap();
}
let mut field = NodeField::default();
field.add_sub(threes.get(0).unwrap()).unwrap();
field.add_sub(ones.get(0).unwrap()).unwrap();
let coords = Handle::new(Coords::new(2).unwrap());
let p: Vec<Node> = [[0.5, 0.0], [0.5, 0.5], [0.5, 1.0]]
.iter()
.map(|q| Node::create_in(coords.clone(), q).unwrap())
.collect();
let mut target = Mesh::empty();
for pair in [[0, 1], [1, 2]] {
let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
sm.add_cell(&[p[pair[0]].id(), p[pair[1]].id()]).unwrap();
target.add_sub(Handle::new(sm)).unwrap();
}
let carried = project_node(&field, &mesh, &target, 1e-6).unwrap();
assert_eq!(carried.len(), 2);
for zone in &carried {
let z = zone.read();
assert!((z.value(p[1].id(), "a").unwrap() - 2.0).abs() < 1e-12);
}
let carried = project_node(&threes, &mesh, &target, 1e-6).unwrap();
let z = carried.get(0).unwrap().read();
assert!((z.value(p[1].id(), "a").unwrap() - 1.5).abs() < 1e-12);
}
#[test]
fn empty_sides_are_no_error() {
let (mesh, nodes) = square(1);
let field = sampled(&mesh, &nodes, |x, _| 1.0 + x);
let (target, targets) = points(&[[0.5, 0.5]]);
assert!(project_node(&NodeField::default(), &mesh, &target, 1e-6)
.unwrap()
.is_empty());
assert!(project_node(&field, &mesh, &Mesh::empty(), 1e-6)
.unwrap()
.is_empty());
let carried = project_node(&field, &Mesh::empty(), &target, 1e-6).unwrap();
let z = carried.get(0).unwrap().read();
assert_eq!(z.value(targets[0].id(), "a").unwrap(), 0.0);
assert_eq!(z.value(targets[0].id(), "b").unwrap(), 0.0);
}
fn tri6() -> (Mesh, Vec<Node>) {
let coords = Handle::new(Coords::new(2).unwrap());
let corners = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.0]];
let mids = [[1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
let nodes: Vec<Node> = corners
.iter()
.chain(&mids)
.map(|p| Node::create_in(coords.clone(), p).unwrap())
.collect();
let mut sm = SubMesh::new(coords, ElementType::TRI6);
let ids: Vec<NodeId> = nodes.iter().map(Node::id).collect();
sm.add_cell(&ids).unwrap();
(Mesh::from_submesh(sm), nodes)
}
#[test]
fn a_field_of_the_space_comes_back_exactly_from_the_gauss_points() {
let (mesh, nodes) = tri6();
let f = |x: f64, y: f64| x * x + x * y - 3.0 * y * y + 1.0;
let nodal = sampled(&mesh, &nodes, f);
let fes =
crate::containers::finite_element_space::FiniteElementSpace::lagrange(&mesh).unwrap();
let at_gauss = crate::ops::element_field::interp_to_gauss(&nodal, &fes).unwrap();
let at = [[0.3, 0.4], [1.2, 0.5], [0.1, 1.7]];
let (target, targets) = points(&at);
let carried = project_element(&at_gauss, &mesh, &target, 1e-6).unwrap();
let z = carried.get(0).unwrap().read();
for (node, p) in targets.iter().zip(&at) {
assert!((z.value(node.id(), "a").unwrap() - f(p[0], p[1])).abs() < 1e-10);
assert!((z.value(node.id(), "b").unwrap() + f(p[0], p[1])).abs() < 1e-10);
}
}
#[test]
fn element_fields_read_zero_where_nothing_holds_them() {
let (mesh, _) = square(1);
let fes =
crate::containers::finite_element_space::FiniteElementSpace::lagrange(&mesh).unwrap();
let with_a = ElementField::new(&fes, vec!["a".into()]).unwrap();
with_a
.get(0)
.unwrap()
.write()
.set_uniform("a", 2.0)
.unwrap();
let (target, targets) = points(&[[0.5, 0.5], [3.0, 3.0]]);
let carried = project_element(&with_a, &mesh, &target, 1e-6).unwrap();
let z = carried.get(0).unwrap().read();
assert!((z.value(targets[0].id(), "a").unwrap() - 2.0).abs() < 1e-12);
assert_eq!(z.value(targets[1].id(), "a").unwrap(), 0.0);
let with_b = ElementField::new(&fes, vec!["b".into()]).unwrap();
with_b
.get(0)
.unwrap()
.write()
.set_uniform("b", 7.0)
.unwrap();
let mut both = ElementField::empty();
both.add_sub(with_a.get(0).unwrap()).unwrap();
both.add_sub(with_b.get(0).unwrap()).unwrap();
let carried = project_element(&both, &mesh, &target, 1e-6).unwrap();
let z = carried.get(0).unwrap().read();
assert!((z.value(targets[0].id(), "a").unwrap() - 2.0).abs() < 1e-12);
assert_eq!(z.value(targets[0].id(), "b").unwrap(), 0.0);
let (other, _) = square(1);
let err = project_element(&with_a, &other, &target, 1e-6).unwrap_err();
assert!(format!("{err}").contains("no zone"), "unexpected: {err}");
}
#[test]
fn mismatches_are_refused() {
let (mesh, nodes) = square(1);
let field = sampled(&mesh, &nodes, |x, _| x);
let (other, _) = square(1);
let (target, _) = points(&[[0.5, 0.5]]);
assert!(project_node(&field, &other, &target, 1e-6).is_err());
let coords = Handle::new(Coords::new(3).unwrap());
let n = Node::create_in(coords, &[0.5, 0.5, 0.0]).unwrap();
let in_3d = poi1_from_nodes(&[n]).unwrap();
assert!(project_node(&field, &mesh, &in_3d, 1e-6).is_err());
}
}