use crate::containers::element_field::{ElementField, SubElementField};
use crate::containers::field::SubField;
use crate::ops::field::Band;
use crate::py::finite_element_space::PyFiniteElementSpace;
use crate::store::{insert, read, write, Handle};
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::pyclass::CompareOp;
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "SubElementField")]
pub struct PySubElementField {
pub(crate) handle: Handle<SubElementField>,
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PySubElementField {
fn cell_count(&self) -> PyResult<usize> {
Ok(read(&self.handle)?.cell_count())
}
fn gauss_count(&self) -> PyResult<usize> {
Ok(read(&self.handle)?.gauss_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 component_index(&self, name: &str) -> PyResult<Option<usize>> {
Ok(read(&self.handle)?.component_index(name))
}
fn get(&self, cell: usize, gauss: usize, comp: usize) -> PyResult<f64> {
Ok(read(&self.handle)?.get(cell, gauss, comp)?)
}
fn set(&self, cell: usize, gauss: usize, comp: usize, value: f64) -> PyResult<()> {
write(&self.handle)?.set(cell, gauss, comp, value)?;
Ok(())
}
fn value(&self, cell: usize, gauss: usize, component: &str) -> PyResult<f64> {
Ok(read(&self.handle)?.value(cell, gauss, component)?)
}
fn set_value(&self, cell: usize, gauss: usize, component: &str, value: f64) -> PyResult<()> {
write(&self.handle)?.set_value(cell, gauss, component, value)?;
Ok(())
}
fn point_values(&self, cell: usize, gauss: usize) -> PyResult<Vec<f64>> {
Ok(read(&self.handle)?.point_values(cell, gauss)?.to_vec())
}
fn set_uniform(&self, component: &str, value: f64) -> PyResult<()> {
write(&self.handle)?.set_uniform(component, value)?;
Ok(())
}
fn set_cell_uniform(&self, cell: usize, component: &str, value: f64) -> PyResult<()> {
write(&self.handle)?.set_cell_uniform(cell, 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<PySubElementField> {
self.scalar_or_combine(rhs, |a, b| a + b)
}
fn __sub__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PySubElementField> {
self.scalar_or_combine(rhs, |a, b| a - b)
}
fn __mul__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PySubElementField> {
self.scalar_or_combine(rhs, |a, b| a * b)
}
fn __truediv__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PySubElementField> {
self.scalar_or_combine(rhs, |a, b| a / b)
}
fn __pow__(
&self,
exponent: &Bound<'_, PyAny>,
modulo: &Bound<'_, PyAny>,
) -> PyResult<PySubElementField> {
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((cell, gauss, comp)) = key.extract::<(usize, usize, String)>() {
let v = read(&self.handle)?
.value(cell, gauss, &comp)
.map_err(|e| PyValueError::new_err(e.to_string()))?;
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,
PySubElementField {
handle: insert(out),
},
)?
.into_any())
}
fn __setitem__(&self, key: (usize, usize, String), value: f64) -> PyResult<()> {
let (cell, gauss, comp) = key;
write(&self.handle)?.set_value(cell, gauss, &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_cells(&*read(&self.handle)?, &band, None);
Ok(Py::new(
py,
PySubElementField {
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 PySubElementField {
fn scalar_or_combine(
&self,
rhs: &Bound<'_, PyAny>,
op: fn(f64, f64) -> f64,
) -> PyResult<PySubElementField> {
if let Ok(s) = rhs.extract::<f64>() {
let out = read(&self.handle)?.map_all(|v| op(v, s));
Ok(PySubElementField {
handle: insert(out),
})
} else if let Ok(other) = rhs.extract::<PyRef<PySubElementField>>() {
let a = (*read(&self.handle)?).clone();
let b = (*read(&other.handle)?).clone();
Ok(PySubElementField {
handle: insert(a.merge_components(&b, op)?),
})
} else {
Err(PyTypeError::new_err(
"unsupported operand: expected a float or a SubElementField",
))
}
}
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "ElementField")]
pub struct PyElementField {
pub(crate) inner: ElementField,
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PyElementField {
#[new]
fn py_new(fespace: PyRef<PyFiniteElementSpace>, components: Vec<String>) -> PyResult<Self> {
let ef = ElementField::new(&fespace.inner, components)?;
Ok(Self { inner: ef })
}
#[classmethod]
fn with_components_per_subspace(
_cls: &pyo3::Bound<'_, pyo3::types::PyType>,
fespace: PyRef<PyFiniteElementSpace>,
components_per_subspace: Vec<Vec<String>>,
) -> PyResult<Self> {
let ef = ElementField::with(&fespace.inner, &components_per_subspace)?;
Ok(Self { inner: ef })
}
fn components(&self) -> PyResult<Vec<String>> {
use crate::containers::field::Field;
Ok(Field::components(&self.inner)?)
}
#[cfg(feature = "viz")]
#[pyo3(signature = (view=None, save=None, show_axes=true, component=None, vmin=None, vmax=None, cmap=None, smooth=4, 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,
component: Option<String>,
vmin: Option<f64>,
vmax: Option<f64>,
cmap: Option<String>,
smooth: usize,
revolve: bool,
revolve_angle: f64,
title: Option<String>,
) -> PyResult<()> {
let view = crate::py::build_view(view, show_axes, revolve, revolve_angle)?;
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,
smooth,
title.as_deref(),
)?;
Ok(())
}
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)?)
}
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<PyElementField> {
self.binary(rhs, |a, b| a + b)
}
fn __sub__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyElementField> {
self.binary(rhs, |a, b| a - b)
}
fn __mul__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyElementField> {
self.binary(rhs, |a, b| a * b)
}
fn __truediv__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyElementField> {
self.binary(rhs, |a, b| a / b)
}
fn __pow__(
&self,
exponent: &Bound<'_, PyAny>,
modulo: &Bound<'_, PyAny>,
) -> PyResult<PyElementField> {
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_cells(&self.inner, &band, None)?;
Ok(Py::new(py, PyElementField { inner: out })?.into_any())
}
}
impl PyElementField {
fn binary(&self, rhs: &Bound<'_, PyAny>, op: fn(f64, f64) -> f64) -> PyResult<PyElementField> {
use crate::containers::field::Field;
if let Ok(s) = rhs.extract::<f64>() {
Ok(PyElementField {
inner: self.inner.combine_scalar(op, s)?,
})
} else if let Ok(other) = rhs.extract::<PyRef<PyElementField>>() {
Ok(PyElementField {
inner: self.inner.merge_field(&other.inner, op)?,
})
} else if let Ok(sub) = rhs.extract::<PyRef<PySubElementField>>() {
let s = (*read(&sub.handle)?).clone();
Ok(PyElementField {
inner: self.inner.merge_subfield(&s, op)?,
})
} else {
Err(PyTypeError::new_err(
"unsupported operand: expected a float, an ElementField, or a SubElementField",
))
}
}
}
crate::impl_aggregate_pymethods!(
PyElementField,
PySubElementField,
"ElementField",
subfield,
ElementField,
field_components
);
crate::impl_dump_pymethod!(handle PySubElementField, handle);