use crate::aggregate::Aggregate;
use crate::atoms::ElementType;
use crate::containers::element_field::SubElementField;
use crate::containers::mesh::Mesh;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::models::{
constraint_block_pair, Constraint, ConstraintTerm, Contribution, MatrixKind, Physics, Relation,
RelationSense, SubModelKind,
};
use serde::{Deserialize, Serialize};
pub fn default_multiplier() -> String {
"lambda_mpc".to_string()
}
pub fn default_imposed_value() -> String {
"mpc_rhs".to_string()
}
#[derive(Serialize, Deserialize)]
pub struct MpcTerm {
pub(crate) mesh: Mesh,
pub(crate) variable: String,
pub(crate) target_dual: String,
pub(crate) coefficient: f64,
}
impl MpcTerm {
pub fn new(
target: &crate::containers::model::Model,
mesh: &Mesh,
variable: &str,
coefficient: f64,
) -> Result<Self> {
let target_dual = target.dual_of(variable).ok_or_else(|| {
PyrucastError::Message(format!(
"MpcTerm: `{variable}` is not a primal of the model it constrains — it \
declares {:?}",
target.primal_vars()
))
})?;
Ok(Self {
mesh: share(mesh)?,
variable: variable.to_string(),
target_dual,
coefficient,
})
}
}
#[derive(Serialize, Deserialize)]
pub struct Mpc {
pub(crate) terms: Vec<MpcTerm>,
pub(crate) multiplier_mesh: Mesh,
pub(crate) multiplier: String,
pub(crate) imposed_value: String,
#[serde(default)]
pub(crate) sense: RelationSense,
}
impl Mpc {
pub fn new(terms: Vec<MpcTerm>, multiplier_mesh: &Mesh, sense: RelationSense) -> Result<Self> {
if terms.is_empty() {
return Err(PyrucastError::Message(
"Mpc: at least one term is required".into(),
));
}
if multiplier_mesh.cell_count() == 0 {
return Err(PyrucastError::Message(
"Mpc: multiplier_mesh must carry at least one node".into(),
));
}
let n_sub = multiplier_mesh.len();
let coords_m = multiplier_mesh.coords()?;
let mut mult_counts = Vec::with_capacity(n_sub);
for i in 0..n_sub {
let mult_sm = multiplier_mesh.get(i)?;
let (met, mcount) = {
let s = mult_sm.read();
(s.element_type(), s.cell_count())
};
if met != ElementType::POI1 {
return Err(PyrucastError::Message(format!(
"Mpc: multiplier_mesh submesh {i} must be POI1, got {met}"
)));
}
mult_counts.push(mcount);
}
for (t_idx, t) in terms.iter().enumerate() {
let coords_t = t.mesh.coords()?;
if !coords_t.same_object(&coords_m) {
return Err(PyrucastError::Message(format!(
"Mpc: term {t_idx} mesh and multiplier_mesh must share a Coords"
)));
}
if t.mesh.len() != n_sub {
return Err(PyrucastError::Message(format!(
"Mpc: multiplier_mesh has {n_sub} submesh(es) but term {t_idx} has {}",
t.mesh.len()
)));
}
for i in 0..n_sub {
let term_sm = t.mesh.get(i)?;
let (tet, tcount) = {
let s = term_sm.read();
(s.element_type(), s.cell_count())
};
if tet != ElementType::POI1 {
return Err(PyrucastError::Message(format!(
"Mpc: term {t_idx} submesh {i} must be POI1, got {tet}"
)));
}
if tcount != mult_counts[i] {
return Err(PyrucastError::Message(format!(
"Mpc: term {t_idx} submesh {i} has {tcount} node(s) but \
multiplier has {}",
mult_counts[i]
)));
}
}
}
Ok(Self {
terms,
multiplier_mesh: share(multiplier_mesh)?,
multiplier: default_multiplier(),
imposed_value: default_imposed_value(),
sense,
})
}
}
impl SubModelKind for Mpc {
fn primal_vars(&self) -> Vec<String> {
vec![self.multiplier.clone()]
}
fn dual_vars(&self) -> Vec<String> {
vec![self.imposed_value.clone()]
}
fn internal_force_contribution(&self) -> Vec<crate::models::ResidualContribution> {
vec![crate::models::ResidualContribution::Relations]
}
fn as_constraint(&self) -> Option<&dyn Constraint> {
Some(self)
}
fn contributions(
&self,
kind: MatrixKind,
_material: Option<&crate::handle::Handle<SubElementField>>,
) -> Result<Vec<Contribution>> {
if kind != MatrixKind::Stiffness {
return Ok(Vec::new());
}
let n_sub = self.multiplier_mesh.len();
let mut blocks = Vec::with_capacity(n_sub * self.terms.len() * 2);
for i in 0..n_sub {
let mult_sm = self.multiplier_mesh.get(i)?;
for t in &self.terms {
let term_sm = t.mesh.get(i)?;
let (c_block, ct_block) = constraint_block_pair(
&mult_sm,
&term_sm,
&t.variable,
&t.target_dual,
&self.multiplier,
&self.imposed_value,
t.coefficient,
)?;
blocks.push(c_block);
blocks.push(ct_block);
}
}
Ok(vec![Contribution::Literal(blocks)])
}
fn physics(&self) -> &'static [Physics] {
&[Physics::Constraint]
}
fn label(&self) -> &'static str {
"Mpc"
}
fn display(&self) -> String {
let n = self.multiplier_mesh.cell_count();
format!(
"SubModel<Mpc>: {} relation(s), {} term(s) each",
n,
self.terms.len()
)
}
fn render(&self, _opts: &DumpOptions) -> String {
let n = self.multiplier_mesh.cell_count();
let mut out = format!(
"SubModel<Mpc>\n primal var(s): {} (multiplier)\n dual var(s): {} \
(imposed value / g)\n sense: {}\n relations: {n}\n terms:",
self.multiplier, self.imposed_value, self.sense,
);
for t in &self.terms {
out.push_str(&format!(
"\n {:+} · {} (dual {})",
t.coefficient, t.variable, t.target_dual
));
}
out
}
}
impl Constraint for Mpc {
fn multiplier_mesh(&self) -> &Mesh {
&self.multiplier_mesh
}
fn relations(&self) -> Result<Vec<Relation>> {
let n_sub = self.multiplier_mesh.len();
let mut relations = Vec::new();
for i in 0..n_sub {
let mult = self.multiplier_mesh.get(i)?.read();
let term_guards: Vec<crate::handle::ReadGuard<crate::containers::mesh::SubMesh>> = self
.terms
.iter()
.map(|t| Ok(t.mesh.get(i)?.read()))
.collect::<Result<Vec<_>>>()?;
for (r, mult_node) in mult.connectivity().iter().enumerate() {
let terms = self
.terms
.iter()
.zip(&term_guards)
.map(|(t, g)| ConstraintTerm {
node: g.connectivity()[r],
variable: t.variable.clone(),
target_dual: t.target_dual.clone(),
coefficient: t.coefficient,
})
.collect();
relations.push(Relation {
multiplier_node: *mult_node,
imposed_value: self.imposed_value.clone(),
terms,
sense: self.sense,
});
}
}
Ok(relations)
}
}
fn share(mesh: &Mesh) -> Result<Mesh> {
let mut out = Mesh::empty();
for sm in mesh {
out.add_sub(sm.clone())?;
}
Ok(out)
}
#[cfg(test)]
mod tests {
fn cible_conduction(coords: &Handle<Coords>, a: &Node) -> crate::containers::model::Model {
let b = Node::create_in(coords.clone(), &[2.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
sm.add_cell(&[a.id(), b.id()]).unwrap();
let fes = crate::containers::finite_element_space::FiniteElementSpace::lagrange1(
&Mesh::from_submesh(sm),
)
.unwrap();
crate::ops::model::heat_conduction(&fes).unwrap()
}
use super::*;
use crate::atoms::Node;
use crate::containers::mesh::SubMesh;
use crate::coords::Coords;
use crate::handle::Handle;
use crate::ops::mesh::barycenter;
fn poi1(node: &Node) -> Mesh {
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(node)).unwrap())
}
#[test]
fn empty_terms_rejected() {
let coords = Handle::new(Coords::new(1).unwrap());
let n = Node::create_in(coords, &[0.0]).unwrap();
let mult = barycenter(&poi1(&n)).unwrap();
assert!(Mpc::new(vec![], &mult, Default::default()).is_err());
}
#[test]
fn mismatched_cell_count_rejected() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
let mut term_sm = SubMesh::new(coords, ElementType::POI1);
term_sm.add_cell(&[a.id()]).unwrap();
term_sm.add_cell(&[b.id()]).unwrap();
let term_mesh = Mesh::from_submesh(term_sm);
let mult = barycenter(&poi1(&a)).unwrap();
let cible = cible_conduction(&a.coords(), &a);
let term = MpcTerm::new(&cible, &term_mesh, "T", 1.0).unwrap();
assert!(Mpc::new(vec![term], &mult, Default::default()).is_err());
}
#[test]
fn relations_flatten_terms() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords, &[1.0]).unwrap();
let mesh_a = poi1(&a);
let mesh_b = poi1(&b);
let mult = barycenter(&mesh_a).unwrap();
let cible = cible_conduction(&a.coords(), &a);
let terms = vec![
MpcTerm::new(&cible, &mesh_a, "T", 2.0).unwrap(),
MpcTerm::new(&cible, &mesh_b, "T", -3.0).unwrap(),
];
let mpc = Mpc::new(terms, &mult, Default::default()).unwrap();
assert_eq!(mpc.primal_vars(), vec!["lambda_mpc".to_string()]);
assert_eq!(mpc.dual_vars(), vec!["mpc_rhs".to_string()]);
let rels = mpc.relations().unwrap();
assert_eq!(rels.len(), 1);
assert_eq!(rels[0].terms.len(), 2);
assert_eq!(rels[0].terms[0].node, a.id());
assert_eq!(rels[0].terms[0].coefficient, 2.0);
assert_eq!(rels[0].terms[1].node, b.id());
assert_eq!(rels[0].terms[1].coefficient, -3.0);
}
}