use crate::aggregate::Aggregate;
use crate::containers::mesh::ElementType;
use crate::containers::mesh::NodeId;
use crate::containers::mesh::{Mesh, SubMesh};
use crate::py::coords::PyCoords;
use crate::py::node::PyNode;
use crate::store::{insert, read, write, Handle};
use pyo3::exceptions::{PyIndexError, PyTypeError, PyValueError};
use pyo3::prelude::*;
#[cfg(feature = "viz")]
fn with_field_arg<R>(
obj: &Bound<'_, PyAny>,
f: impl FnOnce(crate::viz::FieldArg<'_>) -> PyResult<R>,
) -> PyResult<R> {
if let Ok(nf) = obj.extract::<PyRef<crate::py::node_field::PyNodeField>>() {
f(crate::viz::FieldArg::Node(&nf.inner))
} else if let Ok(ef) = obj.extract::<PyRef<crate::py::element_field::PyElementField>>() {
f(crate::viz::FieldArg::Element(&ef.inner))
} else {
Err(PyTypeError::new_err(
"field must be a NodeField or an ElementField",
))
}
}
#[cfg(feature = "viz")]
pub(crate) fn parse_cmap(name: Option<String>) -> PyResult<crate::viz::Colormap> {
match name {
None => Ok(crate::viz::Colormap::default()),
Some(n) => crate::viz::Colormap::from_name(&n).ok_or_else(|| {
PyValueError::new_err(format!(
"unknown colormap {n:?} (available: {:?})",
crate::viz::Colormap::names()
))
}),
}
}
#[cfg(feature = "viz")]
fn mesh_style(wireframe: bool, has_field: bool) -> PyResult<crate::viz::MeshStyle> {
if wireframe && has_field {
return Err(PyValueError::new_err(
"wireframe=True has no meaning with a field: a field colours the \
cell faces. Drop field, or set wireframe=False.",
));
}
Ok(if wireframe {
crate::viz::MeshStyle::Wireframe
} else {
crate::viz::MeshStyle::Surface
})
}
pub(crate) fn submesh_handle(obj: &Bound<'_, PyAny>) -> PyResult<Handle<SubMesh>> {
if let Ok(sm) = obj.extract::<PyRef<PySubMesh>>() {
Ok(sm.handle.clone())
} else if let Ok(mesh) = obj.extract::<PyRef<PyMesh>>() {
Ok(mesh.inner.unit()?)
} else {
Err(PyTypeError::new_err("expected a SubMesh or a unitary Mesh"))
}
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "SubMesh")]
pub struct PySubMesh {
pub(crate) handle: Handle<SubMesh>,
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PySubMesh {
#[getter]
fn element_type(&self) -> PyResult<String> {
Ok(read(&self.handle)?.element_type().name().to_string())
}
fn add_cell(&self, nodes: Vec<PyRef<'_, PyNode>>) -> PyResult<usize> {
let nodes_typed: Vec<NodeId> = nodes.iter().map(|n| n.as_node().id()).collect();
let idx = write(&self.handle)?.add_cell(&nodes_typed)?;
Ok(idx)
}
fn cell_count(&self) -> PyResult<usize> {
Ok(read(&self.handle)?.cell_count())
}
#[getter]
fn is_sealed(&self) -> PyResult<bool> {
Ok(read(&self.handle)?.is_sealed())
}
fn duplicate(&self) -> PyResult<PySubMesh> {
let copy = read(&self.handle)?.duplicate()?;
Ok(PySubMesh {
handle: insert(copy),
})
}
#[getter]
fn face_color(&self) -> PyResult<(u8, u8, u8)> {
let c = read(&self.handle)?.face_color();
Ok((c.r, c.g, c.b))
}
#[setter]
fn set_face_color(&self, rgb: (u8, u8, u8)) -> PyResult<()> {
write(&self.handle)?
.set_face_color(crate::containers::mesh::RgbColor::new(rgb.0, rgb.1, rgb.2));
Ok(())
}
#[cfg(feature = "viz")]
#[pyo3(signature = (view=None, save=None, show_axes=true, field=None, component=None, vmin=None, vmax=None, cmap=None, smooth=4, wireframe=false))]
#[allow(clippy::too_many_arguments)]
fn plot(
&self,
view: Option<(f64, f64, f64)>,
save: Option<std::path::PathBuf>,
show_axes: bool,
field: Option<Bound<'_, PyAny>>,
component: Option<String>,
vmin: Option<f64>,
vmax: Option<f64>,
cmap: Option<String>,
smooth: usize,
wireframe: bool,
) -> PyResult<()> {
let style = mesh_style(wireframe, field.is_some())?;
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: parse_cmap(cmap)?,
vmin,
vmax,
};
let save_ref = save.as_deref();
match field {
Some(f) => {
let comp_ref = component.as_deref();
with_field_arg(&f, |arg| {
crate::viz::render_submesh_with_field(
&self.handle,
arg,
comp_ref,
scale,
smooth,
Some(view),
save_ref,
)?;
Ok(())
})?;
}
None => {
read(&self.handle)?.plot_styled(Some(view), save_ref, style)?;
}
}
Ok(())
}
fn __len__(&self) -> PyResult<usize> {
Ok(read(&self.handle)?.cell_count())
}
fn __getitem__(&self, idx: isize) -> PyResult<crate::py::cell::PyCell> {
let n = read(&self.handle)?.cell_count() as isize;
let normalized = if idx < 0 { n + idx } else { idx };
if normalized < 0 || normalized >= n {
return Err(PyIndexError::new_err(format!(
"submesh index {idx} out of range (len={n})"
)));
}
let cell = crate::containers::mesh::Cell::new(self.handle.clone(), normalized as usize)?;
Ok(crate::py::cell::PyCell::from_cell(cell))
}
fn __repr__(&self) -> PyResult<String> {
Ok(format!("{:?}", &*read(&self.handle)?))
}
fn __str__(&self) -> PyResult<String> {
Ok(format!("{}", &*read(&self.handle)?))
}
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "Mesh")]
pub struct PyMesh {
pub(crate) inner: Mesh,
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PyMesh {
#[new]
#[pyo3(signature = (coords, element_type=None))]
fn py_new(coords: PyRef<PyCoords>, element_type: Option<&str>) -> PyResult<Self> {
let coords = coords.handle.clone();
let mesh = match element_type {
Some(et_str) => {
let et = ElementType::from_name(et_str).ok_or_else(|| {
PyValueError::new_err(format!("unknown element type: {et_str}"))
})?;
Mesh::from_submesh(SubMesh::new(coords, et))
}
None => Mesh::empty(),
};
Ok(Self { inner: mesh })
}
fn element_types(&self) -> PyResult<Vec<String>> {
let types = self.inner.element_types()?;
Ok(types.into_iter().map(|et| et.name().to_string()).collect())
}
fn cell_counts(&self) -> PyResult<Vec<usize>> {
Ok(self.inner.cell_counts()?)
}
fn duplicate(&self) -> PyResult<PyMesh> {
Ok(Self {
inner: self.inner.duplicate()?,
})
}
fn node(&self, submesh_idx: usize, cell_idx: usize, node_idx: usize) -> PyResult<PyNode> {
let node = self.inner.node(submesh_idx, cell_idx, node_idx)?;
Ok(PyNode::from_node(node))
}
fn nearest_node(&self, point: Vec<f64>) -> PyResult<PyNode> {
let node = crate::ops::geom::nearest_node(&self.inner, &point)?;
Ok(PyNode::from_node(node))
}
fn cell(&self, submesh_idx: usize, cell_idx: usize) -> PyResult<crate::py::cell::PyCell> {
let cell = self.inner.cell(submesh_idx, cell_idx)?;
Ok(crate::py::cell::PyCell::from_cell(cell))
}
fn cell_count(&self) -> PyResult<usize> {
Ok(self.inner.cell_count()?)
}
fn coords(&self) -> PyResult<PyCoords> {
Ok(PyCoords {
handle: self.inner.coords()?,
})
}
#[cfg(feature = "viz")]
#[pyo3(signature = (view=None, save=None, show_axes=true, field=None, component=None, vmin=None, vmax=None, cmap=None, smooth=4, wireframe=false))]
#[allow(clippy::too_many_arguments)]
fn plot(
&self,
view: Option<(f64, f64, f64)>,
save: Option<std::path::PathBuf>,
show_axes: bool,
field: Option<Bound<'_, PyAny>>,
component: Option<String>,
vmin: Option<f64>,
vmax: Option<f64>,
cmap: Option<String>,
smooth: usize,
wireframe: bool,
) -> PyResult<()> {
let style = mesh_style(wireframe, field.is_some())?;
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: parse_cmap(cmap)?,
vmin,
vmax,
};
let save_ref = save.as_deref();
match field {
Some(f) => {
let comp_ref = component.as_deref();
with_field_arg(&f, |arg| {
self.inner.plot_with_field(
Some(view),
save_ref,
arg,
comp_ref,
scale,
smooth,
)?;
Ok(())
})?;
}
None => {
self.inner.plot_styled(Some(view), save_ref, style)?;
}
}
Ok(())
}
}
crate::impl_aggregate_pymethods!(PyMesh, PySubMesh, "Mesh", submesh, Mesh);
crate::impl_dump_pymethod!(handle PySubMesh, handle);