diff --git a/pyproject.toml b/pyproject.toml index 57b62c2..6ab4aef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,8 +32,8 @@ rust = ["maturin>=1.14,<2"] docs = [ "mkdocs==1.6.1", "mkdocs-material==9.7.7", - "mkdocstrings==1.0.6", - "mkdocstrings-python==2.0.8", + "mkdocstrings==1.0.8", + "mkdocstrings-python==2.0.10", ] dev = [ "maturin>=1.14,<2", diff --git a/rust/nmag_accel/src/fem.rs b/rust/nmag_accel/src/fem.rs index 87cb3fc..684e1c5 100644 --- a/rust/nmag_accel/src/fem.rs +++ b/rust/nmag_accel/src/fem.rs @@ -11,6 +11,9 @@ use crate::common::{ Vec3, }; +const PARALLEL_FEM_REDUCE_MIN_CELLS: usize = 65_536; +const PARALLEL_FEM_CHUNK_CELLS: usize = 4_096; + pub(crate) type FemGeometryResult<'py> = PyResult<( Bound<'py, PyArray2>, Bound<'py, PyArray3>, @@ -55,10 +58,17 @@ pub(crate) fn build_demag_fem_geometry<'py>( ]); } - let cell_geometries: Vec> = simplex_indices - .par_iter() - .map(|simplex| fem_cell_geometry(points, *simplex)) - .collect(); + let cell_geometries: Vec> = if should_parallelise(cell_count) { + simplex_indices + .par_iter() + .map(|simplex| fem_cell_geometry(points, *simplex)) + .collect() + } else { + simplex_indices + .iter() + .map(|simplex| fem_cell_geometry(points, *simplex)) + .collect() + }; for (cell_index, cell_geometry) in cell_geometries.into_iter().enumerate() { let Some(cell_geometry) = cell_geometry else { @@ -134,53 +144,67 @@ pub(crate) fn build_demag_fem_divergence<'py>( } let cell_count = simplices.shape()[0]; - let mut simplex_indices: Vec<[usize; 4]> = Vec::with_capacity(cell_count); - for cell_index in 0..cell_count { - simplex_indices.push([ - checked_index(simplices[[cell_index, 0]], point_count, "simplex node")?, - checked_index(simplices[[cell_index, 1]], point_count, "simplex node")?, - checked_index(simplices[[cell_index, 2]], point_count, "simplex node")?, - checked_index(simplices[[cell_index, 3]], point_count, "simplex node")?, - ]); - } - - let cell_contribution = |cell_index: usize| { - let simplex = simplex_indices[cell_index]; - let ms = ms_values[cell_index]; - let mut average_m = [0.0; 3]; - for point_index in simplex { - for component in 0..3 { - average_m[component] += m[[point_index, component]] * ms; - } + if cell_count >= PARALLEL_FEM_REDUCE_MIN_CELLS && should_parallelise(cell_count) { + let mut simplex_indices: Vec<[usize; 4]> = Vec::with_capacity(cell_count); + for cell_index in 0..cell_count { + simplex_indices.push([ + checked_index(simplices[[cell_index, 0]], point_count, "simplex node")?, + checked_index(simplices[[cell_index, 1]], point_count, "simplex node")?, + checked_index(simplices[[cell_index, 2]], point_count, "simplex node")?, + checked_index(simplices[[cell_index, 3]], point_count, "simplex node")?, + ]); } - for component in &mut average_m { - *component *= 0.25; - } - - let mut contributions = [0.0; 4]; - for local_index in 0..4 { - let gradient = [ - gradients_by_cell[[cell_index, local_index, 0]], - gradients_by_cell[[cell_index, local_index, 1]], - gradients_by_cell[[cell_index, local_index, 2]], - ]; - contributions[local_index] = volumes[cell_index] * dot3(gradient, average_m); - } - (simplex, contributions) - }; - let cell_contributions: Vec<([usize; 4], [f64; 4])> = if should_parallelise(cell_count) { - (0..cell_count) - .into_par_iter() - .map(cell_contribution) - .collect() - } else { - (0..cell_count).map(cell_contribution).collect() - }; + let divergence = simplex_indices + .par_chunks(PARALLEL_FEM_CHUNK_CELLS) + .enumerate() + .fold( + || vec![0.0; point_count], + |mut local, (chunk_idx, chunk)| { + let base_cell = chunk_idx * PARALLEL_FEM_CHUNK_CELLS; + for (offset, &[s0, s1, s2, s3]) in chunk.iter().enumerate() { + let cell_index = base_cell + offset; + let scale = 0.25 * ms_values[cell_index] * volumes[cell_index]; + let avg_mx = (m[[s0, 0]] + m[[s1, 0]] + m[[s2, 0]] + m[[s3, 0]]) * scale; + let avg_my = (m[[s0, 1]] + m[[s1, 1]] + m[[s2, 1]] + m[[s3, 1]]) * scale; + let avg_mz = (m[[s0, 2]] + m[[s1, 2]] + m[[s2, 2]] + m[[s3, 2]]) * scale; + for (local_index, point_index) in [s0, s1, s2, s3].into_iter().enumerate() { + local[point_index] += + gradients_by_cell[[cell_index, local_index, 0]] * avg_mx + + gradients_by_cell[[cell_index, local_index, 1]] * avg_my + + gradients_by_cell[[cell_index, local_index, 2]] * avg_mz; + } + } + local + }, + ) + .reduce( + || vec![0.0; point_count], + |mut left, right| { + for (l, r) in left.iter_mut().zip(right.into_iter()) { + *l += r; + } + left + }, + ); + return Ok(Array1::from_vec(divergence).into_pyarray(py)); + } let mut divergence = vec![0.0; point_count]; - for (simplex, contributions) in cell_contributions { - for local_index in 0..4 { - divergence[simplex[local_index]] += contributions[local_index]; + for cell_index in 0..cell_count { + let s0 = checked_index(simplices[[cell_index, 0]], point_count, "simplex node")?; + let s1 = checked_index(simplices[[cell_index, 1]], point_count, "simplex node")?; + let s2 = checked_index(simplices[[cell_index, 2]], point_count, "simplex node")?; + let s3 = checked_index(simplices[[cell_index, 3]], point_count, "simplex node")?; + let simplex = [s0, s1, s2, s3]; + let scale = 0.25 * ms_values[cell_index] * volumes[cell_index]; + let avg_mx = (m[[s0, 0]] + m[[s1, 0]] + m[[s2, 0]] + m[[s3, 0]]) * scale; + let avg_my = (m[[s0, 1]] + m[[s1, 1]] + m[[s2, 1]] + m[[s3, 1]]) * scale; + let avg_mz = (m[[s0, 2]] + m[[s1, 2]] + m[[s2, 2]] + m[[s3, 2]]) * scale; + + for (local_index, &point_index) in simplex.iter().enumerate() { + divergence[point_index] += gradients_by_cell[[cell_index, local_index, 0]] * avg_mx + + gradients_by_cell[[cell_index, local_index, 1]] * avg_my + + gradients_by_cell[[cell_index, local_index, 2]] * avg_mz; } } @@ -219,60 +243,87 @@ pub(crate) fn recover_demag_nodal_field<'py>( } let cell_count = simplices.shape()[0]; - let mut simplex_indices: Vec<[usize; 4]> = Vec::with_capacity(cell_count); - for cell_index in 0..cell_count { - simplex_indices.push([ - checked_index(simplices[[cell_index, 0]], point_count, "simplex node")?, - checked_index(simplices[[cell_index, 1]], point_count, "simplex node")?, - checked_index(simplices[[cell_index, 2]], point_count, "simplex node")?, - checked_index(simplices[[cell_index, 3]], point_count, "simplex node")?, - ]); - } - - let cell_contribution = |cell_index: usize| { - let volume = volumes[cell_index]; - if volume <= 0.0 { - return None; + let nodal_len = point_count + .checked_mul(3) + .ok_or_else(|| PyValueError::new_err("point_count overflow"))?; + let mut nodal_h = if cell_count >= PARALLEL_FEM_REDUCE_MIN_CELLS && should_parallelise(cell_count) + { + let mut simplex_indices: Vec<[usize; 4]> = Vec::with_capacity(cell_count); + for cell_index in 0..cell_count { + simplex_indices.push([ + checked_index(simplices[[cell_index, 0]], point_count, "simplex node")?, + checked_index(simplices[[cell_index, 1]], point_count, "simplex node")?, + checked_index(simplices[[cell_index, 2]], point_count, "simplex node")?, + checked_index(simplices[[cell_index, 3]], point_count, "simplex node")?, + ]); } - Some(( - simplex_indices[cell_index], - [ - cell_h[[cell_index, 0]] * volume, - cell_h[[cell_index, 1]] * volume, - cell_h[[cell_index, 2]] * volume, - ], - )) - }; - let cell_contributions: Vec> = if should_parallelise(cell_count) { - (0..cell_count) - .into_par_iter() - .map(cell_contribution) - .collect() + simplex_indices + .par_chunks(PARALLEL_FEM_CHUNK_CELLS) + .enumerate() + .fold( + || vec![0.0; nodal_len], + |mut local, (chunk_idx, chunk)| { + let base_cell = chunk_idx * PARALLEL_FEM_CHUNK_CELLS; + for (offset, &[s0, s1, s2, s3]) in chunk.iter().enumerate() { + let cell_index = base_cell + offset; + let volume = volumes[cell_index]; + if !(volume > 0.0) { + continue; + } + let wx = cell_h[[cell_index, 0]] * volume; + let wy = cell_h[[cell_index, 1]] * volume; + let wz = cell_h[[cell_index, 2]] * volume; + for point_index in [s0, s1, s2, s3] { + let base = point_index * 3; + local[base] += wx; + local[base + 1] += wy; + local[base + 2] += wz; + } + } + local + }, + ) + .reduce( + || vec![0.0; nodal_len], + |mut left, right| { + for (l, r) in left.iter_mut().zip(right.into_iter()) { + *l += r; + } + left + }, + ) } else { - (0..cell_count).map(cell_contribution).collect() - }; - - let mut nodal_h = vec![0.0; point_count * 3]; - for local_index in 0..4 { - for contribution in &cell_contributions { - let Some((simplex, weighted_h)) = contribution else { + let mut sequential = vec![0.0; nodal_len]; + for cell_index in 0..cell_count { + let s0 = checked_index(simplices[[cell_index, 0]], point_count, "simplex node")?; + let s1 = checked_index(simplices[[cell_index, 1]], point_count, "simplex node")?; + let s2 = checked_index(simplices[[cell_index, 2]], point_count, "simplex node")?; + let s3 = checked_index(simplices[[cell_index, 3]], point_count, "simplex node")?; + let volume = volumes[cell_index]; + if !(volume > 0.0) { continue; - }; - let point_index = simplex[local_index]; - let base = point_index * 3; - for component in 0..3 { - nodal_h[base + component] += weighted_h[component]; + } + let wx = cell_h[[cell_index, 0]] * volume; + let wy = cell_h[[cell_index, 1]] * volume; + let wz = cell_h[[cell_index, 2]] * volume; + for point_index in [s0, s1, s2, s3] { + let base = point_index * 3; + sequential[base] += wx; + sequential[base + 1] += wy; + sequential[base + 2] += wz; } } - } + sequential + }; for point_index in 0..point_count { let weight = weights[point_index]; if weight > 0.0 { + let inv_weight = 1.0 / weight; let base = point_index * 3; - for component in 0..3 { - nodal_h[base + component] /= weight; - } + nodal_h[base] *= inv_weight; + nodal_h[base + 1] *= inv_weight; + nodal_h[base + 2] *= inv_weight; } } @@ -299,35 +350,51 @@ pub(crate) fn demag_cell_field_average<'py>( )); } - let (weighted_sum, total_volume) = (0..cell_h.shape()[0]) - .into_par_iter() - .filter_map(|cell_index| { - let volume = volumes[cell_index]; - if volume <= 0.0 { - return None; - } - Some(( - [ - cell_h[[cell_index, 0]] * volume, - cell_h[[cell_index, 1]] * volume, - cell_h[[cell_index, 2]] * volume, - ], - volume, - )) - }) - .reduce( - || ([0.0, 0.0, 0.0], 0.0), - |left, right| { - ( + let cell_count = cell_h.shape()[0]; + let (weighted_sum, total_volume) = if should_parallelise(cell_count) { + (0..cell_count) + .into_par_iter() + .filter_map(|cell_index| { + let volume = volumes[cell_index]; + if !(volume > 0.0) { + return None; + } + Some(( [ - left.0[0] + right.0[0], - left.0[1] + right.0[1], - left.0[2] + right.0[2], + cell_h[[cell_index, 0]] * volume, + cell_h[[cell_index, 1]] * volume, + cell_h[[cell_index, 2]] * volume, ], - left.1 + right.1, - ) - }, - ); + volume, + )) + }) + .reduce( + || ([0.0, 0.0, 0.0], 0.0), + |left, right| { + ( + [ + left.0[0] + right.0[0], + left.0[1] + right.0[1], + left.0[2] + right.0[2], + ], + left.1 + right.1, + ) + }, + ) + } else { + let mut sum = [0.0, 0.0, 0.0]; + let mut total_vol = 0.0; + for cell_index in 0..cell_count { + let volume = volumes[cell_index]; + if volume > 0.0 { + sum[0] += cell_h[[cell_index, 0]] * volume; + sum[1] += cell_h[[cell_index, 1]] * volume; + sum[2] += cell_h[[cell_index, 2]] * volume; + total_vol += volume; + } + } + (sum, total_vol) + }; let average = if total_volume > 0.0 { [ diff --git a/src/mag_material/mag_material.py b/src/mag_material/mag_material.py index dd390ed..71dbe7e 100644 --- a/src/mag_material/mag_material.py +++ b/src/mag_material/mag_material.py @@ -131,18 +131,85 @@ def __init__( self.su_anisotropy = self.anisotropy self._derived_su_constants: dict[str, MaterialScalar] | None = None + self._derived_su_token: tuple[int, ...] | None = None self.extended_print = False + self._initialized = True if log.isEnabledFor(logging.INFO): log.info("Created new Material:\n %s", self) + def _sync_llg_coeffs(self) -> None: + gilbert_to_ll = 1.0 / (1.0 + self.su_llg_damping**2) + base_coeff1 = -self.su_llg_gamma_G * gilbert_to_ll + object.__setattr__(self, "su_llg_coeff2", base_coeff1 * self.su_llg_damping) + object.__setattr__( + self, + "su_llg_coeff1", + 0.0 if not self.do_precession else base_coeff1, + ) + + def __setattr__(self, name: str, value: Any) -> None: + object.__setattr__(self, name, value) + if not getattr(self, "_initialized", False): + return + if name == "Ms": + object.__setattr__(self, "su_Ms", value) + elif name == "llg_gamma_G": + object.__setattr__(self, "su_llg_gamma_G", value) + self._sync_llg_coeffs() + elif name == "llg_damping": + object.__setattr__(self, "su_llg_damping", value) + self._sync_llg_coeffs() + elif name in {"su_llg_gamma_G", "su_llg_damping", "do_precession"}: + self._sync_llg_coeffs() + elif name == "llg_normalisationfactor": + object.__setattr__(self, "su_llg_normalisationfactor", value) + elif name == "exchange_coupling": + object.__setattr__(self, "su_exchange_coupling", value) + elif name == "anisotropy": + object.__setattr__(self, "su_anisotropy", value) + if not name.startswith("_"): + object.__setattr__(self, "_derived_su_constants", None) + object.__setattr__(self, "_derived_su_token", None) + def _derived_su_values(self) -> dict[str, MaterialScalar]: - if self._derived_su_constants is None: + token = ( + id(self.Ms), + id(self.llg_damping), + id(self.su_llg_damping), + id(self.llg_gamma_G), + id(self.su_llg_gamma_G), + id(self.llg_normalisationfactor), + id(self.su_llg_normalisationfactor), + id(self.llg_polarisation), + id(self.llg_xi), + id(self.exchange_coupling), + id(self.su_exchange_coupling), + id(self.su_Ms), + bool(self.do_precession), + id(self.anisotropy), + id(self.su_anisotropy), + ) + if self._derived_su_constants is None or self._derived_su_token != token: constants = _si_constants() - thermal_factor = (2.0 * constants.boltzmann_constant * self.llg_damping) / ( - -constants.gamma0 * constants.mu0 * self.Ms + ms = self.Ms.in_units_of(SI("A/m")) + su_ms = self.su_Ms.in_units_of(SI("A/m")) + thermal_factor = ( + ( + (2.0 * constants.boltzmann_constant * self.llg_damping) + / (-constants.gamma0 * constants.mu0 * SI(1.0, "A/m")) + ) + * 0.0 + if ms == 0.0 + else (2.0 * constants.boltzmann_constant * self.llg_damping) + / (-constants.gamma0 * constants.mu0 * self.Ms) + ) + damping = ( + self.su_llg_damping.in_units_of(SI(1)) + if isinstance(self.su_llg_damping, SI) + else float(self.su_llg_damping) ) - gilbert_to_ll = 1.0 / (1.0 + self.su_llg_damping**2) + gilbert_to_ll = 1.0 / (1.0 + damping * damping) polarisation = ( self.llg_polarisation.in_units_of(SI(1)) if isinstance(self.llg_polarisation, SI) @@ -153,7 +220,6 @@ def _derived_su_values(self) -> dict[str, MaterialScalar]: cast(Any, 1.0 * constants.bohr_magneton).to("J/T").magnitude ) charge = float(cast(Any, 1.0 * constants.positron_charge).to("C").magnitude) - ms = self.Ms.in_units_of(SI("A/m")) su_f = ( SI(0.0, "m^3/A/s") if ms == 0.0 @@ -165,16 +231,20 @@ def _derived_su_values(self) -> dict[str, MaterialScalar]: "m^3/A/s", ) ) + su_exch_prefactor = ( + (2.0 * self.su_exchange_coupling / (constants.mu0 * SI(1.0, "A/m"))) * 0.0 + if su_ms == 0.0 + else 2.0 * self.su_exchange_coupling / (constants.mu0 * self.su_Ms) + ) self._derived_su_constants = { "thermal_factor": thermal_factor, "su_thermal_factor": thermal_factor, "su_llg_stt_prefactor": 0.0 if su_f == 0.0 else 1.0, - "su_llg_stt_nadiab": su_f * (xi - self.su_llg_damping), - "su_llg_stt_adiab": su_f * (1.0 + self.su_llg_damping * xi), - "su_exch_prefactor": ( - 2.0 * self.su_exchange_coupling / (constants.mu0 * self.su_Ms) - ), + "su_llg_stt_nadiab": su_f * (xi - damping), + "su_llg_stt_adiab": su_f * (1.0 + damping * xi), + "su_exch_prefactor": su_exch_prefactor, } + self._derived_su_token = token return self._derived_su_constants @property diff --git a/src/nmag/demag/linear.py b/src/nmag/demag/linear.py index 4730a92..d5dca58 100644 --- a/src/nmag/demag/linear.py +++ b/src/nmag/demag/linear.py @@ -11,6 +11,7 @@ from ..backends import ( DEMAG_DENSE_MAX_POINTS_ENV, + DEMAG_FEM_MATRIX_BACKEND_ENV, LEAST_SQUARES_RELATIVE_RESIDUAL_TOLERANCE, _demag_solve_condition_diagnostics_enabled, _selected_demag_linear_solver_backend, @@ -20,41 +21,267 @@ _scipy_linalg_cache: Any | None = None +_SPARSE_FACTORIZATION_MIN_POINTS = 64 +_SPARSE_FACTORIZATION_MAX_DENSITY = 0.25 + + +def _allow_sparse_factorization() -> bool: + return os.environ.get(DEMAG_FEM_MATRIX_BACKEND_ENV, "auto").strip().lower() != "dense" + + @dataclass(frozen=True, slots=True) class ScipyLUFactorization: - """Reusable LU factorization for a geometry-dependent dense system.""" + """Reusable LU factorization for a geometry-dependent linear system.""" lu: np.ndarray pivots: np.ndarray + splu: Any | None = None + gauge_fixed: bool = False + matrix: np.ndarray | None = None + constraint_scale: float = 1.0 def solve(self, rhs: np.ndarray) -> np.ndarray: - return np.asarray( + rhs_array = np.asarray(rhs, dtype=float) + if not np.all(np.isfinite(rhs_array)): + raise np.linalg.LinAlgError("Cannot solve linear system with non-finite RHS.") + if self.splu is not None: + if self.gauge_fixed: + n = rhs_array.shape[0] - 1 + if n < 0: + raise ValueError(f"Expected rhs of length >= 1, got {rhs_array.shape}.") + rhs_body = rhs_array[:n] + rhs_gauge = rhs_array[n] + if n == 0 and np.any(rhs_gauge != 0.0): + raise np.linalg.LinAlgError( + "Singular gauge-fixed system with non-zero constraint RHS." + ) + lam = np.mean(rhs_body, axis=0) if n > 0 else np.zeros_like(rhs_gauge) + rhs_centered = rhs_body - lam + out = np.zeros_like(rhs_array, dtype=float) + if n > 1: + out[1:n] = self.splu.solve(rhs_centered[1:]) + if n > 0: + out[:n] += rhs_gauge / n - np.mean(out[:n], axis=0) + out[n] = lam + if not np.all(np.isfinite(out)): + raise np.linalg.LinAlgError("Sparse gauge-fixed LU solve produced non-finite values.") + return out + out = np.asarray(self.splu.solve(rhs_array), dtype=float) + if not np.all(np.isfinite(out)): + raise np.linalg.LinAlgError("Sparse LU solve produced non-finite values.") + return out + solve_rhs = rhs_array + if self.gauge_fixed and self.constraint_scale != 1.0 and rhs_array.shape[0] > 0: + solve_rhs = rhs_array.copy() + solve_rhs[-1] *= self.constraint_scale + if self.matrix is not None: + linalg = _scipy_linalg() + out = _validated_least_squares_solution( + self.matrix, + solve_rhs, + np.asarray(linalg.lstsq(self.matrix, solve_rhs, check_finite=False)[0], dtype=float), + ) + if self.gauge_fixed and self.constraint_scale != 1.0 and out.shape[0] > 0: + out = out.copy() + out[-1] *= self.constraint_scale + return out + out = np.asarray( _scipy_linalg().lu_solve( (self.lu, self.pivots), - np.asarray(rhs, dtype=float), + solve_rhs, check_finite=False, ), dtype=float, ) + if not np.all(np.isfinite(out)): + raise np.linalg.LinAlgError("Dense LU solve produced non-finite values.") + if self.gauge_fixed and self.constraint_scale != 1.0 and out.shape[0] > 0: + out = out.copy() + out[-1] *= self.constraint_scale + return out + + def solve_gauge(self, divergence: np.ndarray) -> np.ndarray: + div_array = np.asarray(divergence, dtype=float) + if not np.all(np.isfinite(div_array)): + raise np.linalg.LinAlgError("Cannot solve gauge-fixed system with non-finite RHS.") + if self.splu is not None and self.gauge_fixed: + n = div_array.shape[0] + if n <= 1: + return np.zeros_like(div_array, dtype=float) + rhs_centered = div_array - np.mean(div_array, axis=0) + phi = np.zeros_like(div_array, dtype=float) + phi[1:] = self.splu.solve(rhs_centered[1:]) + phi -= np.mean(phi, axis=0) + if not np.all(np.isfinite(phi)): + raise np.linalg.LinAlgError("Sparse gauge-fixed LU solve produced non-finite values.") + return phi + augmented_shape = (div_array.shape[0] + 1, *div_array.shape[1:]) + augmented_rhs = np.zeros(augmented_shape, dtype=float) + augmented_rhs[:-1] = div_array + return self.solve(augmented_rhs)[:-1] + + +def _is_well_conditioned_splu(splu: Any, matrix_scale: float) -> bool: + if matrix_scale <= np.finfo(float).tiny or not np.isfinite(matrix_scale): + return False + u_diag = np.asarray(splu.U.diagonal(), dtype=float) + if u_diag.size == 0 or not np.all(np.isfinite(u_diag)): + return False + if not np.all(np.isfinite(splu.U.data)) or not np.all(np.isfinite(splu.L.data)): + return False + max_u = max(float(np.max(np.abs(splu.U.data))) if splu.U.nnz else 0.0, matrix_scale) + pivot_tol = 100.0 * np.finfo(float).eps * max_u + return bool(np.all(np.abs(u_diag) > pivot_tol)) + + +def _factorize_dense_scipy(matrix_array: np.ndarray) -> ScipyLUFactorization: + import warnings + + if not np.all(np.isfinite(matrix_array)): + raise np.linalg.LinAlgError("Cannot factorize a matrix with non-finite entries.") + + linalg = _scipy_linalg() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", getattr(linalg, "LinAlgWarning", Warning)) + lu, pivots = linalg.lu_factor( + matrix_array, + check_finite=False, + ) + lu_array = np.asarray(lu, dtype=float) + pivots_array = np.asarray(pivots, dtype=int) + finite_lu = bool(np.all(np.isfinite(lu_array))) + max_entry = float(np.max(np.abs(lu_array))) if (lu_array.size and finite_lu) else 0.0 + retained_matrix = ( + matrix_array + if ( + lu_array.size == 0 + or not finite_lu + or max_entry <= np.finfo(float).tiny + or np.any(np.abs(np.diag(lu_array)) <= 100.0 * np.finfo(float).eps * max_entry) + ) + else None + ) + return ScipyLUFactorization( + lu_array, + pivots_array, + matrix=retained_matrix, + ) def _factorize_scipy(matrix: np.ndarray) -> ScipyLUFactorization: - lu, pivots = _scipy_linalg().lu_factor( - np.asarray(matrix, dtype=float), - check_finite=False, - ) - return ScipyLUFactorization(np.asarray(lu, dtype=float), np.asarray(pivots, dtype=int)) + matrix_array = np.asarray(matrix, dtype=float) + if ( + _allow_sparse_factorization() + and matrix_array.ndim == 2 + and matrix_array.shape[0] == matrix_array.shape[1] + and matrix_array.shape[0] >= _SPARSE_FACTORIZATION_MIN_POINTS + and np.all(np.isfinite(matrix_array)) + ): + sparse, sparse_linalg = _scipy_sparse_modules() + csc = sparse.csc_matrix(matrix_array) + max_abs = float(np.max(np.abs(csc.data))) if csc.nnz else 0.0 + if ( + max_abs > np.finfo(float).tiny + and csc.nnz <= _SPARSE_FACTORIZATION_MAX_DENSITY * matrix_array.size + ): + try: + splu = sparse_linalg.splu(csc) + if _is_well_conditioned_splu(splu, max_abs): + return ScipyLUFactorization( + np.empty((0, 0), dtype=float), + np.empty(0, dtype=int), + splu=splu, + gauge_fixed=False, + ) + except (RuntimeError, np.linalg.LinAlgError): + LOGGER.debug( + "Sparse LU factorization failed; falling back to dense LU.", + exc_info=True, + ) + return _factorize_dense_scipy(matrix_array) + + +def _gauge_constraint_scale(matrix: np.ndarray) -> float: + if matrix.size == 0 or not np.all(np.isfinite(matrix)): + return 1.0 + if matrix.ndim == 2 and matrix.shape[0] == matrix.shape[1]: + diag_max = float(np.max(np.abs(np.diag(matrix)))) + if diag_max > np.finfo(float).tiny: + return diag_max + entry_max = float(np.max(np.abs(matrix))) + if entry_max > np.finfo(float).tiny: + return entry_max + return 1.0 def _factorize_gauge_fixed(matrix: np.ndarray) -> ScipyLUFactorization: - constraint = np.ones(matrix.shape[0], dtype=float) + matrix_array = np.asarray(matrix, dtype=float) + n = matrix_array.shape[0] + if ( + _allow_sparse_factorization() + and matrix_array.ndim == 2 + and matrix_array.shape[1] == n + and n >= _SPARSE_FACTORIZATION_MIN_POINTS + and np.all(np.isfinite(matrix_array)) + ): + sparse, sparse_linalg = _scipy_sparse_modules() + csc = sparse.csc_matrix(matrix_array) + max_abs = float(np.max(np.abs(csc.data))) if csc.nnz else 0.0 + if ( + max_abs > np.finfo(float).tiny + and csc.nnz <= _SPARSE_FACTORIZATION_MAX_DENSITY * matrix_array.size + ): + n_components = sparse.csgraph.connected_components( + csc, + directed=False, + return_labels=False, + ) + row_col_tol = 100.0 * np.finfo(float).eps * max_abs + if ( + n_components == 1 + and np.allclose( + np.asarray(csc.sum(axis=1)).ravel(), + 0.0, + atol=row_col_tol, + rtol=0.0, + ) + and np.allclose( + np.asarray(csc.sum(axis=0)).ravel(), + 0.0, + atol=row_col_tol, + rtol=0.0, + ) + ): + try: + splu = sparse_linalg.splu(csc[1:, 1:]) + if _is_well_conditioned_splu(splu, max_abs): + return ScipyLUFactorization( + np.empty((0, 0), dtype=float), + np.empty(0, dtype=int), + splu=splu, + gauge_fixed=True, + ) + except (RuntimeError, np.linalg.LinAlgError): + LOGGER.debug( + "Sparse gauge-fixed LU factorization failed; falling back to dense LU.", + exc_info=True, + ) + constraint_scale = _gauge_constraint_scale(matrix_array) + constraint = np.full(n, constraint_scale, dtype=float) augmented = np.block( [ - [matrix, constraint[:, np.newaxis]], + [matrix_array, constraint[:, np.newaxis]], [constraint[np.newaxis, :], np.zeros((1, 1), dtype=float)], ] ) - return _factorize_scipy(augmented) + dense = _factorize_dense_scipy(augmented) + return ScipyLUFactorization( + dense.lu, + dense.pivots, + matrix=dense.matrix, + gauge_fixed=True, + constraint_scale=constraint_scale, + ) def __getattr__(name: str) -> Any: @@ -304,10 +531,12 @@ def _gauge_augmented_system( ) -> tuple[np.ndarray, np.ndarray]: started = time.perf_counter() try: - constraint = np.ones(len(rhs), dtype=float) + matrix_array = np.asarray(matrix, dtype=float) + constraint_scale = _gauge_constraint_scale(matrix_array) + constraint = np.full(len(rhs), constraint_scale, dtype=float) augmented = np.block( [ - [matrix, constraint[:, np.newaxis]], + [matrix_array, constraint[:, np.newaxis]], [constraint[np.newaxis, :], np.zeros((1, 1), dtype=float)], ] ) @@ -337,17 +566,29 @@ def _solve_dense_scipy( record_timing: Callable[[str, float], None] | None, timing_prefix: str, ) -> np.ndarray: + import warnings + started = time.perf_counter() linalg = _scipy_linalg() if record_timing is not None: record_timing(f"{timing_prefix}:scipy_import", time.perf_counter() - started) started = time.perf_counter() try: - result = linalg.solve(matrix, rhs, assume_a="sym", check_finite=False) + with warnings.catch_warnings(): + warnings.simplefilter("error", getattr(linalg, "LinAlgWarning", Warning)) + result = np.asarray( + linalg.solve(matrix, rhs, assume_a="sym", check_finite=False), + dtype=float, + ) + if not np.all(np.isfinite(result)) or ( + _safe_relative_residual(matrix @ result - rhs, rhs) + > LEAST_SQUARES_RELATIVE_RESIDUAL_TOLERANCE + ): + raise np.linalg.LinAlgError("Direct SciPy solve failed residual validation.") if record_timing is not None: record_timing(f"{timing_prefix}:scipy_solve", time.perf_counter() - started) return result - except np.linalg.LinAlgError: + except (np.linalg.LinAlgError, Warning): if record_timing is not None: record_timing( f"{timing_prefix}:scipy_solve_failed", @@ -387,7 +628,12 @@ def _solve_dense_numpy( ) -> np.ndarray: started = time.perf_counter() try: - result = np.linalg.solve(matrix, rhs) + result = np.asarray(np.linalg.solve(matrix, rhs), dtype=float) + if not np.all(np.isfinite(result)) or ( + _safe_relative_residual(matrix @ result - rhs, rhs) + > LEAST_SQUARES_RELATIVE_RESIDUAL_TOLERANCE + ): + raise np.linalg.LinAlgError("Direct NumPy solve failed residual validation.") if record_timing is not None: record_timing(f"{timing_prefix}:numpy_solve", time.perf_counter() - started) return result @@ -470,7 +716,8 @@ def _demag_solve_diagnostics( if _is_sparse_matrix(stiffness): diagnostics["condition_numbers_skipped_for_sparse_storage"] = 1 else: - constraint = np.ones(len(divergence), dtype=float) + constraint_scale = _gauge_constraint_scale(np.asarray(stiffness, dtype=float)) + constraint = np.full(len(divergence), constraint_scale, dtype=float) augmented_stiffness = np.block( [ [stiffness, constraint[:, np.newaxis]], diff --git a/src/nmag/simulation/__init__.py b/src/nmag/simulation/__init__.py index bb5d114..f404ad2 100644 --- a/src/nmag/simulation/__init__.py +++ b/src/nmag/simulation/__init__.py @@ -145,7 +145,11 @@ def __init__( self.last_probe_timings_seconds: dict[str, float] = {} self.last_subfield_average_timings_seconds: dict[str, float] = {} self.last_maxangle_timings_seconds: dict[str, float] = {} - self.last_demag_solve_diagnostics: dict[str, float | int] = {} + self._last_demag_solve_diagnostics: dict[str, float | int] | None = {} + self._last_demag_solve_diagnostics_inputs: ( + tuple[Any, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray] + | None + ) = None self._last_bem_operator_stats: BemOperatorStats | None = None self.last_demag_internal_vectors: dict[str, np.ndarray] = {} self._active_subfield_array_timings: dict[str, float] | None = None @@ -159,45 +163,78 @@ def __init__( self.mat_of_mat_name: dict[str, Any] = {} self.materials: list[Any] = [] self._fields: dict[str, Any] = {} - self._demag_cache_token: tuple[int, int] | None = None + self._demag_cache_token: tuple[int, ...] | None = None self._demag_dipoles: tuple[np.ndarray, np.ndarray, float] | None = None self._demag_nodal_cache: np.ndarray | None = None - self._demag_cell_cache_token: tuple[int, int] | None = None + self._demag_cell_cache_token: tuple[int, ...] | None = None self._demag_cell_field_cache: tuple[np.ndarray, np.ndarray] | None = None self._demag_geometry_cache_token: int | None = None self._demag_boundary_faces_cache: list[tuple[int, tuple[int, int, int]]] | None = None self._demag_bem_cache: tuple[str, np.ndarray, Any, BemOperatorStats] | None = None - self._demag_fem_geometry_cache: tuple[str, Any, np.ndarray, np.ndarray] | None = None + self._demag_bem_env_cache: tuple[Any, ...] | None = None + self._demag_fem_geometry_cache: ( + tuple[str, np.ndarray, np.ndarray, Any, np.ndarray, np.ndarray] | None + ) = None + self._demag_fem_env_cache: tuple[Any, ...] | None = None self._demag_gauge_factorization_cache: ScipyLUFactorization | None = None self._demag_dirichlet_factorization_cache: ( - tuple[np.ndarray, np.ndarray, ScipyLUFactorization] | None + tuple[np.ndarray, np.ndarray, Any, ScipyLUFactorization] | None + ) = None + self._demag_nodal_recovery_operator_cache: ( + tuple[np.ndarray, np.ndarray, np.ndarray, int, Any] | None + ) = None + self._demag_fem_divergence_operator_cache: ( + tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, Any] | None + ) = None + self._demag_cell_gradient_inputs_cache: ( + tuple[ + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + ] + | None + ) = None + self._demag_ms_values_cache: tuple[int, int, Any, np.ndarray, np.ndarray] | None = None + self._demag_volume_charge_scales_cache: ( + tuple[int, int, Any, np.ndarray, np.ndarray] | None ) = None - self._demag_ms_values_cache: tuple[int, np.ndarray] | None = None - self._demag_volume_charge_scales_cache: tuple[int, np.ndarray] | None = None - self._nodal_ms_values_cache: tuple[int, np.ndarray] | None = None - self._demag_aux_cache_token: tuple[int, int] | None = None + self._nodal_ms_values_cache: tuple[tuple[int, int], np.ndarray] | None = None + self._demag_aux_cache_token: tuple[int, ...] | None = None self._demag_phi_cache: np.ndarray | None = None self._demag_rho_cache: np.ndarray | None = None self._demag_volumes_cache: np.ndarray | None = None - self._mesh_points_cache: tuple[int, np.ndarray] | None = None + self._mesh_points_cache: tuple[int, Any, int, np.ndarray] | None = None + self._mesh_simplices_cache: tuple[int, Any, int, np.ndarray] | None = None self._mesh_bounds_cache: tuple[int, np.ndarray, np.ndarray, np.ndarray] | None = None self._mesh_edge_cache: tuple[int, np.ndarray] | None = None self._simplex_volume_cache: tuple[int, np.ndarray, np.ndarray] | None = None self._volume_average_node_weights_cache: tuple[int, int, np.ndarray] | None = None self._incident_cell_volume_sums_cache: tuple[int, int, int, np.ndarray] | None = None - self._exchange_cache_token: tuple[int, int] | None = None + self._exchange_cache_token: tuple[int, ...] | None = None self._exchange_nodal_cache: np.ndarray | None = None + self._exchange_operator_cache: ( + tuple[int, Any, np.ndarray, Any, Any, np.ndarray, bool, np.ndarray] | None + ) = None self._exchange_spectral_bound_cache: tuple[int, float] | None = None - self._nodal_material_coefficients_cache: tuple[int, NodalMaterialCoefficients] | None = None + self._nodal_material_coefficients_cache: ( + tuple[tuple[int, int], NodalMaterialCoefficients] | None + ) = None self._nodal_anisotropy_groups_cache: ( - tuple[int, tuple[NodalAnisotropyGroup, ...]] | None + tuple[tuple[int, int], tuple[NodalAnisotropyGroup, ...]] | None ) = None self._anisotropy_fields_cache: tuple[ - tuple[int, int], + tuple[int, int, int], np.ndarray, np.ndarray, ] | None = None - self._llg_affine_operator_cache: tuple[int, np.ndarray] | None = None + self._llg_affine_operator_cache: tuple[tuple[int, int, bool], np.ndarray] | None = None self._probe_geometry_cache_token: int | None = None self._probe_tetrahedral_cache: ( tuple[ diff --git a/src/nmag/simulation/anisotropy/fields.py b/src/nmag/simulation/anisotropy/fields.py index cb0b4eb..1b54b85 100644 --- a/src/nmag/simulation/anisotropy/fields.py +++ b/src/nmag/simulation/anisotropy/fields.py @@ -16,13 +16,17 @@ class SimulationAnisotropyMixin( SimulationAnisotropyMaterialMixin, ): if TYPE_CHECKING: - _anisotropy_fields_cache: tuple[tuple[int, int], np.ndarray, np.ndarray] | None + _anisotropy_fields_cache: tuple[tuple[int, int, int], np.ndarray, np.ndarray] | None def __getattr__(self, name: str) -> Any: ... def _get_anisotropy_fields(self) -> tuple[np.ndarray, np.ndarray]: m = np.asarray(self._fields["m"], dtype=np.float64) - token = (id(self._require_mesh().raw_mesh), id(self._fields["m"])) + token = ( + self._mesh_geometry_token(), + self._material_state_token(), + id(self._fields["m"]), + ) cached = self._anisotropy_fields_cache if cached is not None and cached[0] == token: return cached[1], cached[2] @@ -49,6 +53,8 @@ def _get_anisotropy_fields(self) -> tuple[np.ndarray, np.ndarray]: if not np.all(np.isfinite(field)) or not np.all(np.isfinite(energy)): raise FloatingPointError("Anisotropy evaluation produced non-finite fields.") + field.setflags(write=False) + energy.setflags(write=False) self._anisotropy_fields_cache = (token, field, energy) return field, energy diff --git a/src/nmag/simulation/anisotropy/materials.py b/src/nmag/simulation/anisotropy/materials.py index 835aa18..5b87506 100644 --- a/src/nmag/simulation/anisotropy/materials.py +++ b/src/nmag/simulation/anisotropy/materials.py @@ -22,18 +22,20 @@ class NodalAnisotropyGroup: class SimulationAnisotropyMaterialMixin: if TYPE_CHECKING: - _nodal_anisotropy_groups_cache: tuple[int, tuple[NodalAnisotropyGroup, ...]] | None + _nodal_anisotropy_groups_cache: ( + tuple[tuple[int, int], tuple[NodalAnisotropyGroup, ...]] | None + ) def __getattr__(self, name: str) -> Any: ... def _nodal_anisotropy_groups(self) -> tuple[NodalAnisotropyGroup, ...]: - token = self._mesh_geometry_token() + token = (self._mesh_geometry_token(), self._material_state_token()) cached = self._nodal_anisotropy_groups_cache if cached is not None and cached[0] == token: return cached[1] point_count = len(self._mesh_points()) - simplices = np.asarray(self._require_mesh().simplices, dtype=np.int64) + simplices = np.asarray(self._mesh_simplices(), dtype=np.int64) regions = np.asarray( self._require_mesh().regions or [1] * len(simplices), dtype=np.int64, diff --git a/src/nmag/simulation/demag/bem/dirichlet.py b/src/nmag/simulation/demag/bem/dirichlet.py index 44ec083..faa322a 100644 --- a/src/nmag/simulation/demag/bem/dirichlet.py +++ b/src/nmag/simulation/demag/bem/dirichlet.py @@ -6,12 +6,22 @@ from ....backends import _selected_demag_linear_solver_backend from ....demag import _solve_linear_system -from ....demag.linear import _factorize_scipy, _is_sparse_matrix, _solve_sparse_linear_system +from ....demag.linear import ( + _SPARSE_FACTORIZATION_MAX_DENSITY, + _SPARSE_FACTORIZATION_MIN_POINTS, + ScipyLUFactorization, + _allow_sparse_factorization, + _factorize_scipy, + _is_sparse_matrix, + _solve_sparse_linear_system, +) class SimulationDemagBemDirichletMixin: if TYPE_CHECKING: - _demag_dirichlet_factorization_cache: Any | None + _demag_dirichlet_factorization_cache: ( + tuple[np.ndarray, np.ndarray, Any, ScipyLUFactorization] | None + ) def __getattr__(self, name: str) -> Any: ... @@ -21,16 +31,46 @@ def _dirichlet_extension_from_boundary( boundary_nodes: np.ndarray, boundary_values: np.ndarray, ) -> np.ndarray: + point_count = stiffness.shape[0] + is_sparse = _is_sparse_matrix(stiffness) + use_scipy_cache = ( + not is_sparse and _selected_demag_linear_solver_backend(point_count) == "scipy" + ) + cached = self._demag_dirichlet_factorization_cache if use_scipy_cache else None + + if cached is not None: + interior_nodes, cached_boundary, boundary_stiffness, factorization = cached + if cached_boundary is not boundary_nodes and not np.array_equal( + cached_boundary, boundary_nodes + ): + raise RuntimeError("Cached demag boundary partition does not match the mesh.") + with self._record_active_subfield_array_timing_block( + "demag_auxiliary:dirichlet_extension:index", + ): + phi = np.zeros(point_count, dtype=float) + phi[boundary_nodes] = boundary_values + self._record_active_subfield_array_timing( + "demag_auxiliary:dirichlet_extension:slice", + 0.0, + ) + with self._record_active_subfield_array_timing_block( + "demag_auxiliary:dirichlet_extension:rhs", + ): + interior_rhs = -boundary_stiffness @ boundary_values + with self._record_active_subfield_array_timing_block( + "demag_auxiliary:dirichlet_extension:solve", + ): + phi[interior_nodes] = factorization.solve(interior_rhs) + return phi + with self._record_active_subfield_array_timing_block( "demag_auxiliary:dirichlet_extension:index", ): - phi = np.zeros(stiffness.shape[0], dtype=float) + phi = np.zeros(point_count, dtype=float) phi[boundary_nodes] = boundary_values - boundary_set = set(int(index) for index in boundary_nodes) - interior_nodes = np.asarray( - [index for index in range(stiffness.shape[0]) if index not in boundary_set], - dtype=int, - ) + interior_mask = np.ones(point_count, dtype=bool) + interior_mask[boundary_nodes] = False + interior_nodes = np.flatnonzero(interior_mask) if len(interior_nodes) == 0: self._record_active_subfield_array_timing( "demag_auxiliary:dirichlet_extension:no_interior", @@ -41,7 +81,7 @@ def _dirichlet_extension_from_boundary( with self._record_active_subfield_array_timing_block( "demag_auxiliary:dirichlet_extension:slice", ): - if _is_sparse_matrix(stiffness): + if is_sparse: interior_stiffness = stiffness[interior_nodes][:, interior_nodes] boundary_stiffness = stiffness[interior_nodes][:, boundary_nodes] else: @@ -58,23 +98,25 @@ def _dirichlet_extension_from_boundary( record_timing=self._record_active_subfield_array_timing, timing_prefix="demag_auxiliary:dirichlet_extension", ) - elif _selected_demag_linear_solver_backend(stiffness.shape[0]) == "scipy": - cached = self._demag_dirichlet_factorization_cache - if cached is None: - factorization = _factorize_scipy(interior_stiffness) - self._demag_dirichlet_factorization_cache = ( - interior_nodes, - boundary_nodes, - factorization, - ) - else: - cached_interior, cached_boundary, factorization = cached - if not ( - np.array_equal(cached_interior, interior_nodes) - and np.array_equal(cached_boundary, boundary_nodes) - ): - raise RuntimeError("Cached demag boundary partition does not match the mesh.") - phi[interior_nodes] = factorization.solve(interior_rhs) + elif use_scipy_cache: + factorization = _factorize_scipy(interior_stiffness) + cached_boundary_stiffness: Any = boundary_stiffness + if _allow_sparse_factorization() and point_count >= _SPARSE_FACTORIZATION_MIN_POINTS: + from scipy import sparse + + csr_boundary = sparse.csr_matrix(boundary_stiffness) + if csr_boundary.nnz <= _SPARSE_FACTORIZATION_MAX_DENSITY * boundary_stiffness.size: + cached_boundary_stiffness = csr_boundary + self._demag_dirichlet_factorization_cache = ( + interior_nodes, + boundary_nodes, + cached_boundary_stiffness, + factorization, + ) + with self._record_active_subfield_array_timing_block( + "demag_auxiliary:dirichlet_extension:solve", + ): + phi[interior_nodes] = factorization.solve(interior_rhs) else: phi[interior_nodes] = _solve_linear_system( interior_stiffness, diff --git a/src/nmag/simulation/demag/bem/operator.py b/src/nmag/simulation/demag/bem/operator.py index 08791c0..da7f4dd 100644 --- a/src/nmag/simulation/demag/bem/operator.py +++ b/src/nmag/simulation/demag/bem/operator.py @@ -1,11 +1,15 @@ from __future__ import annotations +import os import time from typing import TYPE_CHECKING, Any, cast import numpy as np from ....backends import ( + DEMAG_BEM_AUTO_MATRIX_FREE_MIN_BOUNDARY_NODES_ENV, + DEMAG_BEM_STORAGE_BACKEND_ENV, + MEMORY_MODE_ENV, _load_rust_accelerator, _selected_demag_bem_storage_backend, _selected_lindholm_bem_backend, @@ -24,7 +28,8 @@ class SimulationDemagBemOperatorMixin: if TYPE_CHECKING: - _demag_bem_cache: Any | None + _demag_bem_cache: tuple[str, np.ndarray, Any, Any] | None + _demag_bem_env_cache: tuple[Any, ...] | None def __getattr__(self, name: str) -> Any: ... @@ -37,12 +42,40 @@ def _lindholm_bem_for_demag_mesh( cache_started = time.perf_counter() token = self._mesh_geometry_token() self._ensure_demag_geometry_cache_token(token) - boundary_node_count = len({node for _, face in boundary_faces for node in face}) config = getattr(self, "config", None) + lindholm_backend = _selected_lindholm_bem_backend(config) + hierarchical_cfg = getattr(config, "hierarchical_bem", None) + env_key = ( + getattr(config, "demag_bem_storage", None), + hierarchical_cfg, + lindholm_backend, + os.environ.get(DEMAG_BEM_STORAGE_BACKEND_ENV), + os.environ.get(MEMORY_MODE_ENV), + os.environ.get(DEMAG_BEM_AUTO_MATRIX_FREE_MIN_BOUNDARY_NODES_ENV), + ) + if self._demag_bem_cache is not None and self._demag_bem_env_cache == env_key: + cached_backend, boundary_nodes, operator, stats = self._demag_bem_cache + cache_kind = "matrix" if cached_backend == "dense" else "operator" + self._last_bem_operator_stats = stats + self._record_active_subfield_array_timing( + f"demag_auxiliary:bem_{cache_kind}_cache_hit", + time.perf_counter() - cache_started, + ) + return boundary_nodes, operator + + boundary_node_count = ( + len(self._demag_bem_cache[1]) + if self._demag_bem_cache is not None + else len({node for _, face in boundary_faces for node in face}) + ) storage_backend = _selected_demag_bem_storage_backend(boundary_node_count, config) - if self._demag_bem_cache is not None: + if self._demag_bem_cache is not None and self._demag_bem_env_cache is not None: cached_backend, boundary_nodes, operator, stats = self._demag_bem_cache - if cached_backend == storage_backend: + if ( + cached_backend == storage_backend + and self._demag_bem_env_cache[1:3] == (hierarchical_cfg, lindholm_backend) + ): + self._demag_bem_env_cache = env_key cache_kind = "matrix" if storage_backend == "dense" else "operator" self._last_bem_operator_stats = stats self._record_active_subfield_array_timing( @@ -89,6 +122,7 @@ def _lindholm_bem_for_demag_mesh( self._last_bem_operator_stats = stats self._demag_boundary_faces_cache = boundary_faces self._demag_bem_cache = (storage_backend, boundary_nodes, bem, stats) + self._demag_bem_env_cache = env_key return boundary_nodes, cast(Any, bem) def _build_lindholm_bem_operator( diff --git a/src/nmag/simulation/demag/fem/assembly.py b/src/nmag/simulation/demag/fem/assembly.py index f18dc33..ab6c6e2 100644 --- a/src/nmag/simulation/demag/fem/assembly.py +++ b/src/nmag/simulation/demag/fem/assembly.py @@ -7,13 +7,20 @@ from ....backends import ( _load_rust_accelerator, _selected_demag_fem_assembly_backend, + _selected_memory_mode, ) from ...support import _simulation_compatibility_binding from .charges import volume_charge_scaling_correction +_DIVERGENCE_OPERATOR_MIN_SIMPLICES = 32 +_DIVERGENCE_OPERATOR_MAX_SIMPLICES = 250_000 + class SimulationDemagFemAssemblyMixin: if TYPE_CHECKING: + _demag_fem_divergence_operator_cache: ( + tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, Any] | None + ) def __getattr__(self, name: str) -> Any: ... @@ -23,7 +30,7 @@ def _assemble_demag_fem_system( simplices: np.ndarray, m: np.ndarray, ms_values: np.ndarray, - volume_charge_scales: np.ndarray, + volume_charge_scales: np.ndarray | None = None, ) -> tuple[Any, np.ndarray, np.ndarray]: point_count = len(points) stiffness, gradients_by_cell, volumes = self._demag_fem_geometry_for_mesh( @@ -54,15 +61,20 @@ def _assemble_demag_fem_system( ms_values, point_count, ) - divergence += volume_charge_scaling_correction( - simplices, - gradients_by_cell, - volumes, - m, - ms_values, - volume_charge_scales, - point_count, - ) + if ( + len(simplices) > 0 + and volume_charge_scales is not None + and not np.all(volume_charge_scales == 1.0) + ): + divergence += volume_charge_scaling_correction( + simplices, + gradients_by_cell, + volumes, + m, + ms_values, + volume_charge_scales, + point_count, + ) return stiffness, divergence, volumes def _assemble_demag_fem_divergence_python( @@ -74,19 +86,76 @@ def _assemble_demag_fem_divergence_python( ms_values: np.ndarray, point_count: int, ) -> np.ndarray: - divergence = np.zeros(point_count, dtype=float) if len(simplices) == 0: - return divergence + return np.zeros(point_count, dtype=float) + + inputs_immutable = ( + not simplices.flags.writeable + and not gradients_by_cell.flags.writeable + and not volumes.flags.writeable + and not ms_values.flags.writeable + ) + if ( + inputs_immutable + and _DIVERGENCE_OPERATOR_MIN_SIMPLICES + <= len(simplices) + <= _DIVERGENCE_OPERATOR_MAX_SIMPLICES + and _selected_memory_mode() != "low" + ): + cached = self._demag_fem_divergence_operator_cache + if ( + cached is not None + and cached[0] is simplices + and cached[1] is gradients_by_cell + and cached[2] is volumes + and cached[3] is ms_values + and cached[4] == point_count + ): + div_operator = cached[5] + else: + from scipy import sparse + + cell_weights = (0.25 * ms_values * volumes)[:, np.newaxis, np.newaxis] + weighted_grads = gradients_by_cell * cell_weights # (C, 4, 3) + # Each cell c contributes weighted_grads[c, i, alpha] * m[simplices[c, j], alpha] + # to row simplices[c, i]. + rows = np.repeat(simplices, 12) + base_cols = 3 * simplices[:, :, np.newaxis] + np.arange(3)[np.newaxis, np.newaxis, :] + cols = np.tile(base_cols.reshape(len(simplices), 1, 12), (1, 4, 1)).ravel() + data = np.tile(weighted_grads[:, :, np.newaxis, :], (1, 1, 4, 1)).ravel() + div_operator = sparse.csr_matrix( + (data, (rows, cols)), + shape=(point_count, 3 * point_count), + ) + self._demag_fem_divergence_operator_cache = ( + simplices, + gradients_by_cell, + volumes, + ms_values, + point_count, + div_operator, + ) + return np.asarray( + div_operator @ np.ascontiguousarray(m, dtype=float).ravel(), + dtype=float, + ) - cell_m = m[simplices] * ms_values[:, np.newaxis, np.newaxis] - average_m = np.mean(cell_m, axis=1) - cell_divergence = volumes[:, np.newaxis] * np.einsum( + scaled_m = ( + m[simplices[:, 0]] + + m[simplices[:, 1]] + + m[simplices[:, 2]] + + m[simplices[:, 3]] + ) * ((0.25 * ms_values * volumes)[:, np.newaxis]) + cell_divergence = np.einsum( "cij,cj->ci", gradients_by_cell, - average_m, + scaled_m, ) - np.add.at(divergence, simplices, cell_divergence) - return divergence + return np.bincount( + simplices.ravel(), + weights=cell_divergence.ravel(), + minlength=point_count, + ).astype(float, copy=False) def _assemble_demag_fem_divergence_rust( self, diff --git a/src/nmag/simulation/demag/fem/geometry.py b/src/nmag/simulation/demag/fem/geometry.py index 1165965..467e69a 100644 --- a/src/nmag/simulation/demag/fem/geometry.py +++ b/src/nmag/simulation/demag/fem/geometry.py @@ -1,10 +1,15 @@ from __future__ import annotations +import os from typing import TYPE_CHECKING, Any import numpy as np from ....backends import ( + DEMAG_DENSE_MAX_POINTS_ENV, + DEMAG_FEM_AUTO_SPARSE_MIN_POINTS_ENV, + DEMAG_FEM_MATRIX_BACKEND_ENV, + MEMORY_MODE_ENV, _load_rust_accelerator, _selected_demag_boundary_face_backend, _selected_demag_fem_geometry_backend, @@ -20,8 +25,11 @@ class SimulationDemagFemGeometryMixin: if TYPE_CHECKING: - _demag_fem_geometry_cache: Any | None - _demag_boundary_faces_cache: Any | None + _demag_fem_geometry_cache: ( + tuple[str, np.ndarray, np.ndarray, Any, np.ndarray, np.ndarray] | None + ) + _demag_fem_env_cache: tuple[Any, ...] | None + _demag_boundary_faces_cache: list[tuple[int, tuple[int, int, int]]] | None def __getattr__(self, name: str) -> Any: ... @@ -32,23 +40,72 @@ def _demag_fem_geometry_for_mesh( ) -> tuple[Any, np.ndarray, np.ndarray]: token = self._mesh_geometry_token() self._ensure_demag_geometry_cache_token(token) + inputs_immutable = not points.flags.writeable and not simplices.flags.writeable + env_key = ( + os.environ.get(DEMAG_FEM_MATRIX_BACKEND_ENV), + os.environ.get(MEMORY_MODE_ENV), + os.environ.get(DEMAG_FEM_AUTO_SPARSE_MIN_POINTS_ENV), + os.environ.get(DEMAG_DENSE_MAX_POINTS_ENV), + ) + if ( + inputs_immutable + and self._demag_fem_geometry_cache is not None + and self._demag_fem_env_cache == env_key + ): + ( + _cached_backend, + cached_points, + cached_simplices, + stiffness, + gradients, + volumes, + ) = self._demag_fem_geometry_cache + if cached_points is points and cached_simplices is simplices: + return stiffness, gradients, volumes + matrix_backend = _selected_demag_fem_matrix_backend(len(points)) - if self._demag_fem_geometry_cache is not None: - cached_backend, stiffness, gradients, volumes = self._demag_fem_geometry_cache - if cached_backend == matrix_backend: + if inputs_immutable and self._demag_fem_geometry_cache is not None: + ( + cached_backend, + cached_points, + cached_simplices, + stiffness, + gradients, + volumes, + ) = self._demag_fem_geometry_cache + if ( + cached_backend == matrix_backend + and cached_points is points + and cached_simplices is simplices + ): + if matrix_backend == "dense": + _validate_dense_demag_size(len(points)) + self._demag_fem_env_cache = env_key return stiffness, gradients, volumes + self._demag_gauge_factorization_cache = None + self._demag_dirichlet_factorization_cache = None + self._demag_fem_divergence_operator_cache = None + self._demag_cell_gradient_inputs_cache = None + self._exchange_operator_cache = None + if matrix_backend == "sparse": stiffness, gradients, volumes = self._demag_fem_geometry_for_mesh_sparse( points, simplices, ) - self._demag_fem_geometry_cache = ( - matrix_backend, - stiffness, - gradients, - volumes, - ) + gradients.setflags(write=False) + volumes.setflags(write=False) + if inputs_immutable: + self._demag_fem_geometry_cache = ( + matrix_backend, + points, + simplices, + stiffness, + gradients, + volumes, + ) + self._demag_fem_env_cache = env_key return stiffness, gradients, volumes backend = _selected_demag_fem_geometry_backend( @@ -68,7 +125,19 @@ def _demag_fem_geometry_for_mesh( simplices, ) stiffness, gradients, volumes = geometry - self._demag_fem_geometry_cache = (matrix_backend, stiffness, gradients, volumes) + stiffness.setflags(write=False) + gradients.setflags(write=False) + volumes.setflags(write=False) + if inputs_immutable: + self._demag_fem_geometry_cache = ( + matrix_backend, + points, + simplices, + stiffness, + gradients, + volumes, + ) + self._demag_fem_env_cache = env_key return stiffness, gradients, volumes def _demag_fem_geometry_for_mesh_sparse( diff --git a/src/nmag/simulation/demag/fields/auxiliary.py b/src/nmag/simulation/demag/fields/auxiliary.py index f881340..ef8148a 100644 --- a/src/nmag/simulation/demag/fields/auxiliary.py +++ b/src/nmag/simulation/demag/fields/auxiliary.py @@ -1,6 +1,5 @@ from __future__ import annotations -import time from typing import TYPE_CHECKING, Any import numpy as np @@ -20,11 +19,34 @@ class SimulationDemagAuxiliaryMixin: _demag_rho_cache: Any | None _demag_volumes_cache: Any | None _demag_gauge_factorization_cache: Any | None + _last_demag_solve_diagnostics: dict[str, float | int] | None + _last_demag_solve_diagnostics_inputs: ( + tuple[Any, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray] + | None + ) def __getattr__(self, name: str) -> Any: ... + @property + def last_demag_solve_diagnostics(self) -> dict[str, float | int]: + diagnostics = self._last_demag_solve_diagnostics + if diagnostics is None: + if self._last_demag_solve_diagnostics_inputs is None: + diagnostics = {} + else: + diagnostics = _demag_solve_diagnostics( + *self._last_demag_solve_diagnostics_inputs + ) + self._last_demag_solve_diagnostics_inputs = None + self._last_demag_solve_diagnostics = diagnostics + return dict(diagnostics) + + @last_demag_solve_diagnostics.setter + def last_demag_solve_diagnostics(self, value: dict[str, float | int]) -> None: + self._last_demag_solve_diagnostics = dict(value) + self._last_demag_solve_diagnostics_inputs = None + def _get_demag_auxiliary_fields(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - cache_started = time.perf_counter() token = self._demag_token() if ( self._demag_aux_cache_token == token @@ -32,17 +54,18 @@ def _get_demag_auxiliary_fields(self) -> tuple[np.ndarray, np.ndarray, np.ndarra and self._demag_rho_cache is not None and self._demag_volumes_cache is not None ): - self._record_active_subfield_array_timing( - "demag_auxiliary:cache_hit", - time.perf_counter() - cache_started, - ) + if self._active_subfield_array_timings is not None: + self._record_active_subfield_array_timing( + "demag_auxiliary:cache_hit", + 0.0, + ) return self._demag_phi_cache, self._demag_rho_cache, self._demag_volumes_cache with self._record_active_subfield_array_timing_block( "demag_auxiliary:mesh_inputs", ): points = self._mesh_points() - simplices = np.asarray(self._require_mesh().simplices, dtype=int) + simplices = self._mesh_simplices() if simplices.size == 0: phi = np.zeros(len(points), dtype=float) rho = np.zeros(len(points), dtype=float) @@ -63,7 +86,8 @@ def _get_demag_auxiliary_fields(self) -> tuple[np.ndarray, np.ndarray, np.ndarra "demag_auxiliary:material_inputs", ): m = np.asarray(self._fields["m"], dtype=float) - regions = list(self._require_mesh().regions or [1] * len(simplices)) + raw_regions = self._require_mesh().regions + regions = raw_regions if raw_regions else [1] * len(simplices) ms_values = self._simplex_material_ms_values(regions) volume_charge_scales = self._simplex_volume_charge_scales(regions) with self._record_active_subfield_array_timing_block( @@ -78,6 +102,9 @@ def _get_demag_auxiliary_fields(self) -> tuple[np.ndarray, np.ndarray, np.ndarra volume_charge_scales, ) + phi.setflags(write=False) + rho.setflags(write=False) + volumes.setflags(write=False) self._demag_aux_cache_token = token self._demag_phi_cache = phi self._demag_rho_cache = rho @@ -91,7 +118,7 @@ def _fem_bem_auxiliary_at_nodes( boundary_faces: list[tuple[int, tuple[int, int, int]]], m: np.ndarray, ms_values: np.ndarray, - volume_charge_scales: np.ndarray, + volume_charge_scales: np.ndarray | None = None, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: with self._record_active_subfield_array_timing_block( "demag_auxiliary:assemble_fem", @@ -121,8 +148,7 @@ def _fem_bem_auxiliary_at_nodes( elif _selected_demag_linear_solver_backend(stiffness.shape[0]) == "scipy": if self._demag_gauge_factorization_cache is None: self._demag_gauge_factorization_cache = _factorize_gauge_fixed(stiffness) - augmented_rhs = np.concatenate([divergence, [0.0]]) - phi1 = self._demag_gauge_factorization_cache.solve(augmented_rhs)[:-1] + phi1 = self._demag_gauge_factorization_cache.solve_gauge(divergence) else: phi1 = _solve_gauge_fixed( stiffness, @@ -153,23 +179,25 @@ def _fem_bem_auxiliary_at_nodes( boundary_nodes, phi2_boundary, ) - self.last_demag_solve_diagnostics = _demag_solve_diagnostics( + phi = phi1 + phi2 + self._last_demag_solve_diagnostics = None + self._last_demag_solve_diagnostics_inputs = ( stiffness, divergence, boundary_nodes, phi1, phi2_boundary, phi2, - phi1 + phi2, + phi, ) if _demag_internal_trace_enabled(): self.last_demag_internal_vectors = { "rho": np.array(rho, copy=True), "phi1": np.array(phi1, copy=True), "phi2": np.array(phi2, copy=True), - "phi": np.array(phi1 + phi2, copy=True), + "phi": np.array(phi, copy=True), } - return phi1 + phi2, rho, volumes + return phi, rho, volumes def _scalar_cofield_to_legacy_boxed_field( self, diff --git a/src/nmag/simulation/demag/fields/probe.py b/src/nmag/simulation/demag/fields/probe.py index e0a2f27..a7032ac 100644 --- a/src/nmag/simulation/demag/fields/probe.py +++ b/src/nmag/simulation/demag/fields/probe.py @@ -12,6 +12,21 @@ class SimulationDemagProbeMixin: if TYPE_CHECKING: _demag_dipoles: tuple[np.ndarray, np.ndarray, float] | None + _demag_cell_gradient_inputs_cache: ( + tuple[ + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, + ] + | None + ) def __getattr__(self, name: str) -> Any: ... @@ -21,12 +36,45 @@ def _cell_demag_from_potential( simplices: np.ndarray, phi: np.ndarray, ) -> np.ndarray: + if len(simplices) == 0: + return np.zeros((0, 3), dtype=float) _, gradients_by_cell, _ = self._demag_fem_geometry_for_mesh(points, simplices) - return -np.einsum( - "ci,cij->cj", - phi[simplices], - gradients_by_cell, - ) + inputs_immutable = not simplices.flags.writeable and not gradients_by_cell.flags.writeable + cached = self._demag_cell_gradient_inputs_cache + if ( + inputs_immutable + and cached is not None + and cached[0] is simplices + and cached[1] is gradients_by_cell + ): + _, _, s0, s1, s2, s3, neg_g0, neg_g1, neg_g2, neg_g3 = cached + else: + s0 = np.ascontiguousarray(simplices[:, 0]) + s1 = np.ascontiguousarray(simplices[:, 1]) + s2 = np.ascontiguousarray(simplices[:, 2]) + s3 = np.ascontiguousarray(simplices[:, 3]) + neg_g0 = np.ascontiguousarray(-gradients_by_cell[:, 0]) + neg_g1 = np.ascontiguousarray(-gradients_by_cell[:, 1]) + neg_g2 = np.ascontiguousarray(-gradients_by_cell[:, 2]) + neg_g3 = np.ascontiguousarray(-gradients_by_cell[:, 3]) + if inputs_immutable: + self._demag_cell_gradient_inputs_cache = ( + simplices, + gradients_by_cell, + s0, + s1, + s2, + s3, + neg_g0, + neg_g1, + neg_g2, + neg_g3, + ) + out = phi[s0, np.newaxis] * neg_g0 + out += phi[s1, np.newaxis] * neg_g1 + out += phi[s2, np.newaxis] * neg_g2 + out += phi[s3, np.newaxis] * neg_g3 + return out def _build_demag_dipoles(self) -> tuple[np.ndarray, np.ndarray, float]: if "m" not in self._fields: @@ -34,7 +82,7 @@ def _build_demag_dipoles(self) -> tuple[np.ndarray, np.ndarray, float]: points = self._mesh_points() mesh = self._require_mesh() - simplices = np.asarray(mesh.simplices, dtype=int) + simplices = self._mesh_simplices() if simplices.size == 0: return np.empty((0, 3)), np.empty((0, 3)), 1.0 if simplices.ndim != 2 or simplices.shape[1] != 4: diff --git a/src/nmag/simulation/demag/fields/recovery.py b/src/nmag/simulation/demag/fields/recovery.py index 0a6888f..7ebca21 100644 --- a/src/nmag/simulation/demag/fields/recovery.py +++ b/src/nmag/simulation/demag/fields/recovery.py @@ -1,6 +1,5 @@ from __future__ import annotations -import time from typing import TYPE_CHECKING, Any import numpy as np @@ -9,14 +8,20 @@ _load_rust_accelerator, _selected_demag_cell_average_backend, _selected_demag_nodal_recovery_backend, + _selected_memory_mode, ) from ...support import _simulation_compatibility_binding +_RECOVERY_OPERATOR_MAX_SIMPLICES = 250_000 + class SimulationDemagRecoveryMixin: if TYPE_CHECKING: _demag_nodal_cache: np.ndarray | None _demag_cell_field_cache: tuple[np.ndarray, np.ndarray] | None + _demag_nodal_recovery_operator_cache: ( + tuple[np.ndarray, np.ndarray, np.ndarray, int, Any] | None + ) def __getattr__(self, name: str) -> Any: ... @@ -26,10 +31,12 @@ def _get_demag_nodal_field(self) -> np.ndarray: return self._demag_nodal_cache points = self._mesh_points() - simplices = np.asarray(self._require_mesh().simplices, dtype=int) + simplices = self._mesh_simplices() if simplices.size == 0: + nodal_h = np.zeros((len(points), 3), dtype=float) + nodal_h.setflags(write=False) self._demag_cache_token = token - self._demag_nodal_cache = np.zeros((len(points), 3), dtype=float) + self._demag_nodal_cache = nodal_h return self._demag_nodal_cache if simplices.ndim != 2 or simplices.shape[1] != 4: raise NotImplementedError("The demag MVP currently supports tetrahedral 3D meshes.") @@ -61,25 +68,28 @@ def _get_demag_nodal_field(self) -> np.ndarray: weights, len(points), ) + nodal_h.setflags(write=False) self._demag_cache_token = token self._demag_nodal_cache = nodal_h return nodal_h def _get_demag_cell_field(self) -> tuple[np.ndarray, np.ndarray]: - cache_started = time.perf_counter() token = self._demag_token() if self._demag_cell_cache_token == token and self._demag_cell_field_cache is not None: - self._record_active_subfield_array_timing( - "H_demag_detail:cell_field_cache_hit", - time.perf_counter() - cache_started, - ) + if self._active_subfield_array_timings is not None: + self._record_active_subfield_array_timing( + "H_demag_detail:cell_field_cache_hit", + 0.0, + ) return self._demag_cell_field_cache points = self._mesh_points() - simplices = np.asarray(self._require_mesh().simplices, dtype=int) + simplices = self._mesh_simplices() if simplices.size == 0: cell_h = np.zeros((0, 3), dtype=float) volumes = np.zeros(0, dtype=float) + cell_h.setflags(write=False) + volumes.setflags(write=False) self._demag_cell_cache_token = token self._demag_cell_field_cache = (cell_h, volumes) return self._demag_cell_field_cache @@ -94,6 +104,8 @@ def _get_demag_cell_field(self) -> tuple[np.ndarray, np.ndarray]: "H_demag_detail:cell_gradient", ): cell_h = self._cell_demag_from_potential(points, simplices, phi) + cell_h.setflags(write=False) + volumes.setflags(write=False) self._demag_cell_cache_token = token self._demag_cell_field_cache = (cell_h, volumes) return self._demag_cell_field_cache @@ -167,18 +179,71 @@ def _recover_demag_nodal_field_python( weights: np.ndarray, point_count: int, ) -> np.ndarray: + if len(simplices) == 0 or cell_h.size == 0: + return np.zeros((point_count, 3), dtype=float) + inputs_immutable = ( + not simplices.flags.writeable + and not volumes.flags.writeable + and not weights.flags.writeable + ) + if ( + len(simplices) <= _RECOVERY_OPERATOR_MAX_SIMPLICES + and _selected_memory_mode() != "low" + ): + cached = self._demag_nodal_recovery_operator_cache + if ( + inputs_immutable + and cached is not None + and cached[0] is simplices + and cached[1] is volumes + and cached[2] is weights + and cached[3] == point_count + ): + cell_to_node_weighted = cached[4] + else: + if np.any((simplices < 0) | (simplices >= point_count)): + raise IndexError("simplex node index out of bounds") + from scipy import sparse + + inv_weights = np.zeros(point_count, dtype=float) + present = weights > 0.0 + inv_weights[present] = 1.0 / weights[present] + positive = volumes > 0.0 + if np.any(positive): + positive_indices = np.flatnonzero(positive) + positive_simplices = simplices[positive_indices] + positive_volumes = volumes[positive_indices] + rows = positive_simplices.ravel() + cols = np.repeat(positive_indices, 4) + data = np.repeat(positive_volumes, 4) * inv_weights[rows] + cell_to_node_weighted = sparse.csr_matrix( + (data, (rows, cols)), + shape=(point_count, len(simplices)), + ) + else: + cell_to_node_weighted = sparse.csr_matrix( + (point_count, len(simplices)), + dtype=float, + ) + if inputs_immutable: + self._demag_nodal_recovery_operator_cache = ( + simplices, + volumes, + weights, + point_count, + cell_to_node_weighted, + ) + return np.asarray(cell_to_node_weighted @ cell_h, dtype=float) + + if np.any((simplices < 0) | (simplices >= point_count)): + raise IndexError("simplex node index out of bounds") nodal_h = np.zeros((point_count, 3), dtype=float) positive = volumes > 0.0 if np.any(positive): + weighted_cells = cell_h[positive] * volumes[positive, np.newaxis] positive_simplices = simplices[positive] - weighted_cell_h = cell_h[positive] * volumes[positive, np.newaxis] for local_index in range(4): - np.add.at( - nodal_h, - positive_simplices[:, local_index], - weighted_cell_h, - ) - + np.add.at(nodal_h, positive_simplices[:, local_index], weighted_cells) present = weights > 0.0 nodal_h[present] /= weights[present, np.newaxis] return nodal_h diff --git a/src/nmag/simulation/exchange/coefficients.py b/src/nmag/simulation/exchange/coefficients.py index 55ab264..1eb32ba 100644 --- a/src/nmag/simulation/exchange/coefficients.py +++ b/src/nmag/simulation/exchange/coefficients.py @@ -13,7 +13,7 @@ class SimulationExchangeCoefficientMixin: if TYPE_CHECKING: _exchange_spectral_bound_cache: tuple[int, float] | None - _nodal_material_coefficients_cache: tuple[int, NodalMaterialCoefficients] | None + _nodal_material_coefficients_cache: tuple[tuple[int, int], NodalMaterialCoefficients] | None def __getattr__(self, name: str) -> Any: ... @@ -48,13 +48,13 @@ def _material_dynamic_coefficients( ) def _nodal_material_coefficients(self) -> NodalMaterialCoefficients: - token = self._mesh_geometry_token() + token = (self._mesh_geometry_token(), self._material_state_token()) cached = self._nodal_material_coefficients_cache if cached is not None and cached[0] == token: return cached[1] point_count = len(self._mesh_points()) - simplices = np.asarray(self._require_mesh().simplices, dtype=int) + simplices = self._mesh_simplices() regions = np.asarray(self._require_mesh().regions or [1] * len(simplices), dtype=int) if len(regions) != len(simplices): raise ValueError("Mesh regions must contain one entry per simplex.") @@ -104,6 +104,8 @@ def _nodal_material_coefficients(self) -> NodalMaterialCoefficients: for component in range(6) ) + for arr in arrays: + arr.setflags(write=False) coefficients = NodalMaterialCoefficients(*arrays) self._nodal_material_coefficients_cache = (token, coefficients) return coefficients @@ -151,7 +153,7 @@ def _exchange_laplacian_spectral_bound(self) -> float: return cached_bound points = self._mesh_points() - simplices = np.asarray(self._require_mesh().simplices, dtype=int) + simplices = self._mesh_simplices() if simplices.size == 0: bound = 0.0 else: diff --git a/src/nmag/simulation/exchange/fields.py b/src/nmag/simulation/exchange/fields.py index 6245df2..45925b0 100644 --- a/src/nmag/simulation/exchange/fields.py +++ b/src/nmag/simulation/exchange/fields.py @@ -4,9 +4,14 @@ import numpy as np +from ...demag.linear import _is_sparse_matrix + class SimulationExchangeFieldMixin: if TYPE_CHECKING: + _exchange_operator_cache: ( + tuple[int, Any, np.ndarray, Any, Any, np.ndarray, bool, np.ndarray] | None + ) def __getattr__(self, name: str) -> Any: ... @@ -14,7 +19,7 @@ def _get_dm_dcurrent(self) -> np.ndarray: if "current_density" not in self._fields: return np.zeros((len(self._mesh_points()), 3), dtype=float) points = self._mesh_points() - simplices = np.asarray(self._require_mesh().simplices, dtype=int) + simplices = self._mesh_simplices() if simplices.ndim != 2 or simplices.shape[1] != 4: raise NotImplementedError("Spin-transfer torque currently supports tetrahedral meshes.") stiffness, gradients_by_cell, volumes = self._demag_fem_geometry_for_mesh( @@ -59,15 +64,17 @@ def _get_exchange_nodal_field(self) -> np.ndarray: return self._exchange_nodal_cache points = self._mesh_points() - simplices = np.asarray(self._require_mesh().simplices, dtype=int) + simplices = self._mesh_simplices() exchange = np.zeros((len(points), 3), dtype=float) if simplices.size == 0: + exchange.setflags(write=False) self._exchange_cache_token = token self._exchange_nodal_cache = exchange return exchange if simplices.ndim != 2 or simplices.shape[1] != 4: raise NotImplementedError("The exchange MVP currently supports tetrahedral 3D meshes.") if self._exchange_is_zero_by_construction(): + exchange.setflags(write=False) self._exchange_cache_token = token self._exchange_nodal_cache = exchange return exchange @@ -75,32 +82,67 @@ def _get_exchange_nodal_field(self) -> np.ndarray: stiffness, _gradients_by_cell, volumes = self._demag_fem_geometry_for_mesh( points, simplices ) - lumped_volumes = ( - self._incident_cell_volume_sums( - points, - simplices, + geom_token = self._mesh_geometry_token() + coefficients = self._nodal_material_coefficients() + op_cache = self._exchange_operator_cache + if ( + op_cache is not None + and op_cache[0] == geom_token + and op_cache[1] is stiffness + and op_cache[2] is volumes + and op_cache[3] is coefficients + ): + _, _, _, _, sparse_stiffness, present, has_present, scale_present = op_cache + else: + from scipy import sparse + + sparse_stiffness = ( + stiffness if _is_sparse_matrix(stiffness) else sparse.csr_matrix(stiffness) + ) + lumped_volumes = ( + self._incident_cell_volume_sums( + points, + simplices, + volumes, + ) + / 4.0 + ) + present = lumped_volumes > 0.0 + has_present = bool(np.any(present)) + if has_present: + prefactors = coefficients.exchange_prefactor + scale_present = -( + prefactors[present, np.newaxis] / lumped_volumes[present, np.newaxis] + ) + else: + scale_present = np.zeros((0, 1), dtype=float) + self._exchange_operator_cache = ( + geom_token, + stiffness, volumes, + coefficients, + sparse_stiffness, + present, + has_present, + scale_present, ) - / 4.0 - ) - present = lumped_volumes > 0.0 - if np.any(present): - cofield = stiffness @ np.asarray(self._fields["m"], dtype=float) - prefactors = self._nodal_material_coefficients().exchange_prefactor - exchange[present] = -( - prefactors[present, np.newaxis] - * cofield[present] - / lumped_volumes[present, np.newaxis] - ) + if has_present: + cofield = sparse_stiffness @ np.asarray(self._fields["m"], dtype=float) + exchange[present] = scale_present * cofield[present] + exchange.setflags(write=False) self._exchange_cache_token = token self._exchange_nodal_cache = exchange return exchange - def _demag_token(self) -> tuple[int, int]: + def _demag_token(self) -> tuple[int, int, int]: if self.mesh is None: raise RuntimeError("A mesh must be loaded before using demag fields.") if "m" not in self._fields: raise RuntimeError("Magnetisation must be set before using demag fields.") - return (id(self._require_mesh().raw_mesh), id(self._fields["m"])) + return ( + self._mesh_geometry_token(), + self._material_state_token(), + id(self._fields["m"]), + ) diff --git a/src/nmag/simulation/exchange/llg_rhs.py b/src/nmag/simulation/exchange/llg_rhs.py index a7490d3..58cb204 100644 --- a/src/nmag/simulation/exchange/llg_rhs.py +++ b/src/nmag/simulation/exchange/llg_rhs.py @@ -91,23 +91,36 @@ def _nodal_coefficients( return tuple(arrays) @staticmethod + def _cross3(a: np.ndarray, b: np.ndarray) -> np.ndarray: + out = np.empty_like(a) + out[:, 0] = a[:, 1] * b[:, 2] - a[:, 2] * b[:, 1] + out[:, 1] = a[:, 2] * b[:, 0] - a[:, 0] * b[:, 2] + out[:, 2] = a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0] + return out + + @staticmethod + def _dot3(a: np.ndarray, b: np.ndarray) -> np.ndarray: + return a[:, 0] * b[:, 0] + a[:, 1] * b[:, 1] + a[:, 2] * b[:, 2] + + @classmethod def _llg_field_rhs( + cls, m: np.ndarray, h_total: np.ndarray, precession_values: np.ndarray, damping_values: np.ndarray, normalisation_values: np.ndarray, ) -> tuple[np.ndarray, np.ndarray]: - mxh = np.cross(m, h_total) - mdoth = np.einsum("ij,ij->i", m, h_total) - mdotm = np.einsum("ij,ij->i", m, m) + mdoth = cls._dot3(m, h_total) + mdotm = cls._dot3(m, m) damping = m * mdoth[:, np.newaxis] - h_total * mdotm[:, np.newaxis] norm_error = (1.0 - mdotm)[:, np.newaxis] * m rhs = ( - precession_values[:, np.newaxis] * mxh - + damping_values[:, np.newaxis] * damping + damping_values[:, np.newaxis] * damping + normalisation_values[:, np.newaxis] * norm_error ) + if np.any(precession_values): + rhs += precession_values[:, np.newaxis] * cls._cross3(m, h_total) return rhs, mdotm def _llg_stt_rhs( @@ -130,8 +143,8 @@ def _llg_stt_rhs( ("stt_nonadiabatic", stt_nonadiabatic_coeff), ), ) - mx_directional = np.cross(m, directional_derivative) - mdot_directional = np.einsum("ij,ij->i", m, directional_derivative) + mx_directional = self._cross3(m, directional_derivative) + mdot_directional = self._dot3(m, directional_derivative) mxmx_directional = ( m * mdot_directional[:, np.newaxis] - directional_derivative * mdotm[:, np.newaxis] ) diff --git a/src/nmag/simulation/fields/arrays.py b/src/nmag/simulation/fields/arrays.py index 201de49..300e0b8 100644 --- a/src/nmag/simulation/fields/arrays.py +++ b/src/nmag/simulation/fields/arrays.py @@ -2,7 +2,7 @@ import time from collections.abc import Generator -from contextlib import contextmanager +from contextlib import AbstractContextManager, contextmanager, nullcontext from typing import TYPE_CHECKING, Any import numpy as np @@ -13,6 +13,8 @@ _copy_average_value, ) +_NULL_TIMING_CONTEXT: AbstractContextManager[None] = nullcontext() + class SimulationFieldArrayMixin: if TYPE_CHECKING: @@ -23,21 +25,30 @@ class SimulationFieldArrayMixin: def __getattr__(self, name: str) -> Any: ... def _subfield_array(self, subfieldname: str) -> np.ndarray: + cache = self._subfield_array_cache + if self._active_subfield_array_timings is None: + if cache is not None and subfieldname in cache: + return cache[subfieldname] + data = self._compute_subfield_array(subfieldname) + if cache is not None: + cache[subfieldname] = data + return data + started = time.perf_counter() - if self._subfield_array_cache is not None and subfieldname in self._subfield_array_cache: + if cache is not None and subfieldname in cache: self._record_active_subfield_array_timing( f"{subfieldname}:cache_hit", time.perf_counter() - started, ) - return self._subfield_array_cache[subfieldname] + return cache[subfieldname] data = self._compute_subfield_array(subfieldname) self._record_active_subfield_array_timing( f"{subfieldname}:compute", time.perf_counter() - started, ) - if self._subfield_array_cache is not None: - self._subfield_array_cache[subfieldname] = data + if cache is not None: + cache[subfieldname] = data return data def _record_active_subfield_array_timing(self, name: str, seconds: float) -> None: @@ -45,8 +56,16 @@ def _record_active_subfield_array_timing(self, name: str, seconds: float) -> Non if timings is not None: timings[name] = timings.get(name, 0.0) + seconds + def _record_active_subfield_array_timing_block( + self, + name: str, + ) -> AbstractContextManager[None]: + if self._active_subfield_array_timings is None: + return _NULL_TIMING_CONTEXT + return self._timed_subfield_array_block(name) + @contextmanager - def _record_active_subfield_array_timing_block(self, name: str) -> Generator[None]: + def _timed_subfield_array_block(self, name: str) -> Generator[None]: started = time.perf_counter() try: yield diff --git a/src/nmag/simulation/fields/derived.py b/src/nmag/simulation/fields/derived.py index a7899c7..fe54d23 100644 --- a/src/nmag/simulation/fields/derived.py +++ b/src/nmag/simulation/fields/derived.py @@ -109,7 +109,9 @@ def _derived_h_total(self, _point_count: int) -> np.ndarray: h_total = np.asarray(self._subfield_array("H_ext"), dtype=float) if self.do_demag: h_total = h_total + np.asarray(self._subfield_array("H_demag"), dtype=float) - return h_total + self._subfield_array("H_anis") + self._subfield_array("H_exch") + if not self._anisotropy_is_zero_by_construction(): + h_total = h_total + self._subfield_array("H_anis") + return h_total + self._subfield_array("H_exch") def _derived_e_anis(self, point_count: int) -> np.ndarray: _field, energy = self._get_anisotropy_fields() @@ -161,4 +163,6 @@ def _exchange_is_zero_by_construction(self) -> bool: m = np.asarray(self._fields["m"], dtype=float) if m.ndim != 2 or len(m) == 0: return False + if len(m) > 1 and np.max(np.abs(m[1] - m[0])) > 1.0e-12: + return False return bool(np.allclose(m, m[0], rtol=0.0, atol=1.0e-12)) diff --git a/src/nmag/simulation/implicit_dynamics.py b/src/nmag/simulation/implicit_dynamics.py index d06c563..4816ee5 100644 --- a/src/nmag/simulation/implicit_dynamics.py +++ b/src/nmag/simulation/implicit_dynamics.py @@ -87,7 +87,11 @@ def _validate_diffsol_dense_memory(state_size: int) -> None: def build_affine_field_operator(simulation: Any) -> FloatArray: """Build the dense linear map from nodal m to demag plus exchange field.""" - mesh_token = simulation._mesh_geometry_token() + mesh_token = ( + simulation._mesh_geometry_token(), + simulation._material_state_token(), + bool(simulation.do_demag), + ) cached = simulation._llg_affine_operator_cache if cached is not None and cached[0] == mesh_token: return cached[1] @@ -118,6 +122,7 @@ def linear_field(state: FloatArray) -> FloatArray: simulation._invalidate_demag() operator = np.ascontiguousarray(operator) + operator.setflags(write=False) simulation._llg_affine_operator_cache = (mesh_token, operator) return operator diff --git a/src/nmag/simulation/mesh/geometry.py b/src/nmag/simulation/mesh/geometry.py index 861a1a7..6f18d9c 100644 --- a/src/nmag/simulation/mesh/geometry.py +++ b/src/nmag/simulation/mesh/geometry.py @@ -31,19 +31,26 @@ def _invalidate_demag(self, *, clear_geometry: bool = False) -> None: self._demag_geometry_cache_token = None self._demag_boundary_faces_cache = None self._demag_bem_cache = None + self._demag_bem_env_cache = None self._last_bem_operator_stats = None self._demag_fem_geometry_cache = None + self._demag_fem_env_cache = None self._demag_gauge_factorization_cache = None self._demag_dirichlet_factorization_cache = None + self._demag_nodal_recovery_operator_cache = None + self._demag_fem_divergence_operator_cache = None + self._demag_cell_gradient_inputs_cache = None self._demag_ms_values_cache = None self._demag_volume_charge_scales_cache = None self._nodal_ms_values_cache = None self._mesh_points_cache = None + self._mesh_simplices_cache = None self._mesh_bounds_cache = None self._mesh_edge_cache = None self._simplex_volume_cache = None self._volume_average_node_weights_cache = None self._incident_cell_volume_sums_cache = None + self._exchange_operator_cache = None self._exchange_spectral_bound_cache = None self._nodal_material_coefficients_cache = None self._nodal_anisotropy_groups_cache = None @@ -53,18 +60,47 @@ def _invalidate_demag(self, *, clear_geometry: bool = False) -> None: self._probe_tetrahedral_cache = None def _mesh_points(self) -> np.ndarray: + mesh = self._require_mesh() + raw_points = mesh.points token = self._mesh_geometry_token() + points_len = len(raw_points) if self._mesh_points_cache is not None: - cached_token, cached_points = self._mesh_points_cache - if cached_token == token: + cached_token, cached_raw, cached_len, cached_points = self._mesh_points_cache + if ( + cached_token == token + and cached_raw is raw_points + and cached_len == points_len + ): return cached_points - points = np.asarray(self._require_mesh().points, dtype=float) + points = np.array(raw_points, dtype=float, copy=True) if points.ndim != 2 or points.shape[1] != 3: raise NotImplementedError("The demag MVP currently supports only 3D meshes.") - self._mesh_points_cache = (token, points) + points.setflags(write=False) + self._mesh_points_cache = (token, raw_points, points_len, points) return points + def _mesh_simplices(self) -> np.ndarray: + mesh = self._require_mesh() + raw_simplices = mesh.simplices + token = self._mesh_geometry_token() + simplices_len = len(raw_simplices) + if self._mesh_simplices_cache is not None: + cached_token, cached_raw, cached_len, cached_simplices = self._mesh_simplices_cache + if ( + cached_token == token + and cached_raw is raw_simplices + and cached_len == simplices_len + ): + return cached_simplices + + simplices = np.array(raw_simplices, dtype=int, copy=True) + if simplices.size == 0 and simplices.ndim == 1: + simplices = simplices.reshape((0, 4)) + simplices.setflags(write=False) + self._mesh_simplices_cache = (token, raw_simplices, simplices_len, simplices) + return simplices + def _mesh_bounds(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]: token = self._mesh_geometry_token() if self._mesh_bounds_cache is not None: @@ -76,6 +112,9 @@ def _mesh_bounds(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]: lower = np.min(points, axis=0) upper = np.max(points, axis=0) span = np.maximum(upper - lower, np.ones(3)) + lower.setflags(write=False) + upper.setflags(write=False) + span.setflags(write=False) self._mesh_bounds_cache = (token, lower, upper, span) return lower, upper, span @@ -87,7 +126,7 @@ def _mesh_edges(self) -> np.ndarray: return cached_edges mesh = self._require_mesh() - simplices = np.asarray(mesh.simplices, dtype=int) + simplices = self._mesh_simplices() if simplices.ndim != 2 or simplices.shape[1] < 2 or len(simplices) == 0: edges = np.zeros((0, 2), dtype=int) else: @@ -126,11 +165,25 @@ def _mesh_edges(self) -> np.ndarray: edges[:, 0] = unique_codes // node_count edges[:, 1] = unique_codes % node_count + edges.setflags(write=False) self._mesh_edge_cache = (token, edges) return edges def _mesh_geometry_token(self) -> int: - return id(self._require_mesh().raw_mesh) + mesh = self._require_mesh() + points = mesh.points + simplices = mesh.simplices + sample = (tuple(points[0]), tuple(points[-1])) if len(points) > 0 else () + return hash( + ( + id(mesh.raw_mesh), + id(points), + id(simplices), + len(points), + len(simplices), + sample, + ) + ) def _require_mesh(self) -> Any: if self.mesh is None: @@ -143,11 +196,19 @@ def _ensure_demag_geometry_cache_token(self, token: int) -> None: self._demag_geometry_cache_token = token self._demag_boundary_faces_cache = None self._demag_bem_cache = None + self._demag_bem_env_cache = None self._last_bem_operator_stats = None self._demag_fem_geometry_cache = None + self._demag_fem_env_cache = None + self._demag_gauge_factorization_cache = None + self._demag_dirichlet_factorization_cache = None + self._demag_nodal_recovery_operator_cache = None + self._demag_fem_divergence_operator_cache = None + self._demag_cell_gradient_inputs_cache = None self._demag_ms_values_cache = None self._demag_volume_charge_scales_cache = None self._nodal_ms_values_cache = None + self._exchange_operator_cache = None self._nodal_material_coefficients_cache = None self._nodal_anisotropy_groups_cache = None self._anisotropy_fields_cache = None diff --git a/src/nmag/simulation/mesh/materials.py b/src/nmag/simulation/mesh/materials.py index fc8c99f..2aaa1b8 100644 --- a/src/nmag/simulation/mesh/materials.py +++ b/src/nmag/simulation/mesh/materials.py @@ -9,6 +9,59 @@ from ..support import _si_unit, _simulation_compatibility_binding +def _scalar_token(value: Any) -> Any: + if value is None or isinstance(value, (bool, int, float, str)): + return value + magnitude = getattr(value, "value", None) + if isinstance(magnitude, (int, float)): + return (id(value), float(magnitude)) + return id(value) + + +def _anisotropy_spec_token(spec: Any) -> Any: + if spec is None: + return None + terms = getattr(spec, "terms", None) + if isinstance(terms, Sequence): + term_tokens: list[Any] = [] + for term in terms: + axis = getattr(term, "axis", None) + axes = getattr(term, "axes", None) + axis_token: Any = None + if axis is not None: + axis_token = tuple(np.asarray(axis, dtype=float).reshape(-1).tolist()) + elif axes is not None: + axis_token = tuple( + tuple(np.asarray(vec, dtype=float).reshape(-1).tolist()) + for vec in axes + ) + term_tokens.append( + ( + getattr(term, "kind", None), + axis_token, + _scalar_token(getattr(term, "k1", None)), + _scalar_token(getattr(term, "k2", None)), + _scalar_token(getattr(term, "k3", None)), + ) + ) + return (id(spec), tuple(term_tokens)) + return id(spec) + + +def _regions_token(regions: Any) -> Any: + if regions is None: + return None + if isinstance(regions, tuple): + return (id(regions), regions) + if isinstance(regions, list): + return (id(regions), tuple(regions)) + if isinstance(regions, np.ndarray): + return (id(regions), regions.shape, regions.tobytes()) + if isinstance(regions, Sequence): + return (id(regions), tuple(regions)) + return id(regions) + + class SimulationMeshMaterialMixin: if TYPE_CHECKING: _simplex_volume_cache: Any | None @@ -20,6 +73,44 @@ class SimulationMeshMaterialMixin: def __getattr__(self, name: str) -> Any: ... + def _material_state_token(self) -> int: + mesh = getattr(self, "mesh", None) + regions = getattr(mesh, "regions", None) if mesh is not None else None + region_map = tuple(sorted(getattr(self, "region_name_of_id", {}).items())) + mats_by_region = tuple( + ( + region_name, + tuple(id(mat) for mat in mats), + ) + for region_name, mats in sorted(getattr(self, "mats_of_region_name", {}).items()) + ) + material_tokens = tuple( + ( + id(mat), + getattr(mat, "name", None), + _scalar_token(getattr(mat, "Ms", None)), + _scalar_token(getattr(mat, "exchange_coupling", None)), + _scalar_token(getattr(mat, "llg_gamma_G", None)), + _scalar_token(getattr(mat, "llg_damping", None)), + _scalar_token(getattr(mat, "llg_normalisationfactor", None)), + _scalar_token(getattr(mat, "llg_xi", None)), + _scalar_token(getattr(mat, "llg_polarisation", None)), + bool(getattr(mat, "do_precession", True)), + float(getattr(mat, "scale_volume_charges", 1.0)), + _anisotropy_spec_token(getattr(mat, "anisotropy", None)), + getattr(mat, "anisotropy_order", None), + ) + for mat in getattr(self, "materials", ()) + ) + return hash( + ( + _regions_token(regions), + region_map, + mats_by_region, + material_tokens, + ) + ) + def _material_region_ids(self, material_name: str) -> np.ndarray: region_ids = [ self.region_id_of_name[region_name] @@ -45,7 +136,7 @@ def _field_average( if len(data) > 0 and np.all(data == data[0]): return np.asarray(data[0], dtype=float) - simplices = np.asarray(self._require_mesh().simplices, dtype=int) + simplices = self._mesh_simplices() points = self._mesh_points() if ( len(data) != len(points) @@ -83,7 +174,7 @@ def _scalar_field_average( if len(data) > 0 and np.all(data == data[0]): return float(data[0]) - simplices = np.asarray(self._require_mesh().simplices, dtype=int) + simplices = self._mesh_simplices() points = self._mesh_points() if len(data) != len(points) or simplices.ndim != 2 or simplices.shape[1] != 4: return float(np.mean(data)) @@ -121,6 +212,8 @@ def _simplex_volume_weights( _simplex_volumes, )(points, simplices) positive = volumes > 0.0 + volumes.setflags(write=False) + positive.setflags(write=False) self._simplex_volume_cache = (token, volumes, positive) return volumes, positive @@ -149,6 +242,7 @@ def _volume_average_node_weights( return None weights /= total_volume + weights.setflags(write=False) self._volume_average_node_weights_cache = (token, point_count, weights) return weights @@ -162,13 +256,17 @@ def _incident_cell_volume_sums( point_count = len(points) cell_count = len(simplices) if self._incident_cell_volume_sums_cache is not None: - cached_token, cached_point_count, cached_cell_count, weights = ( + cached_token, cached_point_count, cached_cell_count, weights, cached_volumes = ( self._incident_cell_volume_sums_cache ) if ( cached_token == token and cached_point_count == point_count and cached_cell_count == cell_count + and ( + (not volumes.flags.writeable and cached_volumes is volumes) + or np.array_equal(cached_volumes, volumes) + ) ): return weights @@ -184,7 +282,15 @@ def _incident_cell_volume_sums( positive_volumes, ) - self._incident_cell_volume_sums_cache = (token, point_count, cell_count, weights) + weights.setflags(write=False) + cached_vols = volumes if not volumes.flags.writeable else volumes.copy() + self._incident_cell_volume_sums_cache = ( + token, + point_count, + cell_count, + weights, + cached_vols, + ) return weights def _simplex_material(self, region_id: int) -> Any: @@ -204,16 +310,42 @@ def _simplex_material_ms(self, region_id: int) -> float: def _simplex_material_ms_values(self, regions: Sequence[int]) -> np.ndarray: token = self._mesh_geometry_token() + material_token = self._material_state_token() self._ensure_demag_geometry_cache_token(token) + mesh = getattr(self, "mesh", None) + mesh_regions = getattr(mesh, "regions", None) if mesh is not None else None if self._demag_ms_values_cache is not None: - cached_token, cached_values = self._demag_ms_values_cache - if cached_token == token and len(cached_values) == len(regions): + cached_token, cached_material_token, cached_regions, cached_region_ids, cached_values = ( + self._demag_ms_values_cache + ) + if ( + cached_token == token + and cached_material_token == material_token + and len(cached_values) == len(regions) + and ( + (cached_regions is regions and regions is mesh_regions) + or (isinstance(regions, tuple) and cached_regions is regions) + or ( + isinstance(regions, np.ndarray) + and not regions.flags.writeable + and cached_regions is regions + ) + or np.array_equal(cached_region_ids, np.asarray(regions, dtype=int)) + ) + ): return cached_values region_ids = np.asarray(regions, dtype=int) if region_ids.size == 0: ms_values = np.zeros(0, dtype=float) - self._demag_ms_values_cache = (token, ms_values) + ms_values.setflags(write=False) + self._demag_ms_values_cache = ( + token, + material_token, + regions, + region_ids, + ms_values, + ) return ms_values first_region = int(region_ids[0]) @@ -223,7 +355,14 @@ def _simplex_material_ms_values(self, regions: Sequence[int]) -> np.ndarray: self._simplex_material_ms(first_region), dtype=float, ) - self._demag_ms_values_cache = (token, ms_values) + ms_values.setflags(write=False) + self._demag_ms_values_cache = ( + token, + material_token, + regions, + region_ids, + ms_values, + ) return ms_values unique_region_ids, inverse = np.unique(region_ids, return_inverse=True) @@ -232,15 +371,41 @@ def _simplex_material_ms_values(self, regions: Sequence[int]) -> np.ndarray: dtype=float, ) ms_values = ms_lookup[inverse] - self._demag_ms_values_cache = (token, ms_values) + ms_values.setflags(write=False) + self._demag_ms_values_cache = ( + token, + material_token, + regions, + region_ids, + ms_values, + ) return ms_values def _simplex_volume_charge_scales(self, regions: Sequence[int]) -> np.ndarray: token = self._mesh_geometry_token() + material_token = self._material_state_token() self._ensure_demag_geometry_cache_token(token) + mesh = getattr(self, "mesh", None) + mesh_regions = getattr(mesh, "regions", None) if mesh is not None else None if self._demag_volume_charge_scales_cache is not None: - cached_token, cached_values = self._demag_volume_charge_scales_cache - if cached_token == token and len(cached_values) == len(regions): + cached_token, cached_material_token, cached_regions, cached_region_ids, cached_values = ( + self._demag_volume_charge_scales_cache + ) + if ( + cached_token == token + and cached_material_token == material_token + and len(cached_values) == len(regions) + and ( + (cached_regions is regions and regions is mesh_regions) + or (isinstance(regions, tuple) and cached_regions is regions) + or ( + isinstance(regions, np.ndarray) + and not regions.flags.writeable + and cached_regions is regions + ) + or np.array_equal(cached_region_ids, np.asarray(regions, dtype=int)) + ) + ): return cached_values region_ids = np.asarray(regions, dtype=int) @@ -257,30 +422,38 @@ def _simplex_volume_charge_scales(self, regions: Sequence[int]) -> np.ndarray: ) scales = scale_lookup[inverse] - self._demag_volume_charge_scales_cache = (token, scales) + scales.setflags(write=False) + self._demag_volume_charge_scales_cache = ( + token, + material_token, + regions, + region_ids, + scales, + ) return scales def _nodal_ms_values(self) -> np.ndarray: if self.mesh is None: raise RuntimeError("A mesh must be loaded before using material fields.") - token = self._mesh_geometry_token() + token = (self._mesh_geometry_token(), self._material_state_token()) if self._nodal_ms_values_cache is not None: cached_token, cached_values = self._nodal_ms_values_cache if cached_token == token: return cached_values points = self._mesh_points() - simplices = np.asarray(self.mesh.simplices, dtype=int) + simplices = self._mesh_simplices() if simplices.size == 0 or simplices.ndim != 2 or simplices.shape[1] != 4: default_ms = ( self.materials[0].Ms.in_units_of(_si_unit("A/m")) if self.materials else 0.0 ) nodal_ms = np.full(len(points), default_ms, dtype=float) + nodal_ms.setflags(write=False) self._nodal_ms_values_cache = (token, nodal_ms) return nodal_ms - regions = list(self.mesh.regions or [1] * len(simplices)) + regions = self.mesh.regions if self.mesh.regions else [1] * len(simplices) simplex_ms = self._simplex_material_ms_values(regions) volumes, positive = self._simplex_volume_weights(points, simplices) nodal_ms = np.zeros(len(points), dtype=float) @@ -295,5 +468,6 @@ def _nodal_ms_values(self) -> np.ndarray: nodal_ms[present] /= weights[present] if np.any(~present): nodal_ms[~present] = simplex_ms[positive][0] if np.any(positive) else 0.0 + nodal_ms.setflags(write=False) self._nodal_ms_values_cache = (token, nodal_ms) return nodal_ms diff --git a/src/nmesh/backend.py b/src/nmesh/backend.py index c50b1a5..31a2382 100644 --- a/src/nmesh/backend.py +++ b/src/nmesh/backend.py @@ -113,6 +113,7 @@ def mesh_scale_node_positions(self, raw_mesh: RawMesh, scale: float) -> None: for point in raw_mesh.points: for index, value in enumerate(point): point[index] = value * scale + raw_mesh.points = list(raw_mesh.points) volume_scale = abs(scale) ** raw_mesh.dim raw_mesh.region_volumes = [volume * volume_scale for volume in raw_mesh.region_volumes] diff --git a/src/nmesh/mesh_generation.py b/src/nmesh/mesh_generation.py index e82e148..d6a932e 100644 --- a/src/nmesh/mesh_generation.py +++ b/src/nmesh/mesh_generation.py @@ -16,19 +16,19 @@ def _as_float_points(points: Sequence[Sequence[float]] | None) -> list[Point]: - return [list(map(float, point)) for point in (points or [])] + return [list(map(float, point)) for point in ([] if points is None else points)] def _as_int_simplices(simplices: Sequence[Sequence[int]] | None) -> list[Simplex]: - return [list(map(int, simplex)) for simplex in (simplices or [])] + return [list(map(int, simplex)) for point_list in [simplices] if point_list is not None for simplex in point_list] def _as_region_ids(regions: Sequence[int] | None) -> list[int]: - return [int(region) for region in (regions or [])] + return [int(region) for region in ([] if regions is None else regions)] def _normalise_periodic(periodic: Sequence[bool] | Sequence[float] | None, dim: int) -> list[float]: - if not periodic: + if periodic is None or len(periodic) == 0: return [0.0] * dim return [1.0 if bool(value) else 0.0 for value in periodic] @@ -168,15 +168,15 @@ def extended_fun_driver(self, nr_piece: int, iteration_nr: int, mesh: object) -> def fixed_points(self, points: Sequence[Sequence[float]] | None) -> None: """Adds fixed points to the mesh configuration.""" - if points: + if points is not None and len(points) > 0: self._fixed_points.extend(_as_float_points(points)) def mobile_points(self, points: Sequence[Sequence[float]] | None) -> None: """Adds mobile points to the mesh configuration.""" - if points: + if points is not None and len(points) > 0: self._mobile_points.extend(_as_float_points(points)) def simply_points(self, points: Sequence[Sequence[float]] | None) -> None: """Adds simply points to the mesh configuration.""" - if points: + if points is not None and len(points) > 0: self._simply_points.extend(_as_float_points(points)) diff --git a/src/nmesh/mesh_io.py b/src/nmesh/mesh_io.py index 0c79f05..91a8e99 100644 --- a/src/nmesh/mesh_io.py +++ b/src/nmesh/mesh_io.py @@ -122,7 +122,10 @@ def __init__( points_list, simplices_list, _as_region_ids(simplices_regions), - [list(map(int, group)) for group in (periodic_point_indices or [])], + [ + list(map(int, group)) + for group in ([] if periodic_point_indices is None else periodic_point_indices) + ], do_reorder, do_distribute, ) diff --git a/src/si/physical.py b/src/si/physical.py index 4d37cbc..c25e2c1 100644 --- a/src/si/physical.py +++ b/src/si/physical.py @@ -142,7 +142,11 @@ def __sub__(self, other: Any) -> Any: def __rsub__(self, other: Any) -> Any: if isinstance(other, (int, float)) and float(other) == 0.0: return _FastQuantity(-self.magnitude, self.units) - return _quantity_from_pint(other) - self + other_base = _fast_base_magnitude(other, self.units.dims) + return _FastQuantity( + (other_base - self.to_base_units().magnitude) / self.units.scale, + self.units, + ) def __mul__(self, other: Any) -> Any: if isinstance(other, (int, float)): @@ -354,7 +358,18 @@ def _fast_base_magnitude(other: Any, expected_dims: Dims) -> float: _unit_from_dims(expected_dims), ) return float(other) - return _quantity_from_pint(other).to_base_units().magnitude + pint_other = _quantity_from_pint(other) + expected_pint_unit = ( + _pint_registry().Unit(_compact_from_dims(expected_dims)) + if any(expected_dims) + else _pint_registry().Unit("") + ) + if not pint_other.is_compatible_with(expected_pint_unit): + raise _pint_module().errors.DimensionalityError( + pint_other.units, + _unit_from_dims(expected_dims), + ) + return float(pint_other.to_base_units().magnitude) def _quantity_from_pint(value: Any) -> Any: diff --git a/tests/mag_material_test.py b/tests/mag_material_test.py index 3af82a0..edc3c47 100644 --- a/tests/mag_material_test.py +++ b/tests/mag_material_test.py @@ -108,5 +108,45 @@ def test_str_representation(self): self.assertIn("su_llg_coeff1", s_ext) self.assertGreater(len(s_ext.splitlines()), len(s_std.splitlines())) + def test_fast_quantity_rsub_and_material_mutation_sync(self): + """Test _FastQuantity.__rsub__, Pint compatibility, and MagMaterial mutation sync.""" + import pint + + self.assertAlmostEqual(float(1.0 - SI(0.25)), 0.75) + self.assertEqual(SI(2.0, "km") - SI(500.0, "m"), SI(1500.0, "m")) + self.assertEqual(SI(500.0, "m") - SI(2.0, "km"), SI(-1500.0, "m")) + with self.assertRaises(pint.DimensionalityError): + _ = 1.0 - SI(1.0, "m") + with self.assertRaises(pint.DimensionalityError): + _ = SI(1.0, "m") + SI(1.0, "T") + + mat = MagMaterial( + name="STTMat", + Ms=SI(0.8e6, "A/m"), + llg_damping=0.02, + llg_xi=0.05, + llg_polarisation=0.7, + ) + nadiab_1 = mat.su_llg_stt_nadiab + adiab_1 = mat.su_llg_stt_adiab + exch_1 = mat.su_exch_prefactor + self.assertNotEqual(nadiab_1.in_units_of(SI("m^3/A/s")), 0.0) + self.assertNotEqual(adiab_1.in_units_of(SI("m^3/A/s")), 0.0) + + mat.Ms = SI(1.6e6, "A/m") + self.assertEqual(mat.su_Ms, mat.Ms) + self.assertAlmostEqual( + mat.su_exch_prefactor.value, + 0.5 * exch_1.value, + ) + + mat.do_precession = False + self.assertEqual(mat.su_llg_coeff1, 0.0) + + zero_mat = MagMaterial(name="ZeroMs", Ms=SI(0.0, "A/m")) + self.assertEqual(zero_mat.su_exch_prefactor.value, 0.0) + self.assertEqual(zero_mat.thermal_factor.value, 0.0) + + if __name__ == '__main__': unittest.main() diff --git a/tests/nmag/test_demag_factorization.py b/tests/nmag/test_demag_factorization.py index 86fea77..8cd6f53 100644 --- a/tests/nmag/test_demag_factorization.py +++ b/tests/nmag/test_demag_factorization.py @@ -69,3 +69,219 @@ def test_geometry_invalidation_clears_demag_factorizations(tmp_path, monkeypatch assert simulation._demag_gauge_factorization_cache is None assert simulation._demag_dirichlet_factorization_cache is None + + +def test_scipy_dirichlet_factorization_caches_boundary_stiffness(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv(DEMAG_LINEAR_SOLVER_BACKEND_ENV, "scipy") + from pathlib import Path + + sphere_fixture = ( + Path(__file__).resolve().parents[1] / "fixtures" / "nmag_doc_example1" / "sphere1.nmesh.h5" + ) + material = nmag.MagMaterial(name="Py", Ms=nmag.SI(1.0e6, "A/m")) + simulation = nmag.Simulation(name="factor-dirichlet") + simulation.load_mesh( + str(sphere_fixture), + [("magnetic", material)], + unit_length=nmag.SI(1.0e-9, "m"), + ) + simulation.set_m([1.0, 0.0, 0.0]) + first = np.asarray(simulation.get_subfield("H_demag")) + dirichlet_cache = simulation._demag_dirichlet_factorization_cache + assert dirichlet_cache is not None + assert len(dirichlet_cache) == 4 + + simulation.set_m([0.0, 1.0, 0.0]) + second = np.asarray(simulation.get_subfield("H_demag")) + assert simulation._demag_dirichlet_factorization_cache is dirichlet_cache + assert not np.allclose(first, second) + + +def test_gauge_fixed_sparse_factorization_matches_dense_augmented_solve(monkeypatch): + from nmag.backends import DEMAG_FEM_MATRIX_BACKEND_ENV + from nmag.demag.linear import _factorize_dense_scipy, _factorize_gauge_fixed + + n = 70 + main_diag = np.full(n, 2.0, dtype=float) + main_diag[0] = 1.0 + main_diag[-1] = 1.0 + off_diag = np.full(n - 1, -1.0, dtype=float) + laplacian = np.diag(main_diag) + np.diag(off_diag, 1) + np.diag(off_diag, -1) + + sparse_factorization = _factorize_gauge_fixed(laplacian) + assert sparse_factorization.splu is not None + assert sparse_factorization.gauge_fixed is True + + constraint = np.ones(n, dtype=float) + augmented = np.block( + [ + [laplacian, constraint[:, np.newaxis]], + [constraint[np.newaxis, :], np.zeros((1, 1), dtype=float)], + ] + ) + dense_factorization = _factorize_dense_scipy(augmented) + + rng = np.random.default_rng(42) + div_1d = rng.standard_normal(n) + np.testing.assert_allclose( + sparse_factorization.solve_gauge(div_1d), + dense_factorization.solve_gauge(div_1d), + rtol=1.0e-10, + atol=1.0e-10, + ) + + rhs_1d = rng.standard_normal(n + 1) + np.testing.assert_allclose( + sparse_factorization.solve(rhs_1d), + dense_factorization.solve(rhs_1d), + rtol=1.0e-10, + atol=1.0e-10, + ) + + rhs_2d = rng.standard_normal((n + 1, 3)) + np.testing.assert_allclose( + sparse_factorization.solve(rhs_2d), + dense_factorization.solve(rhs_2d), + rtol=1.0e-10, + atol=1.0e-10, + ) + + monkeypatch.setenv(DEMAG_FEM_MATRIX_BACKEND_ENV, "dense") + forced_dense = _factorize_gauge_fixed(laplacian) + assert forced_dense.splu is None + + +def test_factorize_gauge_fixed_handles_disconnected_components(): + import pytest + + from nmag.demag.linear import _factorize_gauge_fixed, _factorize_scipy + + # Two disconnected 35-node components (n=70 >= 64 sparse threshold) -> rank-deficient submatrix + comp_size = 35 + main_diag = np.full(comp_size, 2.0, dtype=float) + main_diag[0] = 1.0 + main_diag[-1] = 1.0 + off_diag = np.full(comp_size - 1, -1.0, dtype=float) + comp = np.diag(main_diag) + np.diag(off_diag, 1) + np.diag(off_diag, -1) + zeros = np.zeros((comp_size, comp_size), dtype=float) + disconnected = np.block([[comp, zeros], [zeros, comp]]) + + factorization = _factorize_gauge_fixed(disconnected) + assert factorization.splu is None + divergence = np.zeros(2 * comp_size, dtype=float) + divergence[0] = 1.0 + divergence[comp_size - 1] = -1.0 + divergence[comp_size] = 0.5 + divergence[-1] = -0.5 + phi = factorization.solve_gauge(divergence) + assert np.all(np.isfinite(phi)) + np.testing.assert_allclose(disconnected @ phi, divergence, atol=1.0e-10) + + # Scale-relative row-sum check: non-zero row sums at 1e-9 scale must not use node-0 pinning + non_laplacian_nm = disconnected.copy() * 1.0e-9 + non_laplacian_nm[0, 0] += 1.0e-10 + factorization_nm = _factorize_gauge_fixed(non_laplacian_nm) + assert factorization_nm.splu is None + + # Singular 70x70 system in _factorize_scipy falls back to least-squares instead of corrupt splu + singular_70 = disconnected.copy() + scipy_factor = _factorize_scipy(singular_70) + assert scipy_factor.splu is None + sol = scipy_factor.solve(divergence) + assert np.all(np.isfinite(sol)) + np.testing.assert_allclose(singular_70 @ sol, divergence, atol=1.0e-10) + + # 0x0 gauge-fixed system rejects inconsistent non-zero constraint RHS + empty_gauge = _factorize_gauge_fixed(np.zeros((0, 0), dtype=float)) + np.testing.assert_allclose(empty_gauge.solve(np.array([0.0])), [0.0]) + with pytest.raises(np.linalg.LinAlgError): + empty_gauge.solve(np.array([1.0])) + + # Disconnected nanometre-scale (1e-9) stiffness matrix solves accurately via scaled border + from nmag.demag.linear import _solve_gauge_fixed + + disconnected_nm = disconnected.copy() * 1.0e-9 + divergence_nm = divergence * 1.0e-9 + factorization_disc_nm = _factorize_gauge_fixed(disconnected_nm) + phi_disc_nm = factorization_disc_nm.solve_gauge(divergence_nm) + assert np.all(np.isfinite(phi_disc_nm)) + np.testing.assert_allclose(disconnected_nm @ phi_disc_nm, divergence_nm, atol=1.0e-19) + + phi_direct_nm = _solve_gauge_fixed(disconnected_nm, divergence_nm) + assert np.all(np.isfinite(phi_direct_nm)) + np.testing.assert_allclose(disconnected_nm @ phi_direct_nm, divergence_nm, atol=1.0e-19) + + # Non-zero gauge target g in solve(rhs) with constraint_scale != 1.0 + connected_small_nm = comp[:10, :10].copy() * 1.0e-9 + connected_small_nm[0, 0] = 1.0e-9 + connected_small_nm[-1, -1] = 1.0e-9 + small_factor = _factorize_gauge_fixed(connected_small_nm) + rhs_aug = np.zeros(11, dtype=float) + rhs_aug[0] = 1.0e-9 + rhs_aug[9] = -1.0e-9 + rhs_aug[10] = 3.5 + sol_aug = small_factor.solve(rhs_aug) + np.testing.assert_allclose(np.sum(sol_aug[:10]), 3.5, rtol=1.0e-12, atol=1.0e-12) + np.testing.assert_allclose( + connected_small_nm @ sol_aug[:10] + sol_aug[10], + rhs_aug[:10], + atol=1.0e-19, + ) + + +def test_disconnected_nanometre_mesh_demag_consistency_across_backends(tmp_path, monkeypatch): + import nmesh + from nmag.backends import ( + DEMAG_LINEAR_SOLVER_BACKEND_ENV, + DEMAG_SOLVE_CONDITION_DIAGNOSTICS_ENV, + ) + + points = [ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + [10.0, 0.0, 0.0], + [11.0, 0.0, 0.0], + [10.0, 1.0, 0.0], + [10.0, 0.0, 1.0], + ] + simplices = [[0, 1, 2, 3], [4, 5, 6, 7]] + mesh = nmesh.mesh_from_points_and_simplices(points, simplices, [1, 1]) + mesh_path = tmp_path / "disconnected_two_tet.nmesh" + mesh.save(str(mesh_path)) + + monkeypatch.setenv(DEMAG_SOLVE_CONDITION_DIAGNOSTICS_ENV, "1") + results = {} + for backend in ("auto", "numpy", "scipy"): + monkeypatch.setenv(DEMAG_LINEAR_SOLVER_BACKEND_ENV, backend) + sim = nmag.Simulation(do_demag=True) + mat = nmag.MagMaterial( + name="Py", + Ms=nmag.SI(8e5, "A/m"), + exchange_coupling=nmag.SI(1.3e-11, "J/m"), + ) + sim.load_mesh(str(mesh_path), [("region1", mat)], unit_length=nmag.SI(1e-9, "m")) + sim.set_m([1.0, 0.0, 0.0]) + results[backend] = np.asarray(sim.get_subfield("H_demag"), dtype=float) + diag = sim.last_demag_solve_diagnostics + assert diag["phi1_centered_residual_relative_l2"] < 1.0e-12 + + np.testing.assert_allclose(results["auto"], results["scipy"], rtol=1.0e-10, atol=1.0e-6) + np.testing.assert_allclose(results["numpy"], results["scipy"], rtol=1.0e-10, atol=1.0e-6) + + # Single-tetrahedron condition number diagnostic reflects scaled gauge constraint border + single_mesh = nmesh.mesh_from_points_and_simplices(points[:4], [[0, 1, 2, 3]], [1]) + single_path = tmp_path / "single_tet.nmesh" + single_mesh.save(str(single_path)) + sim_single = nmag.Simulation(do_demag=True) + mat_single = nmag.MagMaterial(name="Py", Ms=nmag.SI(8e5, "A/m")) + sim_single.load_mesh(str(single_path), [("region1", mat_single)], unit_length=nmag.SI(1e-9, "m")) + sim_single.set_m([1.0, 0.0, 0.0]) + _ = sim_single.get_subfield("H_demag") + assert sim_single.last_demag_solve_diagnostics["gauge_augmented_condition_number"] < 100.0 + + + + diff --git a/tests/nmag/test_public_caches.py b/tests/nmag/test_public_caches.py index 67873f7..7d80e73 100644 --- a/tests/nmag/test_public_caches.py +++ b/tests/nmag/test_public_caches.py @@ -198,6 +198,12 @@ def test_mesh_points_and_bounds_reuse_geometry_cache(tmp_path, monkeypatch): first_points = sim._mesh_points() second_points = sim._mesh_points() assert second_points is first_points + assert not first_points.flags.writeable + + first_simplices = sim._mesh_simplices() + second_simplices = sim._mesh_simplices() + assert second_simplices is first_simplices + assert not first_simplices.flags.writeable first_bounds = sim._mesh_bounds() second_bounds = sim._mesh_bounds() @@ -207,8 +213,171 @@ def test_mesh_points_and_bounds_reuse_geometry_cache(tmp_path, monkeypatch): sim._invalidate_demag(clear_geometry=True) assert sim._mesh_points_cache is None + assert sim._mesh_simplices_cache is None assert sim._mesh_bounds_cache is None refreshed_points = sim._mesh_points() assert sim._mesh_points_cache is not None assert refreshed_points is sim._mesh_points() + + refreshed_simplices = sim._mesh_simplices() + assert sim._mesh_simplices_cache is not None + assert refreshed_simplices is sim._mesh_simplices() + + +def test_rhs_hot_path_caches_and_lazy_diagnostics(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + mesh_path = tmp_path / "mesh.nmesh" + helpers.write_two_tetra_mesh(mesh_path) + + material = nmag.MagMaterial( + name="Py", + Ms=nmag.SI(1.0e6, "A/m"), + exchange_coupling=nmag.SI(13.0e-12, "J/m"), + ) + sim = nmag.Simulation(name="mvp") + sim.load_mesh(str(mesh_path), [("generated", material)], unit_length=nmag.SI(1e-9, "m")) + sim.set_m(lambda point: [1.0, 0.0, 0.0] if point[0] <= 5.0e-10 else [0.0, 1.0, 0.0]) + + _ = sim._subfield_array("dmdt") + assert sim._last_demag_solve_diagnostics is None + assert sim._last_demag_solve_diagnostics_inputs is not None + assert sim._demag_nodal_recovery_operator_cache is not None + assert sim._exchange_operator_cache is not None + + first_recovery_cache = sim._demag_nodal_recovery_operator_cache + first_exchange_cache = sim._exchange_operator_cache + + sim.set_m(lambda point: [0.0, 1.0, 0.0] if point[0] <= 5.0e-10 else [0.0, 0.0, 1.0]) + _ = sim._subfield_array("dmdt") + assert sim._demag_nodal_recovery_operator_cache is first_recovery_cache + assert sim._exchange_operator_cache is first_exchange_cache + assert sim._last_demag_solve_diagnostics is None + + diagnostics = sim.last_demag_solve_diagnostics + assert diagnostics["phi1_centered_residual_relative_l2"] >= 0.0 + assert sim._last_demag_solve_diagnostics_inputs is None + diagnostics["node_count"] = -999 + assert sim.last_demag_solve_diagnostics["node_count"] > 0 + + # Invalidating nodal material coefficients happens automatically when material parameters change + material.exchange_coupling = nmag.SI(26.0e-12, "J/m") + exchange_doubled = sim._get_exchange_nodal_field() + assert sim._exchange_operator_cache is not first_exchange_cache + assert np.max(np.abs(exchange_doubled)) > 0.0 + + sim._invalidate_demag(clear_geometry=True) + assert sim._demag_nodal_recovery_operator_cache is None + assert sim._exchange_operator_cache is None + + +def test_material_and_geometry_mutations_automatically_invalidate_caches(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + mesh_path = tmp_path / "mesh.nmesh" + helpers.write_two_tetra_mesh(mesh_path) + + material = nmag.MagMaterial( + name="Py", + Ms=nmag.SI(1.0e6, "A/m"), + exchange_coupling=nmag.SI(13.0e-12, "J/m"), + anisotropy=nmag.uniaxial_anisotropy(axis=[0.0, 0.0, 1.0], K1=nmag.SI(1.0e4, "J/m^3")), + ) + sim = nmag.Simulation(name="mvp-invalidation") + sim.load_mesh(str(mesh_path), [("generated", material)], unit_length=nmag.SI(1e-9, "m")) + sim.set_m(lambda point: [1.0, 0.0, 0.0] if point[0] <= 5.0e-10 else [0.0, 1.0, 0.0]) + + h_demag_1 = np.array(sim._get_demag_nodal_field(), copy=True) + nodal_ms_1 = np.array(sim._nodal_ms_values(), copy=True) + anis_field_1, _ = sim._get_anisotropy_fields() + anis_field_1 = np.array(anis_field_1, copy=True) + thermal_1 = material.thermal_factor + + # Mutate Ms and anisotropy on the material without calling set_m() or _invalidate_demag() + material.Ms = nmag.SI(2.0e6, "A/m") + material.anisotropy = nmag.uniaxial_anisotropy( + axis=[0.0, 0.0, 1.0], K1=nmag.SI(4.0e4, "J/m^3") + ) + assert material.thermal_factor != thermal_1 + nodal_ms_2 = sim._nodal_ms_values() + np.testing.assert_allclose(nodal_ms_2, 2.0 * nodal_ms_1) + h_demag_2 = sim._get_demag_nodal_field() + np.testing.assert_allclose(h_demag_2, 2.0 * h_demag_1, rtol=1.0e-10, atol=1.0e-6) + anis_field_2, _ = sim._get_anisotropy_fields() + np.testing.assert_allclose(anis_field_2, 2.0 * anis_field_1, rtol=1.0e-10, atol=1.0e-6) + + # Scale mesh node positions directly without manual cache invalidation + points_before = np.array(sim._mesh_points(), copy=True) + sim.mesh.scale_node_positions(2.0) + points_after = sim._mesh_points() + np.testing.assert_allclose(points_after, 2.0 * points_before) + + # Empty simplex guard in _cell_demag_from_potential and default volume_charge_scales + empty_cell_h = sim._cell_demag_from_potential( + points_after, + np.empty((0, 4), dtype=int), + np.zeros(len(points_after), dtype=float), + ) + assert empty_cell_h.shape == (0, 3) + + simplices = sim._mesh_simplices() + ms_vals = sim._simplex_material_ms_values(sim.mesh.regions) + stiff, div, vols = sim._assemble_demag_fem_system( + points_after, + simplices, + sim._fields["m"], + ms_vals, + ) + assert stiff is not None and len(div) == len(points_after) and len(vols) == len(simplices) + + +def test_low_memory_mode_and_out_of_bounds_recovery_validation(tmp_path, monkeypatch): + import pytest + + from nmag.backends import MEMORY_MODE_ENV + + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("NMAG_ACCELERATOR", "off") + sim = nmag.Simulation(name="mvp-low-mem") + sim.load_mesh( + str(SPHERE1_MESH), + [("sphere", nmag.MagMaterial(name="Py", Ms=nmag.SI(1.0e6, "A/m")))], + unit_length=nmag.SI(1e-9, "m"), + ) + sim.set_m([1.0, 0.0, 0.0]) + default_h = np.asarray(sim.get_subfield("H_demag")) + assert sim._demag_fem_divergence_operator_cache is not None + assert sim._demag_nodal_recovery_operator_cache is not None + + monkeypatch.setenv(MEMORY_MODE_ENV, "low") + sim._invalidate_demag(clear_geometry=True) + low_mem_h = np.asarray(sim.get_subfield("H_demag")) + assert sim._demag_fem_divergence_operator_cache is None + assert sim._demag_nodal_recovery_operator_cache is None + np.testing.assert_allclose(low_mem_h, default_h, rtol=1.0e-10, atol=1.0e-4) + + with pytest.raises(IndexError): + sim._recover_demag_nodal_field_python( + simplices=np.array([[0, 1, 2, 999]], dtype=int), + volumes=np.array([0.0], dtype=float), + cell_h=np.zeros((1, 3), dtype=float), + weights=np.ones(4, dtype=float), + point_count=4, + ) + + # Direct mesh_from_points_and_simplices accepts NumPy arrays + import nmesh + + pts_np = np.array( + [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], + dtype=float, + ) + simps_np = np.array([[0, 1, 2, 3]], dtype=int) + regs_np = np.array([1], dtype=int) + np_mesh = nmesh.mesh_from_points_and_simplices( + points=pts_np, + simplices_indices=simps_np, + simplices_regions=regs_np, + ) + assert len(np_mesh.points) == 4 + +