use crate::aggregate::Aggregate;
use crate::containers::field::SubField;
use crate::containers::mesh::NodeId;
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::ops::field::Band;
use crate::py::mesh::{PyMesh, PySubMesh};
use crate::py::node::PyNode;
use crate::store::{insert, read, write, Handle};
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;
use pyo3::pyclass::CompareOp;
fn extract_node_ids(obj: &Bound<'_, PyAny>) -> PyResult<Vec<NodeId>> {
if let Ok(sm) = obj.extract::<PyRef<PySubMesh>>() {
return Ok(read(&sm.handle)?.connectivity().to_vec());
}
if let Ok(mesh) = obj.extract::<PyRef<PyMesh>>() {
let mut ids: Vec<NodeId> = Vec::new();
for h in &mesh.inner {
ids.extend_from_slice(read(h)?.connectivity());
}
return Ok(ids);
}
if let Ok(nodes) = obj.extract::<Vec<PyRef<'_, PyNode>>>() {
return Ok(nodes.iter().map(|n| n.as_node().id()).collect());
}
Err(PyTypeError::new_err(
"expected a list of Node, a SubMesh, or a Mesh",
))
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "SubNodeField")]
pub struct PySubNodeField {
pub(crate) handle: Handle<SubNodeField>,
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PySubNodeField {
fn node_count(&self) -> PyResult<usize> {
Ok(read(&self.handle)?.node_count())
}
fn component_count(&self) -> PyResult<usize> {
Ok(read(&self.handle)?.component_count())
}
fn components(&self) -> PyResult<Vec<String>> {
Ok(read(&self.handle)?.components().to_vec())
}
fn get(&self, node_idx: usize, comp_idx: usize) -> PyResult<f64> {
Ok(read(&self.handle)?.get(node_idx, comp_idx)?)
}
fn set(&self, node_idx: usize, comp_idx: usize, value: f64) -> PyResult<()> {
write(&self.handle)?.set(node_idx, comp_idx, value)?;
Ok(())
}
fn get_by_node(&self, node: PyRef<'_, PyNode>, comp_idx: usize) -> PyResult<f64> {
let nid = node.as_node().id();
Ok(read(&self.handle)?.get_by_node(nid, comp_idx)?)
}
fn set_by_node(&self, node: PyRef<'_, PyNode>, comp_idx: usize, value: f64) -> PyResult<()> {
let nid = node.as_node().id();
write(&self.handle)?.set_by_node(nid, comp_idx, value)?;
Ok(())
}
fn component_index(&self, name: &str) -> PyResult<Option<usize>> {
Ok(read(&self.handle)?.component_index(name))
}
fn node_values(&self, node_idx: usize) -> PyResult<Vec<f64>> {
Ok(read(&self.handle)?.node_values(node_idx)?.to_vec())
}
fn support_submesh(&self) -> PyResult<PySubMesh> {
let sm = read(&self.handle)?.support_submesh()?;
Ok(PySubMesh { handle: insert(sm) })
}
fn support_mesh(&self) -> PyResult<PyMesh> {
let mesh = read(&self.handle)?.support_mesh()?;
Ok(PyMesh { inner: mesh })
}
fn value(&self, node: PyRef<'_, PyNode>, component: &str) -> PyResult<f64> {
let nid = node.as_node().id();
Ok(read(&self.handle)?.value(nid, component)?)
}
fn set_value(&self, node: PyRef<'_, PyNode>, component: &str, value: f64) -> PyResult<()> {
let nid = node.as_node().id();
write(&self.handle)?.set_value(nid, component, value)?;
Ok(())
}
fn min(&self, component: &str) -> PyResult<f64> {
use crate::containers::field::SubField;
Ok(SubField::min(&*read(&self.handle)?, component)?)
}
fn max(&self, component: &str) -> PyResult<f64> {
use crate::containers::field::SubField;
Ok(SubField::max(&*read(&self.handle)?, component)?)
}
fn sum(&self, component: &str) -> PyResult<f64> {
use crate::containers::field::SubField;
Ok(SubField::sum(&*read(&self.handle)?, component)?)
}
fn add_to_component(&self, component: &str, scalar: f64) -> PyResult<()> {
write(&self.handle)?.add_to_component(component, scalar)?;
Ok(())
}
fn sub_to_component(&self, component: &str, scalar: f64) -> PyResult<()> {
write(&self.handle)?.sub_to_component(component, scalar)?;
Ok(())
}
fn mul_to_component(&self, component: &str, scalar: f64) -> PyResult<()> {
write(&self.handle)?.mul_to_component(component, scalar)?;
Ok(())
}
fn div_to_component(&self, component: &str, scalar: f64) -> PyResult<()> {
write(&self.handle)?.div_to_component(component, scalar)?;
Ok(())
}
fn __add__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PySubNodeField> {
self.scalar_or_combine(rhs, |a, b| a + b)
}
fn __sub__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PySubNodeField> {
self.scalar_or_combine(rhs, |a, b| a - b)
}
fn __mul__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PySubNodeField> {
self.scalar_or_combine(rhs, |a, b| a * b)
}
fn __truediv__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PySubNodeField> {
self.scalar_or_combine(rhs, |a, b| a / b)
}
fn __pow__(
&self,
exponent: &Bound<'_, PyAny>,
modulo: &Bound<'_, PyAny>,
) -> PyResult<PySubNodeField> {
if !modulo.is_none() {
return Err(PyTypeError::new_err(
"field ** exponent does not support a modulo argument",
));
}
self.scalar_or_combine(exponent, |a, b| a.powf(b))
}
fn __getitem__(&self, py: Python<'_>, key: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
if let Ok((node, comp)) = key.extract::<(PyRef<'_, PyNode>, String)>() {
let nid = node.as_node().id();
let v = read(&self.handle)?.value(nid, &comp)?;
return Ok(v.into_pyobject(py)?.into_any().unbind());
}
let names = crate::py::ops::field::extract_names(key)?;
let out =
crate::containers::field::SubField::select_components(&*read(&self.handle)?, names)?;
Ok(Py::new(
py,
PySubNodeField {
handle: insert(out),
},
)?
.into_any())
}
fn __setitem__(&self, key: (PyRef<'_, PyNode>, String), value: f64) -> PyResult<()> {
let (node, comp) = key;
let nid = node.as_node().id();
write(&self.handle)?.set_value(nid, &comp, value)?;
Ok(())
}
fn __richcmp__(
&self,
py: Python<'_>,
other: &Bound<'_, PyAny>,
op: CompareOp,
) -> PyResult<Py<PyAny>> {
let Ok(x) = other.extract::<f64>() else {
return Ok(py.NotImplemented());
};
let band = match op {
CompareOp::Ge => Band::new(Some(x), None, None, None),
CompareOp::Gt => Band::new(None, Some(x), None, None),
CompareOp::Le => Band::new(None, None, Some(x), None),
CompareOp::Lt => Band::new(None, None, None, Some(x)),
CompareOp::Eq | CompareOp::Ne => return Ok(py.NotImplemented()),
}?;
let out = crate::ops::field::mask_sub_nodes(&*read(&self.handle)?, &band, None);
Ok(Py::new(
py,
PySubNodeField {
handle: insert(out),
},
)?
.into_any())
}
fn __repr__(&self) -> PyResult<String> {
Ok(format!("{:?}", &*read(&self.handle)?))
}
fn __str__(&self) -> PyResult<String> {
Ok(format!("{}", &*read(&self.handle)?))
}
}
impl PySubNodeField {
fn scalar_or_combine(
&self,
rhs: &Bound<'_, PyAny>,
op: fn(f64, f64) -> f64,
) -> PyResult<PySubNodeField> {
if let Ok(s) = rhs.extract::<f64>() {
let out = read(&self.handle)?.map_all(|v| op(v, s));
Ok(PySubNodeField {
handle: insert(out),
})
} else if let Ok(other) = rhs.extract::<PyRef<PySubNodeField>>() {
let a = (*read(&self.handle)?).clone();
let b = (*read(&other.handle)?).clone();
Ok(PySubNodeField {
handle: insert(a.merge_components(&b, op)?),
})
} else {
Err(PyTypeError::new_err(
"unsupported operand: expected a float or a SubNodeField",
))
}
}
}
crate::impl_dump_pymethod!(handle PySubNodeField, handle);
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "NodeField")]
pub struct PyNodeField {
pub(crate) inner: NodeField,
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PyNodeField {
#[new]
fn py_new(support: &Bound<'_, PyAny>, components: Vec<String>) -> PyResult<Self> {
let inner = if let Ok(mesh) = support.extract::<PyRef<PyMesh>>() {
NodeField::new(&mesh.inner, components)?
} else if let Ok(sm) = support.extract::<PyRef<PySubMesh>>() {
NodeField::from_submesh(&sm.handle, components)?
} else {
return Err(PyTypeError::new_err("expected a Mesh or a SubMesh"));
};
Ok(Self { inner })
}
#[classmethod]
fn with_components_per_submesh(
_cls: &pyo3::Bound<'_, pyo3::types::PyType>,
mesh: PyRef<PyMesh>,
components_per_submesh: Vec<Vec<String>>,
) -> PyResult<Self> {
let inner = NodeField::with(&mesh.inner, &components_per_submesh)?;
Ok(Self { inner })
}
fn node_count(&self) -> PyResult<usize> {
Ok(self.inner.node_count()?)
}
fn components(&self) -> PyResult<Vec<String>> {
use crate::containers::field::Field;
Ok(Field::components(&self.inner)?)
}
fn value(&self, node: PyRef<'_, PyNode>, component: &str) -> PyResult<f64> {
let nid = node.as_node().id();
Ok(self.inner.value(nid, component)?)
}
fn values(&self, nodes: &Bound<'_, PyAny>, component: &str) -> PyResult<Vec<f64>> {
let ids = extract_node_ids(nodes)?;
Ok(self.inner.values_at(&ids, component)?)
}
fn check(&self) -> PyResult<()> {
Ok(self.inner.check()?)
}
fn min(&self, component: &str) -> PyResult<f64> {
use crate::containers::field::Field;
Ok(Field::min(&self.inner, component)?)
}
fn max(&self, component: &str) -> PyResult<f64> {
use crate::containers::field::Field;
Ok(Field::max(&self.inner, component)?)
}
fn sum(&self, component: &str) -> PyResult<f64> {
use crate::containers::field::Field;
Ok(Field::sum(&self.inner, component)?)
}
#[cfg(feature = "viz")]
#[pyo3(signature = (view=None, save=None, show_axes=true, component=None, vmin=None, vmax=None, cmap=None))]
#[allow(clippy::too_many_arguments)]
fn plot(
&self,
view: Option<(f64, f64, f64)>,
save: Option<std::path::PathBuf>,
show_axes: bool,
component: Option<String>,
vmin: Option<f64>,
vmax: Option<f64>,
cmap: Option<String>,
) -> PyResult<()> {
let mut view = view
.map(|(yaw, pitch, scale)| crate::viz::View {
yaw,
pitch,
scale,
target: None,
show_axes,
})
.unwrap_or_default();
view.show_axes = show_axes;
let scale = crate::viz::ColorScale {
cmap: crate::py::mesh::parse_cmap(cmap)?,
vmin,
vmax,
};
self.inner
.plot(Some(view), save.as_deref(), component.as_deref(), scale)?;
Ok(())
}
fn support_mesh(&self) -> PyResult<PyMesh> {
let mut mesh = crate::containers::mesh::Mesh::empty();
for h in &self.inner {
let sm = read(h)?.support();
mesh.add_sub(sm)?;
}
Ok(PyMesh { inner: mesh })
}
fn add_to_component(&self, component: &str, scalar: f64) -> PyResult<()> {
use crate::containers::field::Field;
self.inner.add_to_component(component, scalar)?;
Ok(())
}
fn sub_to_component(&self, component: &str, scalar: f64) -> PyResult<()> {
use crate::containers::field::Field;
self.inner.sub_to_component(component, scalar)?;
Ok(())
}
fn mul_to_component(&self, component: &str, scalar: f64) -> PyResult<()> {
use crate::containers::field::Field;
self.inner.mul_to_component(component, scalar)?;
Ok(())
}
fn div_to_component(&self, component: &str, scalar: f64) -> PyResult<()> {
use crate::containers::field::Field;
self.inner.div_to_component(component, scalar)?;
Ok(())
}
fn __add__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyNodeField> {
self.binary(rhs, |a, b| a + b)
}
fn __sub__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyNodeField> {
self.binary(rhs, |a, b| a - b)
}
fn __mul__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyNodeField> {
self.binary(rhs, |a, b| a * b)
}
fn __truediv__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyNodeField> {
self.binary(rhs, |a, b| a / b)
}
fn __pow__(
&self,
exponent: &Bound<'_, PyAny>,
modulo: &Bound<'_, PyAny>,
) -> PyResult<PyNodeField> {
if !modulo.is_none() {
return Err(PyTypeError::new_err(
"field ** exponent does not support a modulo argument",
));
}
self.binary(exponent, |a, b| a.powf(b))
}
fn __richcmp__(
&self,
py: Python<'_>,
other: &Bound<'_, PyAny>,
op: CompareOp,
) -> PyResult<Py<PyAny>> {
let Ok(x) = other.extract::<f64>() else {
return Ok(py.NotImplemented());
};
let band = match op {
CompareOp::Ge => Band::new(Some(x), None, None, None),
CompareOp::Gt => Band::new(None, Some(x), None, None),
CompareOp::Le => Band::new(None, None, Some(x), None),
CompareOp::Lt => Band::new(None, None, None, Some(x)),
CompareOp::Eq | CompareOp::Ne => return Ok(py.NotImplemented()),
}?;
let out = crate::ops::field::mask_nodes(&self.inner, &band, None)?;
Ok(Py::new(py, PyNodeField { inner: out })?.into_any())
}
}
impl PyNodeField {
fn binary(&self, rhs: &Bound<'_, PyAny>, op: fn(f64, f64) -> f64) -> PyResult<PyNodeField> {
use crate::containers::field::Field;
if let Ok(s) = rhs.extract::<f64>() {
Ok(PyNodeField {
inner: self.inner.combine_scalar(op, s)?,
})
} else if let Ok(other) = rhs.extract::<PyRef<PyNodeField>>() {
Ok(PyNodeField {
inner: self.inner.merge_field(&other.inner, op)?,
})
} else if let Ok(sub) = rhs.extract::<PyRef<PySubNodeField>>() {
let s = (*read(&sub.handle)?).clone();
Ok(PyNodeField {
inner: self.inner.merge_subfield(&s, op)?,
})
} else {
Err(PyTypeError::new_err(
"unsupported operand: expected a float, a NodeField, or a SubNodeField",
))
}
}
}
crate::impl_aggregate_pymethods!(
PyNodeField,
PySubNodeField,
"NodeField",
subfield,
NodeField,
field_components
);