use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::element_field::SubElementField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::mesh::Mesh;
use crate::containers::mesh::SubMesh;
use crate::containers::model::SubModel;
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::handle::{Handle, ReadGuard};
use crate::models::{MatrixKind, Physics};
use crate::parallel::*;
use nalgebra::{DMatrix, DVector};
use nalgebra_sparse::{CooMatrix, CscMatrix, CsrMatrix};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
pub type MatrixEntry = (NodeId, String, NodeId, String, f64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum DofOrdering {
VarsThenNodes,
NodesThenVars,
}
impl DofOrdering {
pub fn to_index(
self,
node_local: usize,
var_idx: usize,
n_nodes: usize,
n_vars: usize,
) -> usize {
match self {
DofOrdering::VarsThenNodes => var_idx * n_nodes + node_local,
DofOrdering::NodesThenVars => node_local * n_vars + var_idx,
}
}
pub fn from_index(self, idx: usize, n_nodes: usize, n_vars: usize) -> (usize, usize) {
match self {
DofOrdering::VarsThenNodes => (idx % n_nodes, idx / n_nodes),
DofOrdering::NodesThenVars => (idx / n_vars, idx % n_vars),
}
}
}
impl crate::dump::Dump for DofOrdering {
fn render(&self, _opts: &crate::dump::DumpOptions) -> String {
format!("{self:?}")
}
}
#[derive(Clone, Default, Serialize, Deserialize)]
pub enum KernelInputs {
#[default]
MaterialOnly,
State(Handle<SubElementField>),
Behavior {
deformation: Handle<SubElementField>,
prev: Handle<SubElementField>,
dt: f64,
},
}
#[derive(Clone, Serialize, Deserialize)]
pub struct ComputedRecipe {
pub submodel: Handle<SubModel>,
pub fespaces: Vec<Handle<SubFiniteElementSpace>>,
pub material: Option<Handle<SubElementField>>,
#[serde(default)]
pub kind: MatrixKind,
#[serde(default)]
pub inputs: KernelInputs,
#[serde(default)]
pub col_fespaces: Vec<Handle<SubFiniteElementSpace>>,
}
fn default_factor() -> f64 {
1.0
}
pub type PairId = u64;
fn fnv(h: u64, bytes: &[u8]) -> u64 {
let mut h = h;
for &b in bytes {
h ^= b as u64;
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
pub(crate) const FNV_SEED: u64 = 0xcbf2_9ce4_8422_2325;
pub(crate) fn hash_nodes(h: u64, nodes: &[NodeId]) -> u64 {
nodes.iter().fold(h, |h, n| fnv(h, &n.0.to_le_bytes()))
}
pub(crate) fn hash_name(h: u64, name: &str) -> u64 {
fnv(h, name.as_bytes())
}
pub(crate) fn hash_f64(h: u64, v: f64) -> u64 {
fnv(h, &v.to_bits().to_le_bytes())
}
pub(crate) fn mint_pair(content: u64) -> (PairId, PairId) {
let base = content & !1;
(base, base | 1)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Symmetry {
Full,
Half(PairId),
None,
}
impl crate::named::Named for Symmetry {
const LABEL: &'static str = "symmetry";
const VALUES: &'static [Self] = &[Symmetry::Full, Symmetry::None];
fn name(self) -> &'static str {
match self {
Symmetry::Full => "full",
Symmetry::Half(_) => "half",
Symmetry::None => "none",
}
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct SubMatrix {
row_support: Handle<SubMesh>,
col_support: Handle<SubMesh>,
dual_vars: Vec<String>,
primal_vars: Vec<String>,
ordering: DofOrdering,
#[serde(with = "coo_serde")]
coo: CooMatrix<f64>,
symmetry: Symmetry,
#[serde(default)]
recipe: Option<ComputedRecipe>,
#[serde(default)]
physics: Vec<Physics>,
#[serde(default = "default_factor")]
factor: f64,
}
impl SubMatrix {
pub fn new(
row_support: Handle<SubMesh>,
col_support: Handle<SubMesh>,
dual_vars: Vec<String>,
primal_vars: Vec<String>,
ordering: DofOrdering,
symmetry: Symmetry,
) -> Self {
crate::containers::mesh::seal(&row_support);
crate::containers::mesh::seal(&col_support);
let nrows = row_support.read().connectivity().len() * dual_vars.len();
let ncols = col_support.read().connectivity().len() * primal_vars.len();
Self {
row_support,
col_support,
dual_vars,
primal_vars,
ordering,
coo: CooMatrix::new(nrows, ncols),
symmetry,
recipe: None,
physics: Vec::new(),
factor: 1.0,
}
}
#[allow(clippy::too_many_arguments)]
pub fn computed(
row_support: Handle<SubMesh>,
col_support: Handle<SubMesh>,
dual_vars: Vec<String>,
primal_vars: Vec<String>,
ordering: DofOrdering,
symmetry: Symmetry,
recipe: ComputedRecipe,
) -> Self {
crate::containers::mesh::seal(&row_support);
crate::containers::mesh::seal(&col_support);
let nrows = row_support.read().connectivity().len() * dual_vars.len();
let ncols = col_support.read().connectivity().len() * primal_vars.len();
Self {
row_support,
col_support,
dual_vars,
primal_vars,
ordering,
coo: CooMatrix::new(nrows, ncols),
symmetry,
recipe: Some(recipe),
physics: Vec::new(),
factor: 1.0,
}
}
#[allow(clippy::too_many_arguments)]
pub fn from_coo(
row_support: Handle<SubMesh>,
col_support: Handle<SubMesh>,
dual_vars: Vec<String>,
primal_vars: Vec<String>,
ordering: DofOrdering,
symmetry: Symmetry,
coo: CooMatrix<f64>,
) -> Result<Self> {
crate::containers::mesh::seal(&row_support);
crate::containers::mesh::seal(&col_support);
let nrows = row_support.read().connectivity().len() * dual_vars.len();
let ncols = col_support.read().connectivity().len() * primal_vars.len();
if coo.nrows() != nrows || coo.ncols() != ncols {
return Err(PyrucastError::Message(format!(
"from_coo: COO is {}×{} but the support/vars imply {}×{}",
coo.nrows(),
coo.ncols(),
nrows,
ncols
)));
}
Ok(Self {
row_support,
col_support,
dual_vars,
primal_vars,
ordering,
coo,
symmetry,
recipe: None,
physics: Vec::new(),
factor: 1.0,
})
}
pub fn is_computed(&self) -> bool {
self.recipe.is_some()
}
pub fn recipe(&self) -> Option<&ComputedRecipe> {
self.recipe.as_ref()
}
pub fn physics(&self) -> &[Physics] {
&self.physics
}
pub fn set_physics(&mut self, physics: Vec<Physics>) {
self.physics = physics;
}
pub fn factor(&self) -> f64 {
self.factor
}
pub fn is_symmetric(&self) -> bool {
matches!(self.symmetry, Symmetry::Full)
}
pub fn symmetry(&self) -> Symmetry {
self.symmetry
}
pub fn n_rows(&self) -> usize {
self.coo.nrows()
}
pub fn n_cols(&self) -> usize {
self.coo.ncols()
}
pub fn entry_count(&self) -> usize {
self.coo.nnz()
}
pub fn memory_bytes(&self) -> usize {
self.coo.nnz() * (2 * std::mem::size_of::<usize>() + std::mem::size_of::<f64>())
}
pub fn dual_vars(&self) -> &[String] {
&self.dual_vars
}
pub fn primal_vars(&self) -> &[String] {
&self.primal_vars
}
pub fn ordering(&self) -> DofOrdering {
self.ordering
}
pub fn row_support(&self) -> &Handle<SubMesh> {
&self.row_support
}
pub fn col_support(&self) -> &Handle<SubMesh> {
&self.col_support
}
pub fn field_names(&self) -> Vec<String> {
let mut out = self.dual_vars.clone();
for pv in &self.primal_vars {
if !out.contains(pv) {
out.push(pv.clone());
}
}
out
}
pub fn row_dofs(&self) -> Vec<(NodeId, String)> {
self.row_dofs_with(&self.row_support.read())
}
pub(crate) fn row_dofs_with(&self, row_support: &SubMesh) -> Vec<(NodeId, String)> {
let nodes = row_support.connectivity();
let n_nodes = nodes.len();
let n_vars = self.dual_vars.len();
(0..self.coo.nrows())
.map(|i| {
let (nl, vi) = self.ordering.from_index(i, n_nodes, n_vars);
(nodes[nl], self.dual_vars[vi].clone())
})
.collect()
}
pub fn col_dofs(&self) -> Vec<(NodeId, String)> {
self.col_dofs_with(&self.col_support.read())
}
pub(crate) fn col_dofs_with(&self, col_support: &SubMesh) -> Vec<(NodeId, String)> {
let nodes = col_support.connectivity();
let n_nodes = nodes.len();
let n_vars = self.primal_vars.len();
(0..self.coo.ncols())
.map(|i| {
let (nl, vi) = self.ordering.from_index(i, n_nodes, n_vars);
(nodes[nl], self.primal_vars[vi].clone())
})
.collect()
}
pub(crate) fn row_dof_keys(&self, slot_of: &HashMap<String, u32>) -> Vec<DofKey> {
self.row_dof_keys_with(&self.row_support.read(), slot_of)
}
pub(crate) fn row_dof_keys_with(
&self,
row_support: &SubMesh,
slot_of: &HashMap<String, u32>,
) -> Vec<DofKey> {
Self::keys(
row_support.connectivity(),
&self.var_slots(&self.dual_vars, slot_of),
self.ordering,
self.coo.nrows(),
)
}
pub(crate) fn col_dof_keys(&self, slot_of: &HashMap<String, u32>) -> Vec<DofKey> {
self.col_dof_keys_with(&self.col_support.read(), slot_of)
}
pub(crate) fn col_dof_keys_with(
&self,
col_support: &SubMesh,
slot_of: &HashMap<String, u32>,
) -> Vec<DofKey> {
Self::keys(
col_support.connectivity(),
&self.var_slots(&self.primal_vars, slot_of),
self.ordering,
self.coo.ncols(),
)
}
fn var_slots(&self, vars: &[String], slot_of: &HashMap<String, u32>) -> Vec<u32> {
vars.iter()
.map(|v| {
*slot_of.get(v).unwrap_or_else(|| {
panic!("variable '{v}' is absent from the matrix name table")
})
})
.collect()
}
fn keys(nodes: &[NodeId], slots: &[u32], ordering: DofOrdering, n: usize) -> Vec<DofKey> {
let (n_nodes, n_vars) = (nodes.len(), slots.len());
(0..n)
.map(|i| {
let (nl, vi) = ordering.from_index(i, n_nodes, n_vars);
dof_key(nodes[nl], slots[vi])
})
.collect()
}
pub fn add_entry(
&mut self,
row_node: NodeId,
row_var: &str,
col_node: NodeId,
col_var: &str,
value: f64,
) -> Result<()> {
let (row_g, col_g) = self.support_guards();
let row = &row_g;
let col = col_g.as_deref().unwrap_or(&row_g);
self.add_entry_with(row, col, row_node, row_var, col_node, col_var, value)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn add_entry_with(
&mut self,
row_support: &SubMesh,
col_support: &SubMesh,
row_node: NodeId,
row_var: &str,
col_node: NodeId,
col_var: &str,
value: f64,
) -> Result<()> {
if self.is_computed() {
return Err(PyrucastError::Message(
"add_entry: this is a computed block (its values come from its \
recipe at assembly time); literal entries cannot be added"
.into(),
));
}
let n_rn = row_support.connectivity().len();
let n_dv = self.dual_vars.len();
let n_cn = col_support.connectivity().len();
let n_pv = self.primal_vars.len();
let rnl = *row_support.node_index().get(&row_node).ok_or_else(|| {
PyrucastError::Message(format!(
"add_entry: row node {row_node:?} not in row_support"
))
})?;
let rvi = self
.dual_vars
.iter()
.position(|v| v == row_var)
.ok_or_else(|| {
PyrucastError::Message(format!("add_entry: row var '{row_var}' not in dual_vars"))
})?;
let cnl = *col_support.node_index().get(&col_node).ok_or_else(|| {
PyrucastError::Message(format!(
"add_entry: col node {col_node:?} not in col_support"
))
})?;
let cvi = self
.primal_vars
.iter()
.position(|v| v == col_var)
.ok_or_else(|| {
PyrucastError::Message(format!("add_entry: col var '{col_var}' not in primal_vars"))
})?;
let ri = self.ordering.to_index(rnl, rvi, n_rn, n_dv);
let ci = self.ordering.to_index(cnl, cvi, n_cn, n_pv);
self.coo.push(ri, ci, value);
Ok(())
}
pub fn local_triplets(&self) -> impl Iterator<Item = (usize, usize, f64)> + '_ {
self.coo.triplet_iter().map(|(r, c, &v)| (r, c, v))
}
pub fn local_coo_arrays(&self) -> (&[usize], &[usize], &[f64]) {
(
self.coo.row_indices(),
self.coo.col_indices(),
self.coo.values(),
)
}
pub fn coords(&self) -> Handle<Coords> {
self.row_support.read().coords()
}
pub fn get(&self, row_node: NodeId, row_var: &str, col_node: NodeId, col_var: &str) -> f64 {
let (row_g, col_g) = self.support_guards();
self.get_with(
&row_g,
col_g.as_deref().unwrap_or(&row_g),
row_node,
row_var,
col_node,
col_var,
)
}
fn support_guards(&self) -> (ReadGuard<SubMesh>, Option<ReadGuard<SubMesh>>) {
let row = self.row_support.read();
let col = if self.col_support.same_object(&self.row_support) {
None
} else {
Some(self.col_support.read())
};
(row, col)
}
pub(crate) fn get_with(
&self,
row_support: &SubMesh,
col_support: &SubMesh,
row_node: NodeId,
row_var: &str,
col_node: NodeId,
col_var: &str,
) -> f64 {
let n_rn = row_support.connectivity().len();
let n_dv = self.dual_vars.len();
let n_cn = col_support.connectivity().len();
let n_pv = self.primal_vars.len();
let rnl = match row_support.node_index().get(&row_node) {
Some(&i) => i,
None => return 0.0,
};
let rvi = match self.dual_vars.iter().position(|v| v == row_var) {
Some(i) => i,
None => return 0.0,
};
let cnl = match col_support.node_index().get(&col_node) {
Some(&i) => i,
None => return 0.0,
};
let cvi = match self.primal_vars.iter().position(|v| v == col_var) {
Some(i) => i,
None => return 0.0,
};
let ri = self.ordering.to_index(rnl, rvi, n_rn, n_dv);
let ci = self.ordering.to_index(cnl, cvi, n_cn, n_pv);
let raw: f64 = self
.coo
.row_indices()
.iter()
.zip(self.coo.col_indices())
.zip(self.coo.values())
.filter(|&((&r, &c), _)| r == ri && c == ci)
.map(|(_, &v)| v)
.sum();
raw * self.factor
}
pub fn iter_entries(&self) -> Vec<MatrixEntry> {
let (row_g, col_g) = self.support_guards();
self.iter_entries_with(&row_g, col_g.as_deref().unwrap_or(&row_g))
}
pub(crate) fn iter_entries_with(
&self,
row_support: &SubMesh,
col_support: &SubMesh,
) -> Vec<MatrixEntry> {
let row_nodes = row_support.connectivity();
let col_nodes = col_support.connectivity();
let n_rn = row_nodes.len();
let n_dv = self.dual_vars.len();
let n_cn = col_nodes.len();
let n_pv = self.primal_vars.len();
self.coo
.row_indices()
.iter()
.zip(self.coo.col_indices())
.zip(self.coo.values())
.map(|((&ri, &ci), &v)| {
let (rnl, rvi) = self.ordering.from_index(ri, n_rn, n_dv);
let (cnl, cvi) = self.ordering.from_index(ci, n_cn, n_pv);
(
row_nodes[rnl],
self.dual_vars[rvi].clone(),
col_nodes[cnl],
self.primal_vars[cvi].clone(),
v * self.factor,
)
})
.collect()
}
pub fn dense(&self) -> Vec<f64> {
let m = self.to_dmatrix();
let mut out = Vec::with_capacity(m.nrows() * m.ncols());
for i in 0..m.nrows() {
for j in 0..m.ncols() {
out.push(m[(i, j)]);
}
}
out
}
pub fn to_dmatrix(&self) -> DMatrix<f64> {
let nr = self.coo.nrows();
let nc = self.coo.ncols();
let mut out = DMatrix::<f64>::zeros(nr, nc);
for ((&r, &c), &v) in self
.coo
.row_indices()
.iter()
.zip(self.coo.col_indices())
.zip(self.coo.values())
{
out[(r, c)] += v * self.factor;
}
out
}
pub fn to_coo(&self) -> CooMatrix<f64> {
if self.factor == 1.0 {
return self.coo.clone();
}
let mut out = CooMatrix::new(self.coo.nrows(), self.coo.ncols());
for (r, c, &v) in self.coo.triplet_iter() {
out.push(r, c, v * self.factor);
}
out
}
pub fn to_csr(&self) -> CsrMatrix<f64> {
CsrMatrix::from(&self.to_coo())
}
pub fn to_csc(&self) -> CscMatrix<f64> {
CscMatrix::from(&self.to_coo())
}
pub fn mul_dense(&self, x: &[f64]) -> Result<Vec<f64>> {
if x.len() != self.n_cols() {
return Err(PyrucastError::Message(format!(
"mul_dense: x has length {} but sub-matrix has {} columns",
x.len(),
self.n_cols()
)));
}
let csr = self.to_csr();
let x_vec = DVector::<f64>::from_column_slice(x);
let y_vec: DVector<f64> = &csr * &x_vec;
Ok(y_vec.iter().copied().collect())
}
}
#[track_caller]
fn check_divisor(rhs: f64) -> f64 {
assert!(
rhs != 0.0 && rhs.is_finite(),
"matrix division by {rhs}: every value of the result would be non-finite"
);
rhs
}
impl std::ops::Mul<f64> for SubMatrix {
type Output = SubMatrix;
fn mul(mut self, rhs: f64) -> SubMatrix {
self.factor *= rhs;
self
}
}
impl std::ops::Mul<f64> for &SubMatrix {
type Output = SubMatrix;
fn mul(self, rhs: f64) -> SubMatrix {
self.clone() * rhs
}
}
impl std::ops::Mul<SubMatrix> for f64 {
type Output = SubMatrix;
fn mul(self, rhs: SubMatrix) -> SubMatrix {
rhs * self
}
}
impl std::ops::Mul<&SubMatrix> for f64 {
type Output = SubMatrix;
fn mul(self, rhs: &SubMatrix) -> SubMatrix {
rhs * self
}
}
impl std::ops::Div<f64> for SubMatrix {
type Output = SubMatrix;
#[track_caller]
fn div(mut self, rhs: f64) -> SubMatrix {
self.factor /= check_divisor(rhs);
self
}
}
impl std::ops::Div<f64> for &SubMatrix {
type Output = SubMatrix;
#[track_caller]
fn div(self, rhs: f64) -> SubMatrix {
self.clone() / rhs
}
}
impl std::ops::Neg for SubMatrix {
type Output = SubMatrix;
fn neg(self) -> SubMatrix {
self * -1.0
}
}
impl std::ops::Neg for &SubMatrix {
type Output = SubMatrix;
fn neg(self) -> SubMatrix {
self * -1.0
}
}
fn human_bytes(b: usize) -> String {
const UNITS: [&str; 5] = ["B", "kB", "MB", "GB", "TB"];
let mut v = b as f64;
let mut u = 0;
while v >= 1024.0 && u + 1 < UNITS.len() {
v /= 1024.0;
u += 1;
}
if u == 0 {
format!("{b} B")
} else {
format!("{v:.1} {}", UNITS[u])
}
}
impl fmt::Debug for SubMatrix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SubMatrix")
.field("n_rows", &self.coo.nrows())
.field("n_cols", &self.coo.ncols())
.field("entries", &self.coo.nnz())
.field(
"memory",
&crate::aggregate::Unquoted(&human_bytes(self.memory_bytes())),
)
.field("symmetry", &self.symmetry)
.field("dual_vars", &self.dual_vars)
.field("primal_vars", &self.primal_vars)
.field("ordering", &self.ordering)
.field("factor", &self.factor)
.finish()
}
}
impl fmt::Display for SubMatrix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let entries: std::borrow::Cow<str> = if self.is_computed() {
"computed (values from recipe)".into()
} else {
format!("{} entries", self.coo.nnz()).into()
};
let physics: std::borrow::Cow<str> = if self.physics.is_empty() {
"".into()
} else {
let tags: Vec<&str> = self.physics.iter().map(|p| p.name()).collect();
format!(", {}", tags.join("+")).into()
};
let factor: std::borrow::Cow<str> = if self.factor == 1.0 {
"".into()
} else {
format!(", ×{}", self.factor).into()
};
write!(
f,
"SubMatrix: {} row(s) × {} col(s), {}{}{}{}",
self.coo.nrows(),
self.coo.ncols(),
entries,
if self.is_symmetric() {
", symmetric"
} else {
""
},
physics,
factor,
)
}
}
fn dof_label((n, v): &NamedDof) -> String {
format!("({n},{v})")
}
impl crate::dump::Dump for SubMatrix {
fn render(&self, opts: &crate::dump::DumpOptions) -> String {
if self.is_computed() {
let recipe = self.recipe.as_ref().expect("is_computed ⇒ recipe");
return format!(
"{self}\n recipe: submodel {:?}, fespaces {:?}{}\n dual_vars: [{}]\n primal_vars: [{}]",
recipe.submodel,
recipe.fespaces,
recipe
.material
.as_ref()
.map(|m| format!(", material {m:?}"))
.unwrap_or_default(),
self.dual_vars.join(", "),
self.primal_vars.join(", "),
);
}
let row_labels: Vec<String> = self.row_dofs().iter().map(dof_label).collect();
let col_labels: Vec<String> = self.col_dofs().iter().map(dof_label).collect();
let data = self.dense();
format!(
"{self}\n symmetry: {}, ordering: {:?}, factor: {:?}\n dual_vars: [{}], primal_vars: [{}]\n{}",
crate::named::Named::name(self.symmetry),
self.ordering,
self.factor,
self.dual_vars.join(", "),
self.primal_vars.join(", "),
crate::dump::labeled_grid(&row_labels, &col_labels, &data, opts)
)
}
}
mod coo_serde {
use nalgebra_sparse::CooMatrix;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Serialize, Deserialize)]
struct CooData {
nrows: usize,
ncols: usize,
row_indices: Vec<usize>,
col_indices: Vec<usize>,
values: Vec<f64>,
}
pub fn serialize<S: Serializer>(
coo: &CooMatrix<f64>,
s: S,
) -> std::result::Result<S::Ok, S::Error> {
CooData {
nrows: coo.nrows(),
ncols: coo.ncols(),
row_indices: coo.row_indices().to_vec(),
col_indices: coo.col_indices().to_vec(),
values: coo.values().to_vec(),
}
.serialize(s)
}
pub fn deserialize<'de, D: Deserializer<'de>>(
d: D,
) -> std::result::Result<CooMatrix<f64>, D::Error> {
let data = CooData::deserialize(d)?;
let mut coo = CooMatrix::new(data.nrows, data.ncols);
for ((r, c), v) in data
.row_indices
.into_iter()
.zip(data.col_indices)
.zip(data.values)
{
coo.push(r, c, v);
}
Ok(coo)
}
}
pub(crate) struct AssembledCsr {
pub(crate) row_offsets: std::sync::Arc<Vec<usize>>,
pub(crate) col_indices: std::sync::Arc<Vec<usize>>,
pub(crate) values: Vec<f64>,
pub(crate) ncols: usize,
}
impl AssembledCsr {
fn nrows(&self) -> usize {
self.row_offsets.len().saturating_sub(1)
}
fn slot(&self, r: usize, c: usize) -> Option<usize> {
let (lo, hi) = (*self.row_offsets.get(r)?, *self.row_offsets.get(r + 1)?);
self.col_indices[lo..hi]
.binary_search(&c)
.ok()
.map(|k| lo + k)
}
fn triplets(&self) -> impl Iterator<Item = (usize, usize, f64)> + '_ {
(0..self.nrows()).flat_map(move |r| {
let (lo, hi) = (self.row_offsets[r], self.row_offsets[r + 1]);
(lo..hi).map(move |k| (r, self.col_indices[k], self.values[k]))
})
}
fn to_csr(&self) -> Result<CsrMatrix<f64>> {
CsrMatrix::try_from_csr_data(
self.nrows(),
self.ncols,
(*self.row_offsets).clone(),
(*self.col_indices).clone(),
self.values.clone(),
)
.map_err(|e| PyrucastError::Message(format!("to_csr: invalid CSR: {e}")))
}
}
struct AssembledData {
vars: std::sync::Arc<Vec<String>>,
row_keys: std::sync::Arc<Vec<DofKey>>,
col_keys: std::sync::Arc<Vec<DofKey>>,
csr: AssembledCsr,
}
#[derive(Serialize, Deserialize, Default)]
pub struct Matrix {
subs: Vec<Handle<SubMatrix>>,
#[serde(skip)]
assembled: Option<AssembledData>,
#[serde(skip)]
factorization: parking_lot::Mutex<Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>>,
}
crate::impl_aggregate!(Matrix, SubMatrix, sub_matrix, "sub-matrix(es)", {
fn post_push(&mut self) {
self.assembled = None;
*self.factorization.get_mut() = None;
}
fn display_extra(&self) -> Option<String> {
let n_rows = self.n_rows().unwrap_or(0);
let n_cols = self.n_cols().unwrap_or(0);
let sym = self.symmetric();
Some(format!(
", {} row(s) × {} col(s){}, ~{}",
n_rows,
n_cols,
if sym { ", symmetric" } else { "" },
human_bytes(self.memory_bytes())
))
}
});
pub type NamedDof = (NodeId, String);
pub type DofKey = u64;
pub type DofOrder = std::sync::Arc<Vec<DofKey>>;
#[inline]
pub fn dof_key(node: NodeId, var_slot: u32) -> DofKey {
((node.0 as u64) << 32) | var_slot as u64
}
#[inline]
pub fn dof_node(key: DofKey) -> NodeId {
NodeId((key >> 32) as u32)
}
#[inline]
pub fn dof_var(key: DofKey) -> u32 {
(key & 0xffff_ffff) as u32
}
enum DofSeen {
Dense {
flags: Vec<bool>,
n_vars: usize,
},
Sparse(std::collections::HashSet<DofKey>),
}
impl DofSeen {
fn new(max_node: u32, n_vars: usize, n_dofs: usize) -> Self {
let slots = (max_node as usize + 1).saturating_mul(n_vars.max(1));
if slots <= n_dofs.saturating_mul(8).max(1024) {
DofSeen::Dense {
flags: vec![false; slots],
n_vars: n_vars.max(1),
}
} else {
DofSeen::Sparse(std::collections::HashSet::with_capacity(n_dofs))
}
}
#[inline]
fn insert(&mut self, key: DofKey) -> bool {
match self {
DofSeen::Dense { flags, n_vars } => {
let i = dof_node(key).0 as usize * *n_vars + dof_var(key) as usize;
let fresh = !flags[i];
flags[i] = true;
fresh
}
DofSeen::Sparse(set) => set.insert(key),
}
}
}
fn dof_text(key: DofKey, vars: &[String]) -> String {
format!("node {} · {}", dof_node(key).0, vars[dof_var(key) as usize])
}
fn push_conjugate(
seen_row: &mut DofSeen,
seen_col: &mut DofSeen,
out_row: &mut Vec<DofKey>,
out_col: &mut Vec<DofKey>,
vars: &[String],
r: DofKey,
c: DofKey,
) -> Result<()> {
let fresh_row = seen_row.insert(r);
let fresh_col = seen_col.insert(c);
if fresh_row != fresh_col {
return Err(PyrucastError::Message(format!(
"Matrix: {} and {} are declared conjugate, but one of them is already \
paired with another DOF — two blocks disagree on what faces what",
dof_text(r, vars),
dof_text(c, vars)
)));
}
if fresh_row {
out_row.push(r);
out_col.push(c);
}
Ok(())
}
fn conjugate_lengths(rows: usize, cols: usize, what: &str) -> Result<()> {
if rows != cols {
return Err(PyrucastError::Message(format!(
"Matrix: {what} faces {rows} row DOF(s) with {cols} column DOF(s); a block \
declaring symmetry must be square, and the two members of a pair must be \
each other's transpose"
)));
}
Ok(())
}
#[derive(Clone)]
pub struct AssemblyPattern {
pub vars: std::sync::Arc<Vec<String>>,
pub row_keys: std::sync::Arc<Vec<DofKey>>,
pub col_keys: std::sync::Arc<Vec<DofKey>>,
pub row_offsets: std::sync::Arc<Vec<usize>>,
pub col_indices: std::sync::Arc<Vec<usize>>,
pub block_slots: Vec<BlockSlots>,
}
#[derive(Clone)]
pub enum BlockSlots {
Computed { slots: Vec<u32>, stride: usize },
ComputedBlocked {
bases: Vec<u32>,
stride: usize,
n_primal: usize,
},
Literal(Vec<usize>),
}
impl BlockSlots {
pub(crate) fn each_entry(&self, cell: usize, ke: &[f64], mut add: impl FnMut(usize, f64)) {
match self {
BlockSlots::Computed { slots, stride } => {
let base = cell * stride;
for (k, &v) in ke.iter().enumerate() {
add(slots[base + k] as usize, v);
}
}
BlockSlots::ComputedBlocked {
bases,
stride,
n_primal,
} => {
let row = &bases[cell * stride..(cell + 1) * stride];
let mut k = 0;
for &base in row {
for pj in 0..*n_primal {
add(base as usize + pj, ke[k]);
k += 1;
}
}
}
BlockSlots::Literal(_) => {}
}
}
}
impl AssemblyPattern {
#[inline]
pub(crate) fn slot(&self, r: usize, c: usize) -> usize {
let base = self.row_offsets[r];
let seg = &self.col_indices[base..self.row_offsets[r + 1]];
base + seg
.binary_search(&c)
.expect("scatter: entry (r, c) absent from the CSR pattern")
}
pub fn nnz(&self) -> usize {
self.col_indices.len()
}
pub fn row_dofs(&self) -> Vec<NamedDof> {
self.named(&self.row_keys)
}
pub fn col_dofs(&self) -> Vec<NamedDof> {
self.named(&self.col_keys)
}
pub(crate) fn assembled_csr(&self, values: Vec<f64>) -> AssembledCsr {
AssembledCsr {
row_offsets: self.row_offsets.clone(),
col_indices: self.col_indices.clone(),
values,
ncols: self.col_keys.len(),
}
}
fn named(&self, keys: &[DofKey]) -> Vec<NamedDof> {
keys.iter()
.map(|&k| (dof_node(k), self.vars[dof_var(k) as usize].clone()))
.collect()
}
}
fn sort_rows_in_place(pairs: &mut [(usize, f64)], bounds: &[usize]) {
let nrows = bounds.len() - 1;
let base = bounds[0];
const SERIAL_BELOW: usize = 4096;
if nrows <= 1 || pairs.len() < SERIAL_BELOW {
for i in 0..nrows {
pairs[bounds[i] - base..bounds[i + 1] - base].sort_by_key(|&(c, _)| c);
}
return;
}
let mid = nrows / 2;
let (left, right) = pairs.split_at_mut(bounds[mid] - base);
rayon::join(
|| sort_rows_in_place(left, &bounds[..=mid]),
|| sort_rows_in_place(right, &bounds[mid..]),
);
}
#[allow(clippy::type_complexity)]
fn csr_from_triplets_parallel(
nrows: usize,
_ncols: usize,
triplets: Vec<(usize, usize, f64)>,
) -> (Vec<usize>, Vec<usize>, Vec<f64>) {
let nnz = triplets.len();
let mut bounds = vec![0usize; nrows + 1];
for &(r, _, _) in &triplets {
bounds[r + 1] += 1;
}
for r in 0..nrows {
bounds[r + 1] += bounds[r];
}
let mut cursor: Vec<usize> = bounds[..nrows].to_vec();
let mut pairs = vec![(0usize, 0.0f64); nnz];
for (r, c, v) in triplets {
pairs[cursor[r]] = (c, v);
cursor[r] += 1;
}
sort_rows_in_place(&mut pairs, &bounds);
let mut row_offsets = vec![0usize; nrows + 1];
let mut col_indices: Vec<usize> = Vec::with_capacity(nnz);
let mut values: Vec<f64> = Vec::with_capacity(nnz);
for r in 0..nrows {
let mut last_col: Option<usize> = None;
for &(c, v) in &pairs[bounds[r]..bounds[r + 1]] {
if last_col == Some(c) {
*values.last_mut().unwrap() += v;
} else {
col_indices.push(c);
values.push(v);
row_offsets[r + 1] += 1;
last_col = Some(c);
}
}
}
for r in 0..nrows {
row_offsets[r + 1] += row_offsets[r];
}
(row_offsets, col_indices, values)
}
impl Matrix {
pub fn finalize(&mut self) -> Result<()> {
if self.assembled.is_some() {
return Ok(());
}
for h in &*self {
if h.read().is_computed() {
return Err(PyrucastError::Message(
"Matrix::finalize: this matrix carries a computed block; \
assemble it with m.assemble() (or \
ops::matrix::stiffness), which scatters the kernel into \
the global CSR — finalize() cannot (it must not reach into \
the model/kernel)"
.into(),
));
}
}
let vars = std::sync::Arc::new(self.field_names());
let (row_keys, col_keys) = self.dof_orders(&vars)?;
let triplets = self.build_global_triplets(&vars, &row_keys, &col_keys)?;
let (row_offsets, col_indices, values) =
csr_from_triplets_parallel(row_keys.len(), col_keys.len(), triplets);
let csr = AssembledCsr {
row_offsets: std::sync::Arc::new(row_offsets),
col_indices: std::sync::Arc::new(col_indices),
values,
ncols: col_keys.len(),
};
self.assembled = Some(AssembledData {
vars,
row_keys: std::sync::Arc::new(row_keys),
col_keys: std::sync::Arc::new(col_keys),
csr,
});
Ok(())
}
pub(crate) fn set_assembled(
&mut self,
vars: std::sync::Arc<Vec<String>>,
row_keys: std::sync::Arc<Vec<DofKey>>,
col_keys: std::sync::Arc<Vec<DofKey>>,
csr: AssembledCsr,
) {
self.assembled = Some(AssembledData {
vars,
row_keys,
col_keys,
csr,
});
}
fn assembled_or_err(&self) -> Result<&AssembledData> {
self.assembled.as_ref().ok_or_else(|| {
PyrucastError::Message(
"Matrix has not been finalized; call finalize() before solving".into(),
)
})
}
pub fn cached_factorization<T: std::any::Any + Send + Sync>(
&self,
) -> Option<std::sync::Arc<T>> {
let arc = self.factorization.lock().as_ref().cloned()?;
arc.downcast::<T>().ok()
}
pub fn store_factorization(
&self,
factorization: std::sync::Arc<dyn std::any::Any + Send + Sync>,
) {
*self.factorization.lock() = Some(factorization);
}
fn collect_dof_keys(&self, row: bool, vars: &[String]) -> Result<Vec<DofKey>> {
let slot_of: HashMap<String, u32> = vars
.iter()
.cloned()
.enumerate()
.map(|(i, v)| (v, i as u32))
.collect();
let (mut total, mut max_node) = (0usize, 0u32);
for h in self {
let sub = h.read();
let support = if row {
sub.row_support().read()
} else {
sub.col_support().read()
};
total += if row { sub.n_rows() } else { sub.n_cols() };
for n in support.connectivity() {
max_node = max_node.max(n.0);
}
}
let mut seen = DofSeen::new(max_node, vars.len(), total);
let mut out: Vec<DofKey> = Vec::with_capacity(total);
for h in self {
let sub = h.read();
let keys = if row {
sub.row_dof_keys_with(&sub.row_support().read(), &slot_of)
} else {
sub.col_dof_keys_with(&sub.col_support().read(), &slot_of)
};
for k in keys {
if seen.insert(k) {
out.push(k);
}
}
}
if let Some(first) = self.iter().next() {
let coords_h = first.read().coords();
if let Some(perm) = coords_h.read().permutation() {
out.par_sort_by_key(|&k| perm[dof_node(k).0 as usize]);
}
}
Ok(out)
}
fn dof_orders(&self, vars: &[String]) -> Result<(Vec<DofKey>, Vec<DofKey>)> {
if self.symmetric() {
self.collect_conjugate_dof_keys(vars)
} else {
Ok((
self.collect_dof_keys(true, vars)?,
self.collect_dof_keys(false, vars)?,
))
}
}
fn collect_conjugate_dof_keys(&self, vars: &[String]) -> Result<(Vec<DofKey>, Vec<DofKey>)> {
let slot_of: HashMap<String, u32> = vars
.iter()
.cloned()
.enumerate()
.map(|(i, v)| (v, i as u32))
.collect();
let (mut total, mut max_node) = (0usize, 0u32);
for h in self {
let sub = h.read();
total += sub.n_rows();
for support in [sub.row_support(), sub.col_support()] {
for n in support.read().connectivity() {
max_node = max_node.max(n.0);
}
}
}
let mut seen_row = DofSeen::new(max_node, vars.len(), total);
let mut seen_col = DofSeen::new(max_node, vars.len(), total);
let mut out_row: Vec<DofKey> = Vec::with_capacity(total);
let mut out_col: Vec<DofKey> = Vec::with_capacity(total);
let mut consumed = vec![false; self.len()];
for (i, h) in self.iter().enumerate() {
if consumed[i] {
continue;
}
let a = h.read();
let a_rows = {
let g = a.row_support().read();
a.row_dof_keys_with(&g, &slot_of)
};
let a_cols = {
let g = a.col_support().read();
a.col_dof_keys_with(&g, &slot_of)
};
match a.symmetry() {
Symmetry::Full => {
conjugate_lengths(a_rows.len(), a_cols.len(), "a Full block")?;
for (&r, &c) in a_rows.iter().zip(a_cols.iter()) {
push_conjugate(
&mut seen_row,
&mut seen_col,
&mut out_row,
&mut out_col,
vars,
r,
c,
)?;
}
}
Symmetry::Half(id) => {
let partner = self.iter().enumerate().position(|(j, g)| {
j != i
&& !consumed[j]
&& matches!(g.read().symmetry(),
Symmetry::Half(o) if o & !1 == id & !1 && o & 1 != id & 1)
});
let Some(j) = partner else {
return Err(PyrucastError::Message(
"Matrix: a Half block has no partner in this matrix, so the two \
DOF orders cannot be paired — the symmetry declaration and the \
blocks disagree"
.into(),
));
};
let p = self.iter().nth(j).expect("index from position").read();
let p_rows = {
let g = p.row_support().read();
p.row_dof_keys_with(&g, &slot_of)
};
let p_cols = {
let g = p.col_support().read();
p.col_dof_keys_with(&g, &slot_of)
};
conjugate_lengths(a_rows.len(), p_cols.len(), "a Half pair")?;
conjugate_lengths(p_rows.len(), a_cols.len(), "a Half pair")?;
for (&r, &c) in a_rows.iter().zip(p_cols.iter()) {
push_conjugate(
&mut seen_row,
&mut seen_col,
&mut out_row,
&mut out_col,
vars,
r,
c,
)?;
}
for (&r, &c) in p_rows.iter().zip(a_cols.iter()) {
push_conjugate(
&mut seen_row,
&mut seen_col,
&mut out_row,
&mut out_col,
vars,
r,
c,
)?;
}
consumed[j] = true;
}
Symmetry::None => unreachable!("a None block cannot reach the conjugate walk"),
}
}
if let Some(first) = self.iter().next() {
let coords_h = first.read().coords();
if let Some(perm) = coords_h.read().permutation() {
let mut pairs: Vec<(DofKey, DofKey)> = out_row.into_iter().zip(out_col).collect();
pairs.par_sort_by_key(|&(r, _)| perm[dof_node(r).0 as usize]);
(out_row, out_col) = pairs.into_iter().unzip();
}
}
Ok((out_row, out_col))
}
fn name_dofs(keys: &[DofKey], vars: &[String]) -> Vec<NamedDof> {
keys.iter()
.map(|&k| (dof_node(k), vars[dof_var(k) as usize].clone()))
.collect()
}
fn build_global_triplets(
&self,
vars: &[String],
row_keys: &[DofKey],
col_keys: &[DofKey],
) -> Result<Vec<(usize, usize, f64)>> {
let slot_of: HashMap<String, u32> = vars
.iter()
.cloned()
.enumerate()
.map(|(i, v)| (v, i as u32))
.collect();
let row_map: HashMap<DofKey, usize> =
row_keys.iter().enumerate().map(|(i, &k)| (k, i)).collect();
let col_map: HashMap<DofKey, usize> =
col_keys.iter().enumerate().map(|(i, &k)| (k, i)).collect();
let mut out: Vec<(usize, usize, f64)> = Vec::new();
for h in self {
let sub = h.read();
let trow: Vec<usize> = sub
.row_dof_keys(&slot_of)
.iter()
.map(|k| row_map[k])
.collect();
let tcol: Vec<usize> = sub
.col_dof_keys(&slot_of)
.iter()
.map(|k| col_map[k])
.collect();
let (lr, lc, lv) = sub.local_coo_arrays();
let factor = sub.factor();
let block: Vec<(usize, usize, f64)> = (0..lv.len())
.into_par_iter()
.with_min_len(MIN_PARALLEL_LEN)
.map(|k| (trow[lr[k]], tcol[lc[k]], lv[k] * factor))
.collect();
if out.is_empty() {
out = block;
} else {
out.extend(block);
}
}
Ok(out)
}
pub fn symmetric(&self) -> bool {
let mut pairs: Vec<(PairId, [usize; 2])> = Vec::new();
for h in self {
match h.read().symmetry() {
Symmetry::Full => {}
Symmetry::None => return false,
Symmetry::Half(id) => {
let (base, member) = (id & !1, (id & 1) as usize);
match pairs.iter_mut().find(|(b, _)| *b == base) {
Some((_, seen)) => seen[member] += 1,
None => {
let mut seen = [0usize; 2];
seen[member] = 1;
pairs.push((base, seen));
}
}
}
}
}
if pairs.iter().any(|(_, seen)| seen[0] != seen[1]) {
return false;
}
debug_assert!(
self.pairs_are_mutual_transposes(),
"a Half group holds blocks that are not each other's transpose — \
two distinct pairs hashed alike, or a pair was minted wrongly"
);
true
}
fn pairs_are_mutual_transposes(&self) -> bool {
let halves: Vec<_> = self
.iter()
.filter_map(|h| match h.read().symmetry() {
Symmetry::Half(id) => Some((id & !1, h)),
_ => None,
})
.collect();
halves.iter().all(|(base, h)| {
let a = h.read();
halves.iter().any(|(other_base, g)| {
if other_base != base || Handle::same_object(h, g) {
return false;
}
let b = g.read();
Handle::same_object(a.row_support(), b.col_support())
&& Handle::same_object(a.col_support(), b.row_support())
})
})
}
pub fn row_dofs(&self) -> Result<Vec<NamedDof>> {
let vars = self.dof_vars();
Ok(Self::name_dofs(&self.row_dof_keys()?, &vars))
}
pub fn col_dofs(&self) -> Result<Vec<NamedDof>> {
let vars = self.dof_vars();
Ok(Self::name_dofs(&self.col_dof_keys()?, &vars))
}
pub fn dof_vars(&self) -> std::sync::Arc<Vec<String>> {
if let Some(a) = &self.assembled {
return a.vars.clone();
}
std::sync::Arc::new(self.field_names())
}
pub fn row_dof_keys(&self) -> Result<DofOrder> {
if let Some(a) = &self.assembled {
return Ok(a.row_keys.clone());
}
Ok(self.dof_key_orders()?.0)
}
pub(crate) fn dof_key_orders(&self) -> Result<(DofOrder, DofOrder)> {
if let Some(a) = &self.assembled {
return Ok((a.row_keys.clone(), a.col_keys.clone()));
}
let vars = self.field_names();
let (row, col) = self.dof_orders(&vars)?;
Ok((std::sync::Arc::new(row), std::sync::Arc::new(col)))
}
pub fn col_dof_keys(&self) -> Result<DofOrder> {
if let Some(a) = &self.assembled {
return Ok(a.col_keys.clone());
}
Ok(self.dof_key_orders()?.1)
}
pub fn field_names(&self) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for h in self {
for name in h.read().field_names() {
if !out.contains(&name) {
out.push(name);
}
}
}
out
}
pub fn n_rows(&self) -> Result<usize> {
Ok(self.row_dof_keys()?.len())
}
pub fn n_cols(&self) -> Result<usize> {
Ok(self.col_dof_keys()?.len())
}
pub fn entry_count(&self) -> usize {
let mut total = 0usize;
for h in self {
total += h.read().entry_count();
}
total
}
pub fn memory_bytes(&self) -> usize {
let mut total = 0usize;
for h in self {
total += h.read().memory_bytes();
}
if let Some(a) = &self.assembled {
let word = std::mem::size_of::<usize>();
total += a.csr.row_offsets.len() * word
+ a.csr.col_indices.len() * word
+ a.csr.values.len() * std::mem::size_of::<f64>()
+ (a.row_keys.len() + a.col_keys.len()) * std::mem::size_of::<DofKey>();
}
total
}
pub fn get(&self, row_node: NodeId, row_field: &str, col_node: NodeId, col_field: &str) -> f64 {
if let Some(a) = &self.assembled {
let slot = |name: &str| a.vars.iter().position(|v| v == name).map(|i| i as u32);
let find = |keys: &[DofKey], node: NodeId, name: &str| {
slot(name).and_then(|s| keys.iter().position(|&k| k == dof_key(node, s)))
};
let r = find(&a.row_keys, row_node, row_field);
let c = find(&a.col_keys, col_node, col_field);
return match (r, c) {
(Some(r), Some(c)) => a.csr.slot(r, c).map_or(0.0, |k| a.csr.values[k]),
_ => 0.0,
};
}
let mut total = 0.0;
for h in self {
total += h.read().get(row_node, row_field, col_node, col_field);
}
total
}
pub fn iter_entries(&self) -> Vec<MatrixEntry> {
let mut out = Vec::new();
for h in self {
out.extend(h.read().iter_entries());
}
out
}
pub fn to_csr(&self) -> Result<CsrMatrix<f64>> {
self.assembled_or_err()?.csr.to_csr()
}
pub fn csr_arrays(&self) -> Result<(&[usize], &[usize], &[f64])> {
let a = self.assembled_or_err()?;
Ok((&a.csr.row_offsets, &a.csr.col_indices, &a.csr.values))
}
pub fn to_dmatrix(&self) -> Result<DMatrix<f64>> {
let a = self.assembled_or_err()?;
let nr = a.row_keys.len();
let nc = a.col_keys.len();
let mut out = DMatrix::<f64>::zeros(nr, nc);
for (r, c, v) in a.csr.triplets() {
out[(r, c)] += v;
}
Ok(out)
}
pub fn dense(&self) -> Result<Vec<f64>> {
let m = self.to_dmatrix()?;
let mut out = Vec::with_capacity(m.nrows() * m.ncols());
for i in 0..m.nrows() {
for j in 0..m.ncols() {
out.push(m[(i, j)]);
}
}
Ok(out)
}
pub fn to_coo(&self) -> Result<CooMatrix<f64>> {
let a = self.assembled_or_err()?;
let mut coo = CooMatrix::<f64>::new(a.row_keys.len(), a.col_keys.len());
for (r, c, v) in a.csr.triplets() {
coo.push(r, c, v);
}
Ok(coo)
}
pub fn to_csc(&self) -> Result<CscMatrix<f64>> {
Ok(CscMatrix::from(&self.assembled_or_err()?.csr.to_csr()?))
}
pub fn mul_dense(&self, x: &[f64]) -> Result<Vec<f64>> {
let a = self.assembled_or_err()?;
let nc = a.col_keys.len();
if x.len() != nc {
return Err(PyrucastError::Message(format!(
"mul_dense: x has length {} but matrix has {} columns",
x.len(),
nc
)));
}
let (offsets, cols, vals) = (&a.csr.row_offsets, &a.csr.col_indices, &a.csr.values);
let mut y = vec![0.0f64; a.csr.nrows()];
y.par_iter_mut()
.with_min_len(MIN_PARALLEL_LEN)
.enumerate()
.for_each(|(r, out)| {
let (lo, hi) = (offsets[r], offsets[r + 1]);
*out = (lo..hi).map(|k| vals[k] * x[cols[k]]).sum();
});
Ok(y)
}
pub fn row_mesh(&self) -> Result<Mesh> {
self.support_mesh(true)
}
pub fn col_mesh(&self) -> Result<Mesh> {
self.support_mesh(false)
}
pub fn filter(&self, physics: Physics) -> Matrix {
let mut out = Matrix::empty();
for h in self {
if h.read().physics().contains(&physics) {
out.push(h.clone());
}
}
out.post_push();
out
}
pub fn physics(&self) -> Vec<Physics> {
let mut out: Vec<Physics> = Vec::new();
for h in self {
for &p in h.read().physics() {
if !out.contains(&p) {
out.push(p);
}
}
}
out
}
fn support_mesh(&self, rows: bool) -> Result<Mesh> {
let mut out = Mesh::empty();
for h in self {
let s = h.read();
let sup = if rows {
s.row_support.clone()
} else {
s.col_support.clone()
};
if !out.iter().any(|m| m.same_object(&sup)) {
out.add_sub(sup)?;
}
}
Ok(out)
}
pub fn field_from_col_values(&self, x: &[f64]) -> Result<NodeField> {
self.field_from_flat_values(x, false)
}
pub fn field_from_row_values(&self, y: &[f64]) -> Result<NodeField> {
self.field_from_flat_values(y, true)
}
fn field_from_flat_values(&self, values: &[f64], rows: bool) -> Result<NodeField> {
let a = self.assembled_or_err()?;
let keys = if rows { &a.row_keys } else { &a.col_keys };
if values.len() != keys.len() {
return Err(PyrucastError::Message(format!(
"field_from_{}_values: {} value(s) for {} DOF(s)",
if rows { "row" } else { "col" },
values.len(),
keys.len()
)));
}
let index: HashMap<DofKey, usize> = keys.iter().enumerate().map(|(i, &k)| (k, i)).collect();
let slot_of: HashMap<&str, u32> = a
.vars
.iter()
.enumerate()
.map(|(i, v)| (v.as_str(), i as u32))
.collect();
struct Group {
support: Handle<SubMesh>,
vars: Vec<String>,
}
let mut groups: Vec<Group> = Vec::new();
for h in self {
let s = h.read();
let (support, vars) = if rows {
(s.row_support().clone(), s.dual_vars())
} else {
(s.col_support().clone(), s.primal_vars())
};
match groups.iter_mut().find(|g| g.support.same_object(&support)) {
Some(g) => {
for v in vars {
if !g.vars.contains(v) {
g.vars.push(v.clone());
}
}
}
None => groups.push(Group {
support,
vars: vars.to_vec(),
}),
}
}
let mut out = NodeField::default();
for g in &groups {
use crate::containers::field::SubField;
let mut sub = SubNodeField::from_poi1(&g.support, g.vars.clone())?;
let ncomp = g.vars.len();
let vals = sub.values_mut();
let slots: Vec<Option<u32>> = g
.vars
.iter()
.map(|v| slot_of.get(v.as_str()).copied())
.collect();
let support = g.support.read();
for (ni, nid) in support.connectivity().iter().enumerate() {
for (ci, slot) in slots.iter().enumerate() {
let Some(slot) = slot else { continue };
if let Some(&gi) = index.get(&dof_key(*nid, *slot)) {
vals[ni * ncomp + ci] = values[gi];
}
}
}
drop(support);
out.add_sub(Handle::new(sub))?;
}
Ok(out)
}
pub fn mul_field(&self, x_field: &NodeField) -> Result<NodeField> {
let x = x_field.gather(&self.col_dofs()?)?;
let y = self.mul_dense(&x)?;
self.field_from_row_values(&y)
}
fn map_blocks(&self, f: impl Fn(SubMatrix) -> SubMatrix) -> Matrix {
let mut out = Matrix::empty();
for h in self {
let mapped = f((*h.read()).clone());
out.push(Handle::new(mapped));
}
out.post_push();
out
}
fn scaled(&self, f: impl Fn(f64) -> f64) -> Matrix {
let mut out = self.map_blocks(|mut b| {
b.factor = f(b.factor);
b
});
out.assembled = self.assembled.as_ref().map(|a| AssembledData {
vars: a.vars.clone(),
row_keys: a.row_keys.clone(),
col_keys: a.col_keys.clone(),
csr: AssembledCsr {
row_offsets: a.csr.row_offsets.clone(),
col_indices: a.csr.col_indices.clone(),
values: a.csr.values.iter().map(|&v| f(v)).collect(),
ncols: a.csr.ncols,
},
});
out
}
fn scale_in_place(&mut self, f: impl Fn(f64) -> f64) {
for h in self.items_mut() {
if h.is_sole_owner() {
let mut blk = h.write();
blk.factor = f(blk.factor);
} else {
let mut blk = (*h.read()).clone();
blk.factor = f(blk.factor);
*h = Handle::new(blk);
}
}
if let Some(a) = &mut self.assembled {
for v in &mut a.csr.values {
*v = f(*v);
}
}
*self.factorization.get_mut() = None;
}
fn concat(&self, other: &Matrix) -> Matrix {
let mut out = Matrix::empty();
for h in self.iter().chain(other.iter()) {
out.push(h.clone());
}
out.post_push();
out
}
}
impl std::ops::Mul<&NodeField> for &Matrix {
type Output = Result<NodeField>;
fn mul(self, rhs: &NodeField) -> Self::Output {
self.mul_field(rhs)
}
}
impl std::ops::Mul<&NodeField> for Matrix {
type Output = Result<NodeField>;
fn mul(self, rhs: &NodeField) -> Self::Output {
self.mul_field(rhs)
}
}
impl std::ops::Mul<f64> for &Matrix {
type Output = Matrix;
fn mul(self, rhs: f64) -> Self::Output {
self.scaled(|v| v * rhs)
}
}
impl std::ops::Mul<f64> for Matrix {
type Output = Matrix;
fn mul(mut self, rhs: f64) -> Self::Output {
self.scale_in_place(|v| v * rhs);
self
}
}
impl std::ops::Mul<Matrix> for f64 {
type Output = Matrix;
fn mul(self, rhs: Matrix) -> Matrix {
rhs * self
}
}
impl std::ops::Mul<&Matrix> for f64 {
type Output = Matrix;
fn mul(self, rhs: &Matrix) -> Matrix {
rhs * self
}
}
impl std::ops::Div<f64> for &Matrix {
type Output = Matrix;
#[track_caller]
fn div(self, rhs: f64) -> Self::Output {
let d = check_divisor(rhs);
self.scaled(|v| v / d)
}
}
impl std::ops::Div<f64> for Matrix {
type Output = Matrix;
#[track_caller]
fn div(mut self, rhs: f64) -> Self::Output {
let d = check_divisor(rhs);
self.scale_in_place(|v| v / d);
self
}
}
impl std::ops::Neg for &Matrix {
type Output = Matrix;
fn neg(self) -> Matrix {
self.scaled(|v| -v)
}
}
impl std::ops::Neg for Matrix {
type Output = Matrix;
fn neg(mut self) -> Matrix {
self.scale_in_place(|v| -v);
self
}
}
impl SubMatrix {
fn as_matrix(&self) -> Matrix {
let mut out = Matrix::empty();
out.push(Handle::new(self.clone()));
out.post_push();
out
}
fn as_negated_matrix(&self) -> Matrix {
(-self).as_matrix()
}
}
macro_rules! forward_ref_binop {
($trait:ident, $method:ident, $lhs:ty, $rhs:ty) => {
impl std::ops::$trait<$rhs> for &$lhs {
type Output = Matrix;
fn $method(self, rhs: $rhs) -> Matrix {
std::ops::$trait::$method(self, &rhs)
}
}
impl std::ops::$trait<&$rhs> for $lhs {
type Output = Matrix;
fn $method(self, rhs: &$rhs) -> Matrix {
std::ops::$trait::$method(&self, rhs)
}
}
impl std::ops::$trait<$rhs> for $lhs {
type Output = Matrix;
fn $method(self, rhs: $rhs) -> Matrix {
std::ops::$trait::$method(&self, &rhs)
}
}
};
}
impl std::ops::Add<&Matrix> for &Matrix {
type Output = Matrix;
fn add(self, rhs: &Matrix) -> Matrix {
self.concat(rhs)
}
}
impl std::ops::Sub<&Matrix> for &Matrix {
type Output = Matrix;
fn sub(self, rhs: &Matrix) -> Matrix {
self.concat(&rhs.map_blocks(|b| -b))
}
}
impl std::ops::Add<&SubMatrix> for &Matrix {
type Output = Matrix;
fn add(self, rhs: &SubMatrix) -> Matrix {
self.concat(&rhs.as_matrix())
}
}
impl std::ops::Sub<&SubMatrix> for &Matrix {
type Output = Matrix;
fn sub(self, rhs: &SubMatrix) -> Matrix {
self.concat(&rhs.as_negated_matrix())
}
}
impl std::ops::Add<&Matrix> for &SubMatrix {
type Output = Matrix;
fn add(self, rhs: &Matrix) -> Matrix {
self.as_matrix().concat(rhs)
}
}
impl std::ops::Sub<&Matrix> for &SubMatrix {
type Output = Matrix;
fn sub(self, rhs: &Matrix) -> Matrix {
self.as_matrix().concat(&rhs.map_blocks(|b| -b))
}
}
impl std::ops::Add<&SubMatrix> for &SubMatrix {
type Output = Matrix;
fn add(self, rhs: &SubMatrix) -> Matrix {
self.as_matrix().concat(&rhs.as_matrix())
}
}
impl std::ops::Sub<&SubMatrix> for &SubMatrix {
type Output = Matrix;
fn sub(self, rhs: &SubMatrix) -> Matrix {
self.as_matrix().concat(&rhs.as_negated_matrix())
}
}
forward_ref_binop!(Add, add, Matrix, Matrix);
forward_ref_binop!(Sub, sub, Matrix, Matrix);
forward_ref_binop!(Add, add, Matrix, SubMatrix);
forward_ref_binop!(Sub, sub, Matrix, SubMatrix);
forward_ref_binop!(Add, add, SubMatrix, Matrix);
forward_ref_binop!(Sub, sub, SubMatrix, Matrix);
forward_ref_binop!(Add, add, SubMatrix, SubMatrix);
forward_ref_binop!(Sub, sub, SubMatrix, SubMatrix);
impl crate::dump::Dump for Matrix {
fn render(&self, opts: &crate::dump::DumpOptions) -> String {
let grid = (|| -> Result<String> {
let (row_dofs, col_dofs, data) = if let Some(a) = &self.assembled {
let nc = a.col_keys.len();
let mut data = vec![0.0f64; a.row_keys.len() * nc];
for (r, c, v) in a.csr.triplets() {
data[r * nc + c] = v;
}
(
Self::name_dofs(&a.row_keys, &a.vars),
Self::name_dofs(&a.col_keys, &a.vars),
data,
)
} else {
let vars = self.field_names();
let (row_keys, col_keys) = self.dof_orders(&vars)?;
let triplets = self.build_global_triplets(&vars, &row_keys, &col_keys)?;
let row_dofs = Self::name_dofs(&row_keys, &vars);
let col_dofs = Self::name_dofs(&col_keys, &vars);
let nc = col_dofs.len();
let mut data = vec![0.0f64; row_dofs.len() * nc];
for (r, c, v) in triplets {
data[r * nc + c] += v;
}
(row_dofs, col_dofs, data)
};
let row_labels: Vec<String> = row_dofs.iter().map(dof_label).collect();
let col_labels: Vec<String> = col_dofs.iter().map(dof_label).collect();
Ok(crate::dump::labeled_grid(
&row_labels,
&col_labels,
&data,
opts,
))
})();
match grid {
Ok(g) => format!("{self}\n{g}"),
Err(e) => format!("{self}\n<{e}>"),
}
}
}
impl crate::archive::Archivable for SubMatrix {
const TAG: &'static str = "SubMatrix";
}
impl crate::archive::Archivable for Matrix {
const TAG: &'static str = "Matrix";
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aggregate::Aggregate;
use crate::atoms::ElementType;
use crate::atoms::Node;
use crate::coords::Coords;
use crate::handle::Handle;
fn make_poi1(n: usize) -> (Handle<Coords>, Vec<Node>, Handle<SubMesh>) {
let coords = Handle::new(Coords::new(1).unwrap());
let nodes: Vec<Node> = (0..n)
.map(|i| Node::create_in(coords.clone(), &[i as f64]).unwrap())
.collect();
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
for node in &nodes {
sm.add_cell(&[node.id()]).unwrap();
}
(coords, nodes, Handle::new(sm))
}
fn make_poi1_repeated(n: usize) -> (Handle<Coords>, Vec<Node>, Handle<SubMesh>) {
let coords = Handle::new(Coords::new(1).unwrap());
let nodes: Vec<Node> = (0..n)
.map(|i| Node::create_in(coords.clone(), &[i as f64]).unwrap())
.collect();
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[nodes[0].id()]).unwrap();
for node in &nodes[1..] {
sm.add_cell(&[node.id()]).unwrap();
sm.add_cell(&[nodes[0].id()]).unwrap();
}
(coords, nodes, Handle::new(sm))
}
#[test]
fn node_index_is_the_flat_position_only_on_a_deduplicated_support() {
let (_c, nodes, sup) = make_poi1(4);
let guard = sup.read();
for (position, nid) in guard.connectivity().iter().enumerate() {
assert_eq!(
guard.node_index()[nid],
position,
"deduplicated support: rank and position must agree on {nid:?}"
);
}
assert_eq!(guard.node_index().len(), nodes.len());
drop(guard);
let (_c2, nodes2, sup2) = make_poi1_repeated(3);
let guard2 = sup2.read();
assert_eq!(guard2.connectivity().len(), 5);
assert_eq!(guard2.node_index()[&nodes2[1].id()], 1);
assert_eq!(guard2.connectivity()[3], nodes2[2].id());
assert_eq!(guard2.node_index()[&nodes2[2].id()], 2);
}
#[test]
fn empty_sub_matrix() {
let (_cfg, _nodes, sup) = make_poi1(2);
let m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
assert_eq!(m.n_rows(), 2);
assert_eq!(m.n_cols(), 2);
assert_eq!(m.entry_count(), 0);
assert!(!m.is_symmetric());
}
#[test]
fn symmetry_round_trips_through_serde() {
let (left, right) = mint_pair(0x1234_5678_9abc_def0);
for declared in [Symmetry::Full, Symmetry::None, Symmetry::Half(left)] {
let bytes =
bincode::serde::encode_to_vec(declared, bincode::config::standard()).unwrap();
let (back, _): (Symmetry, usize) =
bincode::serde::decode_from_slice(&bytes, bincode::config::standard()).unwrap();
assert_eq!(back, declared, "{declared:?} did not survive");
}
assert_ne!(left, right);
}
#[test]
fn mint_pair_splits_one_content_in_two() {
let (a, b) = mint_pair(0xdead_beef_0000_1111);
assert_ne!(a, b);
assert_eq!(a & !1, b & !1, "both halves name the same pair");
assert_eq!(a & 1, 0);
assert_eq!(b & 1, 1);
assert_eq!(mint_pair(0xdead_beef_0000_1111), (a, b));
let mut h = FNV_SEED;
h = hash_name(h, "T");
let mut other = FNV_SEED;
other = hash_name(other, "P");
assert_ne!(mint_pair(h).0 & !1, mint_pair(other).0 & !1);
}
#[test]
fn a_half_counts_only_with_its_other_half() {
let (coords, nodes, _) = make_poi1(2);
let (a, m) = (nodes[0].id(), nodes[1].id());
let one = |n: NodeId| {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[n]).unwrap();
Handle::new(sm)
};
let (sup_a, sup_m) = (one(a), one(m));
let (id_c, id_ct) = mint_pair(0x5555_5555_5555_5555);
let c = SubMatrix::new(
sup_m.clone(),
sup_a.clone(),
vec!["imposed_T".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Half(id_c),
);
let ct = SubMatrix::new(
sup_a,
sup_m,
vec!["T".into()],
vec!["imposed_T".into()],
DofOrdering::NodesThenVars,
Symmetry::Half(id_ct),
);
assert!(!c.is_symmetric(), "a half is not symmetric on its own");
let mut both = Matrix::empty();
both.add_sub(Handle::new(c)).unwrap();
both.add_sub(Handle::new(ct)).unwrap();
assert!(both.symmetric(), "the pair is complete");
let halved = both.subset([0]).unwrap();
assert!(!halved.symmetric(), "one half alone carries no symmetry");
}
#[test]
fn add_entry_and_field_names() {
let (_cfg, nodes, sup) = make_poi1(2);
let (a, b) = (nodes[0].id(), nodes[1].id());
let mut m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
m.add_entry(a, "q", a, "T", 2.0).unwrap();
m.add_entry(a, "q", b, "T", -1.0).unwrap();
m.add_entry(b, "q", a, "T", -1.0).unwrap();
m.add_entry(b, "q", b, "T", 2.0).unwrap();
assert_eq!(m.field_names().len(), 2);
assert_eq!(m.n_rows(), 2);
assert_eq!(m.n_cols(), 2);
assert_eq!(m.entry_count(), 4);
}
#[test]
fn get_unknown_returns_zero() {
let (_cfg, nodes, sup) = make_poi1(1);
let m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
assert_eq!(m.get(nodes[0].id(), "x", nodes[0].id(), "y"), 0.0);
}
#[test]
fn get_sums_duplicates() {
let (_cfg, nodes, sup) = make_poi1(1);
let a = nodes[0].id();
let mut m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
m.add_entry(a, "q", a, "T", 2.0).unwrap();
m.add_entry(a, "q", a, "T", 1.5).unwrap();
m.add_entry(a, "q", a, "T", -0.5).unwrap();
assert_eq!(m.get(a, "q", a, "T"), 3.0);
}
#[test]
fn dense_matches_get() {
let (_cfg, nodes, sup) = make_poi1(2);
let (a, b) = (nodes[0].id(), nodes[1].id());
let mut m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
m.add_entry(a, "q", a, "T", 2.0).unwrap();
m.add_entry(a, "q", b, "T", -1.0).unwrap();
m.add_entry(b, "q", a, "T", -1.0).unwrap();
m.add_entry(b, "q", b, "T", 2.0).unwrap();
assert_eq!(m.dense(), vec![2.0, -1.0, -1.0, 2.0]);
}
#[test]
fn dump_labels_grid_with_dofs() {
use crate::dump::{Dump, DumpOptions};
let (_cfg, nodes, sup) = make_poi1(2);
let (a, b) = (nodes[0].id(), nodes[1].id());
let mut m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
m.add_entry(a, "q", a, "T", 2.0).unwrap();
m.add_entry(a, "q", b, "T", -1.0).unwrap();
m.add_entry(b, "q", a, "T", -1.0).unwrap();
m.add_entry(b, "q", b, "T", 2.0).unwrap();
let s = m.render(&DumpOptions::default());
let mut lines = s.lines();
assert_eq!(
lines.next().unwrap(),
"SubMatrix: 2 row(s) × 2 col(s), 4 entries"
);
assert!(s.contains(&format!("({a},q)")), "row label:\n{s}");
assert!(s.contains(&format!("({a},T)")), "col label:\n{s}");
assert!(s.contains("2.000") && s.contains("-1.000"), "values:\n{s}");
assert_eq!(
s.lines().count(),
6,
"summary + 2 metadata lines + header + 2 rows:\n{s}"
);
}
#[test]
fn mul_dense_against_known_matrix() {
let (_cfg, nodes, sup) = make_poi1(2);
let (a, b) = (nodes[0].id(), nodes[1].id());
let mut m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
m.add_entry(a, "q", a, "T", 2.0).unwrap();
m.add_entry(a, "q", b, "T", -1.0).unwrap();
m.add_entry(b, "q", a, "T", -1.0).unwrap();
m.add_entry(b, "q", b, "T", 2.0).unwrap();
assert_eq!(m.mul_dense(&[1.0, 1.0]).unwrap(), vec![1.0, 1.0]);
assert_eq!(m.mul_dense(&[1.0, 2.0]).unwrap(), vec![0.0, 3.0]);
}
#[test]
fn mul_dense_rejects_wrong_size() {
let (_cfg, nodes, sup) = make_poi1(1);
let a = nodes[0].id();
let mut m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
m.add_entry(a, "q", a, "T", 1.0).unwrap();
assert!(m.mul_dense(&[1.0, 2.0]).is_err());
}
#[test]
fn rectangular_sub_matrix_distinct_row_and_col_supports() {
let (_cfg_r, row_nodes, row_sup) = make_poi1(2);
let (_cfg_c, col_nodes, col_sup) = make_poi1(2);
let mut c = SubMatrix::new(
row_sup,
col_sup,
vec!["T".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
c.add_entry(row_nodes[0].id(), "T", col_nodes[0].id(), "T", 1.0)
.unwrap();
c.add_entry(row_nodes[1].id(), "T", col_nodes[1].id(), "T", 1.0)
.unwrap();
assert_eq!(c.n_rows(), 2);
assert_eq!(c.n_cols(), 2);
assert_eq!(c.field_names().len(), 1);
}
#[test]
fn iter_entries_preserves_insertion_order() {
let (_cfg, nodes, sup) = make_poi1(2);
let (a, b) = (nodes[0].id(), nodes[1].id());
let mut m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
m.add_entry(a, "q", a, "T", 1.0).unwrap();
m.add_entry(b, "q", b, "T", 2.0).unwrap();
m.add_entry(a, "q", a, "T", 3.0).unwrap();
let entries = m.iter_entries();
assert_eq!(entries.len(), 3);
assert_eq!(entries[0].4, 1.0);
assert_eq!(entries[1].4, 2.0);
assert_eq!(entries[2].4, 3.0);
}
#[test]
fn sub_matrix_mul_and_div_scale_only_the_factor() {
let (_cfg, nodes, sup) = make_poi1(1);
let a = nodes[0].id();
let mut m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
m.add_entry(a, "q", a, "T", 2.0).unwrap();
assert_eq!(m.factor(), 1.0);
let scaled = &m * 3.0;
assert_eq!(scaled.factor(), 3.0);
assert_eq!(scaled.get(a, "q", a, "T"), 6.0);
assert_eq!(scaled.dense(), vec![6.0]);
assert_eq!(scaled.iter_entries()[0].4, 6.0);
assert_eq!(
m.get(a, "q", a, "T"),
2.0,
"reference Mul must not mutate m"
);
let halved = scaled / 2.0;
assert_eq!(halved.factor(), 1.5);
assert_eq!(halved.get(a, "q", a, "T"), 3.0);
assert_eq!(halved.to_coo().values(), &[3.0]);
assert_eq!(halved.to_csr().values(), &[3.0]);
assert_eq!(halved.to_csc().values(), &[3.0]);
assert_eq!(halved.to_dmatrix()[(0, 0)], 3.0);
assert_eq!(halved.mul_dense(&[1.0]).unwrap(), vec![3.0]);
assert_eq!(halved.local_coo_arrays().2, &[2.0]);
}
#[test]
fn physics_tag_set_empty_multiple_and_other() {
let (_cfg, nodes, sup) = make_poi1(2);
let (a, _b) = (nodes[0].id(), nodes[1].id());
let make = || {
SubMatrix::new(
sup.clone(),
sup.clone(),
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
)
};
let bare = make();
assert!(bare.physics().is_empty());
let mut coupled = make();
coupled.set_physics(vec![Physics::Mechanical, Physics::Thermal]);
assert_eq!(coupled.physics(), &[Physics::Mechanical, Physics::Thermal]);
let mut other = make();
other.set_physics(vec![Physics::Other]);
let mut k = Matrix::empty();
k.add_sub(Handle::new(bare)).unwrap();
k.add_sub(Handle::new(coupled)).unwrap();
k.add_sub(Handle::new(other)).unwrap();
let _ = a;
assert_eq!(k.filter(Physics::Mechanical).len(), 1);
assert_eq!(k.filter(Physics::Thermal).len(), 1);
assert_eq!(k.filter(Physics::Other).len(), 1);
let present = k.physics();
assert!(present.contains(&Physics::Mechanical));
assert!(present.contains(&Physics::Thermal));
assert!(present.contains(&Physics::Other));
assert_eq!(present.len(), 3);
}
#[test]
fn sub_debug_and_display() {
let (_cfg, nodes, sup) = make_poi1(1);
let a = nodes[0].id();
let mut m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
m.add_entry(a, "q", a, "T", 2.0).unwrap();
let d = format!("{:?}", m);
assert!(d.contains("SubMatrix"));
assert!(d.contains("n_rows"));
assert!(d.contains("symmetry"));
let s = format!("{}", m);
assert!(s.contains("SubMatrix"));
assert!(s.contains("1 row"));
assert!(s.contains("symmetric"));
}
#[test]
fn dof_ordering_vars_then_nodes() {
let (_cfg, nodes, sup) = make_poi1(2);
let (a, b) = (nodes[0].id(), nodes[1].id());
let (_cfg2, nodes2, sup2) = make_poi1(2);
let (c, d) = (nodes2[0].id(), nodes2[1].id());
let mut m = SubMatrix::new(
sup,
sup2,
vec!["p".into(), "q".into()],
vec!["u".into(), "v".into()],
DofOrdering::VarsThenNodes,
Symmetry::None,
);
m.add_entry(a, "p", c, "u", 1.0).unwrap();
m.add_entry(b, "p", d, "v", 2.0).unwrap();
m.add_entry(a, "q", c, "v", 3.0).unwrap();
assert_eq!(m.get(a, "p", c, "u"), 1.0);
assert_eq!(m.get(b, "p", d, "v"), 2.0);
assert_eq!(m.get(a, "q", c, "v"), 3.0);
assert_eq!(m.get(b, "q", d, "u"), 0.0);
let rdofs = m.row_dofs();
assert_eq!(rdofs[0], (a, "p".to_string()));
assert_eq!(rdofs[1], (b, "p".to_string()));
assert_eq!(rdofs[2], (a, "q".to_string()));
assert_eq!(rdofs[3], (b, "q".to_string()));
}
#[test]
fn dof_ordering_nodes_then_vars() {
let (_cfg, nodes, sup) = make_poi1(2);
let (a, b) = (nodes[0].id(), nodes[1].id());
let (_cfg2, nodes2, sup2) = make_poi1(2);
let (c, _d) = (nodes2[0].id(), nodes2[1].id());
let mut m = SubMatrix::new(
sup,
sup2,
vec!["p".into(), "q".into()],
vec!["u".into(), "v".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
m.add_entry(a, "p", c, "u", 7.0).unwrap();
assert_eq!(m.get(a, "p", c, "u"), 7.0);
let rdofs = m.row_dofs();
assert_eq!(rdofs[0], (a, "p".to_string()));
assert_eq!(rdofs[1], (a, "q".to_string()));
assert_eq!(rdofs[2], (b, "p".to_string()));
assert_eq!(rdofs[3], (b, "q".to_string()));
}
#[test]
fn empty_aggregate_is_vacuous_symmetric() {
let m = Matrix::empty();
assert_eq!(m.n_rows().unwrap(), 0);
assert_eq!(m.n_cols().unwrap(), 0);
assert!(m.symmetric());
assert_eq!(m.entry_count(), 0);
}
#[test]
fn aggregate_unions_dofs_and_sums_at_coincidence() {
let (coords, nodes, _) = make_poi1(5);
let (na, ca0, ca1, m0, m1) = (
nodes[0].id(),
nodes[1].id(),
nodes[2].id(),
nodes[3].id(),
nodes[4].id(),
);
let mut row_a = SubMesh::new(coords.clone(), ElementType::POI1);
row_a.add_cell(&[na]).unwrap();
let mut col_a = SubMesh::new(coords.clone(), ElementType::POI1);
col_a.add_cell(&[ca0]).unwrap();
col_a.add_cell(&[ca1]).unwrap();
let mut a = SubMatrix::new(
Handle::new(row_a),
Handle::new(col_a),
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
a.add_entry(na, "q", ca0, "T", 2.0).unwrap();
a.add_entry(na, "q", ca1, "T", -1.0).unwrap();
let mut row_b = SubMesh::new(coords.clone(), ElementType::POI1);
row_b.add_cell(&[m0]).unwrap();
row_b.add_cell(&[m1]).unwrap();
let mut col_b = SubMesh::new(coords.clone(), ElementType::POI1);
col_b.add_cell(&[m0]).unwrap();
col_b.add_cell(&[m1]).unwrap();
let mut b = SubMatrix::new(
Handle::new(row_b),
Handle::new(col_b),
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
b.add_entry(m0, "q", m0, "T", 0.5).unwrap();
b.add_entry(m1, "q", m0, "T", -1.0).unwrap();
b.add_entry(m1, "q", m1, "T", 2.0).unwrap();
let mut k = Matrix::empty();
k.add_sub(Handle::new(a)).unwrap();
k.add_sub(Handle::new(b)).unwrap();
assert_eq!(k.n_rows().unwrap(), 3);
assert_eq!(k.n_cols().unwrap(), 4);
}
#[test]
fn aggregate_symmetric_is_and_of_subs() {
let (_cfg, _nodes, sup) = make_poi1(1);
let a = SubMatrix::new(
sup.clone(),
sup.clone(),
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
let b = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
let mut k = Matrix::empty();
k.add_sub(Handle::new(a)).unwrap();
k.add_sub(Handle::new(b)).unwrap();
assert!(!k.symmetric());
}
#[test]
fn aggregate_scale_is_isolated_from_the_source_matrix() {
let (_cfg, nodes, sup) = make_poi1(2);
let (a, b) = (nodes[0].id(), nodes[1].id());
let mut blk = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
blk.add_entry(a, "q", a, "T", 2.0).unwrap();
blk.add_entry(b, "q", b, "T", 3.0).unwrap();
let mut orig = Matrix::empty();
orig.add_sub(Handle::new(blk)).unwrap();
let scaled = &orig * 10.0;
let orig_h = orig.iter().next().unwrap();
let scaled_h = scaled.iter().next().unwrap();
assert!(!orig_h.same_object(scaled_h));
assert_eq!(orig.get(a, "q", a, "T"), 2.0);
assert_eq!(orig.get(b, "q", b, "T"), 3.0);
assert_eq!(scaled.get(a, "q", a, "T"), 20.0);
assert_eq!(scaled.get(b, "q", b, "T"), 30.0);
let halved = &scaled / 2.0;
assert_eq!(halved.get(a, "q", a, "T"), 10.0);
assert_eq!(
scaled.get(a, "q", a, "T"),
20.0,
"/ must not mutate its source either"
);
}
fn diag(sup: &Handle<SubMesh>, nodes: &[NodeId], value: f64) -> Matrix {
let mut blk = SubMatrix::new(
sup.clone(),
sup.clone(),
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
for &n in nodes {
blk.add_entry(n, "q", n, "T", value).unwrap();
}
let mut m = Matrix::empty();
m.add_sub(Handle::new(blk)).unwrap();
m
}
#[test]
fn scaling_carries_the_assembled_csr() {
let (_cfg, nodes, sup) = make_poi1(2);
let (a, b) = (nodes[0].id(), nodes[1].id());
let mut k = diag(&sup, &[a, b], 2.0);
k.finalize().unwrap();
let scaled = &k * 3.0;
assert_eq!(scaled.to_csr().unwrap().values(), &[6.0, 6.0]);
assert_eq!(scaled.get(a, "q", a, "T"), 6.0);
let (ka, sa) = (
k.assembled.as_ref().unwrap(),
scaled.assembled.as_ref().unwrap(),
);
assert!(std::sync::Arc::ptr_eq(
&ka.csr.row_offsets,
&sa.csr.row_offsets
));
assert!(std::sync::Arc::ptr_eq(
&ka.csr.col_indices,
&sa.csr.col_indices
));
assert_eq!(k.to_csr().unwrap().values(), &[2.0, 2.0]);
let raw = diag(&sup, &[a], 1.0);
assert!((&raw * 2.0).to_csr().is_err());
}
#[test]
fn owned_scaling_reuses_a_block_no_one_else_holds() {
let (_cfg, nodes, sup) = make_poi1(1);
let a = nodes[0].id();
let sole = diag(&sup, &[a], 2.0);
let slot = sole.iter().next().unwrap().id();
let scaled = sole * 3.0;
assert_eq!(
scaled.iter().next().unwrap().id(),
slot,
"sole owner: in place"
);
assert_eq!(scaled.get(a, "q", a, "T"), 6.0);
let shared = diag(&sup, &[a], 2.0);
let alias = shared.subset([0]).unwrap();
let slot = shared.iter().next().unwrap().id();
let scaled = shared * 3.0;
assert_ne!(scaled.iter().next().unwrap().id(), slot, "shared: rebuilt");
assert_eq!(scaled.get(a, "q", a, "T"), 6.0);
assert_eq!(
alias.get(a, "q", a, "T"),
2.0,
"the aliasing matrix is spared"
);
}
#[test]
fn sum_counts_a_shared_block_twice_where_union_drops_it() {
let (_cfg, nodes, sup) = make_poi1(1);
let a = nodes[0].id();
let k = diag(&sup, &[a], 2.0);
let mut sum = &k + &k;
sum.finalize().unwrap();
assert_eq!(sum.len(), 2);
assert_eq!(sum.get(a, "q", a, "T"), 4.0, "k + k is 2k");
let mut union = k.union(&k).unwrap();
union.finalize().unwrap();
assert_eq!(union.len(), 1);
assert_eq!(union.get(a, "q", a, "T"), 2.0, "k | k is k");
assert!(sum
.iter()
.next()
.unwrap()
.same_object(k.iter().next().unwrap()));
assert_eq!(k.get(a, "q", a, "T"), 2.0);
}
#[test]
fn difference_negates_only_the_right_hand_side() {
let (_cfg, nodes, sup) = make_poi1(1);
let a = nodes[0].id();
let x = diag(&sup, &[a], 5.0);
let y = diag(&sup, &[a], 2.0);
let mut d = &x - &y;
d.finalize().unwrap();
assert_eq!(d.get(a, "q", a, "T"), 3.0);
assert_eq!(y.get(a, "q", a, "T"), 2.0, "the subtrahend is untouched");
assert!(!d
.iter()
.nth(1)
.unwrap()
.same_object(y.iter().next().unwrap()));
let mut z = &x - &x;
z.finalize().unwrap();
assert_eq!(z.get(a, "q", a, "T"), 0.0);
}
#[test]
fn scalar_on_the_left_and_unary_minus() {
let (_cfg, nodes, sup) = make_poi1(1);
let a = nodes[0].id();
let k = diag(&sup, &[a], 2.0);
assert_eq!((2.0 * &k).get(a, "q", a, "T"), 4.0);
assert_eq!((-&k).get(a, "q", a, "T"), -2.0);
assert_eq!((-&k).get(a, "q", a, "T"), (&k * -1.0).get(a, "q", a, "T"));
let blk = (*k.iter().next().unwrap().read()).clone();
assert_eq!((3.0 * &blk).factor(), 3.0);
assert_eq!((-&blk).factor(), -1.0);
}
#[test]
fn a_block_and_a_matrix_mix_in_a_sum() {
let (_cfg, nodes, sup) = make_poi1(1);
let a = nodes[0].id();
let k = diag(&sup, &[a], 2.0);
let blk = (*k.iter().next().unwrap().read()).clone();
for mut s in [&k + &blk, &blk + &k] {
s.finalize().unwrap();
assert_eq!(s.len(), 2);
assert_eq!(s.get(a, "q", a, "T"), 4.0);
}
let mut two_blocks = &blk + &blk;
two_blocks.finalize().unwrap();
assert_eq!(two_blocks.get(a, "q", a, "T"), 4.0);
let mut d = &k - &blk;
d.finalize().unwrap();
assert_eq!(d.get(a, "q", a, "T"), 0.0);
}
#[test]
#[should_panic(expected = "matrix division by 0")]
fn division_by_zero_is_refused() {
let (_cfg, nodes, sup) = make_poi1(1);
let k = diag(&sup, &[nodes[0].id()], 2.0);
let _ = &k / 0.0;
}
#[test]
#[should_panic(expected = "non-finite")]
fn division_by_infinity_is_refused() {
let (_cfg, nodes, sup) = make_poi1(1);
let k = diag(&sup, &[nodes[0].id()], 2.0);
let _ = &k / f64::INFINITY;
}
#[test]
fn union_and_reassemble_combines_scaled_mass_with_stiffness() {
let (coords, nodes, _) = make_poi1(3);
let (a, b, c) = (nodes[0].id(), nodes[1].id(), nodes[2].id());
let mut sup_k = SubMesh::new(coords.clone(), ElementType::POI1);
sup_k.add_cell(&[a]).unwrap();
sup_k.add_cell(&[b]).unwrap();
sup_k.add_cell(&[c]).unwrap();
let sup_k = Handle::new(sup_k);
let mut k_blk = SubMatrix::new(
sup_k.clone(),
sup_k,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
k_blk.add_entry(a, "q", a, "T", 2.0).unwrap();
k_blk.add_entry(a, "q", b, "T", -1.0).unwrap();
k_blk.add_entry(b, "q", a, "T", -1.0).unwrap();
k_blk.add_entry(b, "q", b, "T", 2.0).unwrap();
k_blk.add_entry(c, "q", c, "T", 5.0).unwrap(); let mut k = Matrix::empty();
k.add_sub(Handle::new(k_blk)).unwrap();
let mut sup_m = SubMesh::new(coords.clone(), ElementType::POI1);
sup_m.add_cell(&[a]).unwrap();
sup_m.add_cell(&[b]).unwrap();
let sup_m = Handle::new(sup_m);
let mut m_blk = SubMatrix::new(
sup_m.clone(),
sup_m,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
m_blk.add_entry(a, "q", a, "T", 4.0).unwrap();
m_blk.add_entry(b, "q", b, "T", 4.0).unwrap();
let mut m = Matrix::empty();
m.add_sub(Handle::new(m_blk)).unwrap();
let dt = 0.5;
let m_dt = &m / dt;
let mut sys = m_dt.union(&k).unwrap();
sys.assemble().unwrap();
assert_eq!(sys.n_rows().unwrap(), 3);
assert_eq!(sys.n_cols().unwrap(), 3);
assert_eq!(sys.get(a, "q", a, "T"), 2.0 + 8.0);
assert_eq!(sys.get(a, "q", b, "T"), -1.0);
assert_eq!(sys.get(b, "q", a, "T"), -1.0);
assert_eq!(sys.get(b, "q", b, "T"), 2.0 + 8.0);
assert_eq!(sys.get(c, "q", c, "T"), 5.0);
}
#[test]
fn aggregate_to_dmatrix_layout_is_union_first_seen() {
let (coords, nodes, _) = make_poi1(2);
let na = nodes[0].id();
let nb = nodes[1].id();
let mut sm_a = SubMesh::new(coords.clone(), ElementType::POI1);
sm_a.add_cell(&[na]).unwrap();
let sup_a = Handle::new(sm_a);
let mut sm_b = SubMesh::new(coords.clone(), ElementType::POI1);
sm_b.add_cell(&[nb]).unwrap();
let sup_b = Handle::new(sm_b);
let mut a = SubMatrix::new(
sup_a.clone(),
sup_a,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
a.add_entry(na, "q", na, "T", 2.0).unwrap();
let mut b = SubMatrix::new(
sup_b.clone(),
sup_b,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
b.add_entry(nb, "q", nb, "T", 3.0).unwrap();
let mut k = Matrix::empty();
k.add_sub(Handle::new(a)).unwrap();
k.add_sub(Handle::new(b)).unwrap();
k.finalize().unwrap();
let d = k.to_dmatrix().unwrap();
assert_eq!(d.nrows(), 2);
assert_eq!(d.ncols(), 2);
assert_eq!(d[(0, 0)], 2.0);
assert_eq!(d[(0, 1)], 0.0);
assert_eq!(d[(1, 0)], 0.0);
assert_eq!(d[(1, 1)], 3.0);
}
#[test]
fn aggregate_dof_order_follows_permutation() {
let (coords, nodes, _) = make_poi1(2);
let na = nodes[0].id();
let nb = nodes[1].id();
let mk = |nid| {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[nid]).unwrap();
Handle::new(sm)
};
let sup_a = mk(na);
let sup_b = mk(nb);
let mut a = SubMatrix::new(
sup_a.clone(),
sup_a,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
a.add_entry(na, "q", na, "T", 2.0).unwrap();
let mut b = SubMatrix::new(
sup_b.clone(),
sup_b,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
b.add_entry(nb, "q", nb, "T", 3.0).unwrap();
let mut k = Matrix::empty();
k.add_sub(Handle::new(a)).unwrap();
k.add_sub(Handle::new(b)).unwrap();
let cap = coords.read().capacity();
let mut perm: Vec<u32> = (0..cap as u32).collect();
perm.swap(na.0 as usize, nb.0 as usize);
coords.write().set_permutation(perm).unwrap();
k.finalize().unwrap();
let rows = k.row_dofs().unwrap();
assert_eq!(rows[0], (nb, "q".to_string()));
assert_eq!(rows[1], (na, "q".to_string()));
let d = k.to_dmatrix().unwrap();
assert_eq!(d[(0, 0)], 3.0); assert_eq!(d[(1, 1)], 2.0); }
#[test]
fn not_finalized_yields_error() {
let (_cfg, nodes, sup) = make_poi1(1);
let a = nodes[0].id();
let mut m = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
m.add_entry(a, "q", a, "T", 1.0).unwrap();
let mut k = Matrix::empty();
k.add_sub(Handle::new(m)).unwrap();
assert!(k.to_csr().is_err());
assert!(k.to_dmatrix().is_err());
assert!(k.mul_dense(&[1.0]).is_err());
k.finalize().unwrap();
assert!(k.to_csr().is_ok());
}
#[test]
fn aggregate_mul_dense_matches_dense() {
let (_cfg_a, nodes_a, sup_a) = make_poi1(2);
let (na0, na1) = (nodes_a[0].id(), nodes_a[1].id());
let mut row_a = SubMesh::new(sup_a.read().coords(), ElementType::POI1);
row_a.add_cell(&[na0]).unwrap();
let row_a_h = Handle::new(row_a);
let mut a = SubMatrix::new(
row_a_h,
sup_a.clone(),
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
a.add_entry(na0, "q", na0, "T", 2.0).unwrap();
a.add_entry(na0, "q", na1, "T", -1.0).unwrap();
let mut row_b = SubMesh::new(sup_a.read().coords(), ElementType::POI1);
row_b.add_cell(&[na1]).unwrap();
let row_b_h = Handle::new(row_b);
let mut b = SubMatrix::new(
row_b_h,
sup_a,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
b.add_entry(na1, "q", na0, "T", -1.0).unwrap();
b.add_entry(na1, "q", na1, "T", 2.0).unwrap();
let mut k = Matrix::empty();
k.add_sub(Handle::new(a)).unwrap();
k.add_sub(Handle::new(b)).unwrap();
k.finalize().unwrap();
assert_eq!(k.mul_dense(&[1.0, 1.0]).unwrap(), vec![1.0, 1.0]);
assert_eq!(k.mul_dense(&[1.0, 2.0]).unwrap(), vec![0.0, 3.0]);
}
#[test]
fn aggregate_mul_field_matches_mul_dense_and_operator() {
use crate::containers::node_field::{NodeField, SubNodeField};
let (_cfg, nodes, sup) = make_poi1(2);
let (a, b) = (nodes[0].id(), nodes[1].id());
let mut sm = SubMatrix::new(
sup.clone(),
sup.clone(),
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
sm.add_entry(a, "q", a, "T", 2.0).unwrap();
sm.add_entry(a, "q", b, "T", -1.0).unwrap();
sm.add_entry(b, "q", a, "T", -1.0).unwrap();
sm.add_entry(b, "q", b, "T", 2.0).unwrap();
let mut k = Matrix::empty();
k.add_sub(Handle::new(sm)).unwrap();
k.finalize().unwrap();
let mut x_sub = SubNodeField::from_poi1(&sup, vec!["T".into()]).unwrap();
x_sub.set_value(a, "T", 1.0).unwrap();
x_sub.set_value(b, "T", 2.0).unwrap();
let x = NodeField::from_sub(x_sub);
let y = k.mul_field(&x).unwrap();
assert_eq!(y.value(a, "q").unwrap(), 0.0);
assert_eq!(y.value(b, "q").unwrap(), 3.0);
assert!(y.value_opt(a, "T").is_none());
let y_op = (&k * &x).unwrap();
assert_eq!(y_op.value(a, "q").unwrap(), 0.0);
assert_eq!(y_op.value(b, "q").unwrap(), 3.0);
let mut x2_sub = SubNodeField::from_poi1(&sup, vec!["T".into()]).unwrap();
x2_sub.set_value(a, "T", 3.0).unwrap();
let x2 = NodeField::from_sub(x2_sub);
let y2 = k.mul_field(&x2).unwrap();
assert_eq!(y2.value(a, "q").unwrap(), 6.0);
assert_eq!(y2.value(b, "q").unwrap(), -3.0);
}
#[test]
fn aggregate_entries_concatenates_blocks() {
let (_cfg_a, nodes_a, sup_a) = make_poi1(1);
let (_cfg_b, nodes_b, sup_b) = make_poi1(1);
let na = nodes_a[0].id();
let nb = nodes_b[0].id();
let mut a = SubMatrix::new(
sup_a.clone(),
sup_a,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
a.add_entry(na, "q", na, "T", 1.0).unwrap();
let mut b = SubMatrix::new(
sup_b.clone(),
sup_b,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
b.add_entry(nb, "q", nb, "T", 2.0).unwrap();
let mut k = Matrix::empty();
k.add_sub(Handle::new(a)).unwrap();
k.add_sub(Handle::new(b)).unwrap();
let entries = k.iter_entries();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].4, 1.0);
assert_eq!(entries[1].4, 2.0);
}
#[test]
fn aggregate_debug_and_display() {
let (_cfg, nodes, sup) = make_poi1(1);
let a_id = nodes[0].id();
let mut a = SubMatrix::new(
sup.clone(),
sup,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
a.add_entry(a_id, "q", a_id, "T", 2.0).unwrap();
let mut k = Matrix::empty();
k.add_sub(Handle::new(a)).unwrap();
let d = format!("{:?}", k);
assert!(d.contains("Matrix"));
let s = format!("{}", k);
assert!(s.contains("Matrix"));
assert!(s.contains("1 row"));
assert!(s.contains("symmetric"));
}
#[test]
fn field_from_col_values_shares_block_supports_and_orders_values() {
let coords = Handle::new(Coords::new(1).unwrap());
let phys_nodes: Vec<Node> = (0..2)
.map(|i| Node::create_in(coords.clone(), &[i as f64]).unwrap())
.collect();
let mult_node = Node::create_in(coords.clone(), &[10.0]).unwrap();
let phys = {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
for n in &phys_nodes {
sm.add_cell(&[n.id()]).unwrap();
}
Handle::new(sm)
};
let mult = {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[mult_node.id()]).unwrap();
Handle::new(sm)
};
let mut k = SubMatrix::new(
phys.clone(),
phys.clone(),
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
k.add_entry(phys_nodes[0].id(), "q", phys_nodes[0].id(), "T", 1.0)
.unwrap();
let mut c = SubMatrix::new(
mult.clone(),
phys.clone(),
vec!["imposed_T".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
c.add_entry(mult_node.id(), "imposed_T", phys_nodes[0].id(), "T", 1.0)
.unwrap();
let mut ct = SubMatrix::new(
phys.clone(),
mult.clone(),
vec!["q".into()],
vec!["lambda_T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
ct.add_entry(phys_nodes[0].id(), "q", mult_node.id(), "lambda_T", 1.0)
.unwrap();
let mut m = Matrix::empty();
m.add_sub(Handle::new(k)).unwrap();
m.add_sub(Handle::new(c)).unwrap();
m.add_sub(Handle::new(ct)).unwrap();
assert!(m.field_from_col_values(&[0.0]).is_err());
m.finalize().unwrap();
let col_dofs = m.col_dofs().unwrap();
let x: Vec<f64> = (0..col_dofs.len()).map(|i| i as f64).collect();
let f = m.field_from_col_values(&x).unwrap();
assert_eq!(f.len(), 2);
assert!(f.get(0).unwrap().read().support().same_object(&phys));
assert!(f.get(1).unwrap().read().support().same_object(&mult));
for (i, (nid, var)) in col_dofs.iter().enumerate() {
assert_eq!(f.value(*nid, var).unwrap(), i as f64);
}
f.check().unwrap();
assert!(m.field_from_col_values(&x[..1]).is_err());
}
#[test]
fn field_from_col_values_unions_vars_on_a_shared_support() {
use crate::containers::field::SubField;
let (_cfg, nodes, sup) = make_poi1(2);
let mut a = SubMatrix::new(
sup.clone(),
sup.clone(),
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
a.add_entry(nodes[0].id(), "q", nodes[0].id(), "T", 1.0)
.unwrap();
let mut b = SubMatrix::new(
sup.clone(),
sup.clone(),
vec!["r".into()],
vec!["P".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
b.add_entry(nodes[1].id(), "r", nodes[1].id(), "P", 1.0)
.unwrap();
let mut m = Matrix::empty();
m.add_sub(Handle::new(a)).unwrap();
m.add_sub(Handle::new(b)).unwrap();
m.finalize().unwrap();
let col_dofs = m.col_dofs().unwrap();
let x: Vec<f64> = (0..col_dofs.len()).map(|i| 10.0 + i as f64).collect();
let f = m.field_from_col_values(&x).unwrap();
assert_eq!(f.len(), 1, "same support ⇒ one zone");
{
let z = f.get(0).unwrap().read();
assert!(z.support().same_object(&sup));
assert_eq!(SubField::components(&*z), &["T", "P"]);
}
for (i, (nid, var)) in col_dofs.iter().enumerate() {
assert_eq!(f.value(*nid, var).unwrap(), 10.0 + i as f64);
}
}
#[test]
fn row_mesh_enables_zone_aligned_residual() {
use crate::containers::node_field::SubNodeField;
let coords = Handle::new(Coords::new(1).unwrap());
let n0 = Node::create_in(coords.clone(), &[0.0]).unwrap();
let n1 = Node::create_in(coords.clone(), &[1.0]).unwrap();
let nm = Node::create_in(coords.clone(), &[10.0]).unwrap();
let phys = {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[n0.id()]).unwrap();
sm.add_cell(&[n1.id()]).unwrap();
Handle::new(sm)
};
let mult = {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[nm.id()]).unwrap();
Handle::new(sm)
};
let mut k = SubMatrix::new(
phys.clone(),
phys.clone(),
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::Full,
);
k.add_entry(n0.id(), "q", n0.id(), "T", 2.0).unwrap();
k.add_entry(n1.id(), "q", n1.id(), "T", 2.0).unwrap();
let mut c = SubMatrix::new(
mult.clone(),
phys.clone(),
vec!["imposed_T".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
c.add_entry(nm.id(), "imposed_T", n0.id(), "T", 1.0)
.unwrap();
let mut m = Matrix::empty();
m.add_sub(Handle::new(k)).unwrap();
m.add_sub(Handle::new(c)).unwrap();
let rm = m.row_mesh().unwrap();
assert_eq!(rm.len(), 2);
assert!(rm.get(0).unwrap().same_object(&phys));
assert!(rm.get(1).unwrap().same_object(&mult));
let cm = m.col_mesh().unwrap();
assert_eq!(cm.len(), 1, "K and C share the phys column support");
assert!(cm.get(0).unwrap().same_object(&phys));
m.finalize().unwrap();
let x = NodeField::from_sub(
SubNodeField::from_poi1(&phys, vec!["T".into()])
.map(|mut s| {
s.set_value(n0.id(), "T", 1.0).unwrap();
s.set_value(n1.id(), "T", 1.0).unwrap();
s
})
.unwrap(),
);
let f_int = m.mul_field(&x).unwrap();
let f_ext = {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[n0.id()]).unwrap();
sm.add_cell(&[n1.id()]).unwrap();
let mut s = SubNodeField::from_poi1(&Handle::new(sm), vec!["q".into()]).unwrap();
s.set_value(n0.id(), "q", 5.0).unwrap();
s.set_value(n1.id(), "q", 5.0).unwrap();
NodeField::from_sub(s)
};
let f_ext_r = crate::ops::node_field::restrict(&f_ext, &rm).unwrap();
for (za, zb) in f_ext_r.iter().zip(f_int.iter()) {
let sa = za.read().support();
let sb = zb.read().support();
assert!(
sa.same_object(&sb),
"restrict must land on the block supports"
);
}
let r = (&f_ext_r - &f_int).unwrap();
assert_eq!(r.value(n0.id(), "q").unwrap(), 3.0); assert_eq!(r.value(n1.id(), "q").unwrap(), 3.0);
assert_eq!(r.value(nm.id(), "imposed_T").unwrap(), 1.0);
let f_ext_like = crate::ops::node_field::restrict_like(&f_ext, &f_int).unwrap();
let r2 = (&f_ext_like - &f_int).unwrap();
assert_eq!(r2.value(n0.id(), "q").unwrap(), 3.0);
assert_eq!(r2.value(nm.id(), "imposed_T").unwrap(), -1.0); }
#[test]
fn field_from_row_values_uses_row_supports_and_dual_vars() {
let coords = Handle::new(Coords::new(1).unwrap());
let r0 = Node::create_in(coords.clone(), &[0.0]).unwrap();
let r1 = Node::create_in(coords.clone(), &[1.0]).unwrap();
let c0 = Node::create_in(coords.clone(), &[2.0]).unwrap();
let sup_r = {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[r0.id()]).unwrap();
sm.add_cell(&[r1.id()]).unwrap();
Handle::new(sm)
};
let sup_c = {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[c0.id()]).unwrap();
Handle::new(sm)
};
let mut blk = SubMatrix::new(
sup_r.clone(),
sup_c,
vec!["q".into()],
vec!["T".into()],
DofOrdering::NodesThenVars,
Symmetry::None,
);
blk.add_entry(r0.id(), "q", c0.id(), "T", 1.0).unwrap();
let mut m = Matrix::empty();
m.add_sub(Handle::new(blk)).unwrap();
m.finalize().unwrap();
let f = m.field_from_row_values(&[3.0, 7.0]).unwrap();
assert_eq!(f.len(), 1);
assert!(f.get(0).unwrap().read().support().same_object(&sup_r));
assert_eq!(f.value(r0.id(), "q").unwrap(), 3.0);
assert_eq!(f.value(r1.id(), "q").unwrap(), 7.0);
}
}