use crate::aggregate::Aggregate;
use crate::atoms::ElementType;
use crate::atoms::NodeId;
use crate::containers::mesh::{Mesh, SubMesh};
use crate::handle::Handle;
use crate::py::coords::PyCoords;
use crate::py::node::PyNode;
use pyo3::exceptions::{PyIndexError, PyTypeError};
#[cfg(feature = "viz")]
use pyo3::exceptions::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")]
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(self.handle.read().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 = self.handle.write().add_cell(&nodes_typed)?;
Ok(idx)
}
fn cell_count(&self) -> PyResult<usize> {
Ok(self.handle.read().cell_count())
}
#[getter]
fn is_sealed(&self) -> PyResult<bool> {
Ok(self.handle.read().is_sealed())
}
fn duplicate(&self) -> PyResult<PySubMesh> {
let copy = self.handle.read().duplicate()?;
Ok(PySubMesh {
handle: Handle::new(copy),
})
}
#[getter]
fn face_color(&self) -> PyResult<(u8, u8, u8)> {
let c = self.handle.read().face_color();
Ok((c.r, c.g, c.b))
}
#[setter]
fn set_face_color(&self, rgb: (u8, u8, u8)) -> PyResult<()> {
self.handle
.write()
.set_face_color(crate::atoms::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, revolve=false, revolve_angle=360.0, title=None))]
#[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<crate::viz::Colormap>,
smooth: usize,
wireframe: bool,
revolve: bool,
revolve_angle: f64,
title: Option<String>,
) -> PyResult<()> {
let style = mesh_style(wireframe, field.is_some())?;
let view = crate::py::build_view(view, show_axes, revolve, revolve_angle)?;
let scale = crate::viz::ColorScale {
cmap: cmap.unwrap_or_default(),
vmin,
vmax,
};
let save_ref = save.as_deref();
let title_ref = title.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,
view,
save_ref,
title_ref,
)?;
Ok(())
})?;
}
None => {
self.handle
.read()
.plot_styled(view, save_ref, style, title_ref)?;
}
}
Ok(())
}
fn __len__(&self) -> PyResult<usize> {
Ok(self.handle.read().cell_count())
}
fn __getitem__(&self, idx: isize) -> PyResult<crate::py::cell::PyCell> {
let n = self.handle.read().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::atoms::Cell::new(self.handle.clone(), normalized as usize)?;
Ok(crate::py::cell::PyCell::from_cell(cell))
}
fn __repr__(&self) -> PyResult<String> {
Ok(format!("{:?}", *self.handle.read()))
}
fn __str__(&self) -> PyResult<String> {
Ok(format!("{}", *self.handle.read()))
}
}
#[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<ElementType>) -> PyResult<Self> {
let coords = coords.handle.clone();
let mesh = match element_type {
Some(et) => 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 set_face_color(&self, rgb: (u8, u8, u8)) -> PyResult<PyMesh> {
let color = crate::atoms::RgbColor::new(rgb.0, rgb.1, rgb.2);
Ok(Self {
inner: self.inner.set_face_color(color),
})
}
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 = self.inner.nearest_node(&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, revolve=false, revolve_angle=360.0, title=None))]
#[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<crate::viz::Colormap>,
smooth: usize,
wireframe: bool,
revolve: bool,
revolve_angle: f64,
title: Option<String>,
) -> PyResult<()> {
let style = mesh_style(wireframe, field.is_some())?;
let view = crate::py::build_view(view, show_axes, revolve, revolve_angle)?;
let scale = crate::viz::ColorScale {
cmap: cmap.unwrap_or_default(),
vmin,
vmax,
};
let save_ref = save.as_deref();
let title_ref = title.as_deref();
match field {
Some(f) => {
let comp_ref = component.as_deref();
with_field_arg(&f, |arg| {
self.inner
.plot_with_field(view, save_ref, arg, comp_ref, scale, smooth, title_ref)?;
Ok(())
})?;
}
None => {
self.inner.plot_styled(view, save_ref, style, title_ref)?;
}
}
Ok(())
}
}
crate::impl_aggregate_pymethods!(
PyMesh,
PySubMesh,
"Mesh",
submesh,
Mesh,
r#"
class PyMesh:
@overload
def __getitem__(self, key: int) -> pyo3_stub_gen.RustType["PySubMesh"]:
"""`mesh[i]` → the `SubMesh` view of zone i, i.e. the cells of one
element type (negative indices supported). Iterating a `Mesh` yields
the same views, one per zone."""
@overload
def __getitem__(self, key: slice) -> pyo3_stub_gen.RustType["PyMesh"]:
"""`mesh[i:j:k]` → a fresh `Mesh` over the sliced zones, sharing their
cells with this one (no deep copy)."""
def __or__(self, other: pyo3_stub_gen.RustType["PyMesh"] | pyo3_stub_gen.RustType["PySubMesh"]) -> pyo3_stub_gen.RustType["PyMesh"]:
"""`mesh | other` → a fresh `Mesh` holding the zones of both, in
first-seen order. A zone already present (the same object) is not added
twice; the others are shared, not copied. All zones must hang off the
same `Coords`."""
def __ror__(self, other: pyo3_stub_gen.RustType["PySubMesh"]) -> pyo3_stub_gen.RustType["PyMesh"]:
"""`submesh | mesh` — the mirror of `mesh | submesh`, differing only in
that the lone zone comes first."""
"#,
r#"
class PySubMesh:
def __or__(self, other: pyo3_stub_gen.RustType["PySubMesh"]) -> pyo3_stub_gen.RustType["PyMesh"]:
"""`submesh | submesh` → a fresh `Mesh` holding both zones. The usual
way to build a multi-element-type mesh from single-type ones."""
"#
);
crate::impl_dump_pymethod!(handle PySubMesh, handle);