tensormesh.operator¶
Condenser¶
- class Condenser(dirichlet_mask: Tensor, dirichlet_value: Tensor | None = None)[source]¶
Bases:
ModuleStatic-condensation operator for Dirichlet boundary conditions.
Partitions a global system \(K u = f\) into inner (free) DOFs and outer (Dirichlet) DOFs and condenses the prescribed values into the right-hand side:
\[K_{ii}\, u_i = f_i - K_{io}\, u_o.\]- Parameters:
dirichlet_mask (Tensor) – 1D boolean tensor of shape \([n_{\text{dof}}]\).
Truemarks DOFs whose value is prescribed.dirichlet_value (Tensor, optional) – 1D tensor of shape \([n_{\text{dof}}]\) (a full vector — only the entries where
dirichlet_maskisTrueare read) or \([n_{\text{outer\_dof}}]\) (already restricted to the boundary). Defaults to all zeros.
- dirichlet_value¶
Prescribed values restricted to the boundary, shape \([n_{\text{outer\_dof}}]\). A tensor of this length given to the constructor or to
update_dirichlet()is stored as it is, not copied, so later calls see in-place updates of it; a full-length vector is restricted withdirichlet_mask, which copies (also when every DOF is prescribed, so that the two lengths coincide). The stored tensor keeps the dtype, device and autograd graph it was given:__call__,condense_rhs()andrecover()never reassign or modify it, each casts a local copy to the dtype and device it needs. Only the constructor,update_dirichlet()and module casts such ascondenser.to(...)orcondenser.double()change it.- Type:
- inner_row, inner_col
Row/column indices of the inner block \(K_{ii}\) in local inner-DOF numbering. Populated lazily on the first call.
- Type:
Tensor or None
- ou2in_row, ou2in_col
Row/column indices of the coupling block \(K_{io}\) in local numbering. Populated lazily.
- Type:
Tensor or None
- is_inner_edge, is_ou2in_edge
Boolean masks over the matrix’s COO edge list selecting the \(K_{ii}\) / \(K_{io}\) entries.
- Type:
Tensor or None
- is_inner_dof, is_outer_dof
Boolean masks over the global DOFs.
- Type:
Tensor or None
- n_inner_dof, n_outer_dof, n_dof
DOF counts.
- Type:
int or None
- layout_signature¶
layout_signatureof the matrix the cached layout was computed from (seetensormesh.sparse.mixin): the addresses and version counters of its row and column index tensors, its number of entries and its shape. It identifies these index tensors, not the sparsity pattern: a later matrix is accepted only with the same signature (matrix.has_same_layout) and index tensors of the same shapes and strides.Nonebefore the first call, on a copy (copy.copy,copy.deepcopy,pickle) until its first call, and after a failed layout computation. AlsoNoneafter a call with aDSparseMatrix: that call releases the signature and the held index tensors but keeps the masks andK_ou2in, socondense_rhs()andrecover()still work.- Type:
tuple or None
- K_ou2in¶
Cached \(K_{io}\) block; reused by
condense_rhs().- Type:
SparseMatrix or None
Notes
Condenseris atorch.nn.Module. Its tensor state (dirichlet_mask,dirichlet_value, and the lazily computed index buffers) is registered as PyTorch buffers, socondenser.to(device)/condenser.cuda()/condenser.cpu()move them together with the input system. The index tensors of the layout matrix that the condenser keeps (see below) are not buffers.The first call to
__call__lazily computes the inner / outer edge masks and caches them on the instance, together with thelayout_signatureof the matrix. Subsequent calls reuse the cached layout as long as the inputSparseMatrixhas the same signature (checked viamatrix.has_same_layout) and index tensors of the same shapes and strides. The lazy buffers are registered withpersistent=Falseso they are not saved intostate_dict.The signature identifies the row and column index tensors of the matrix by address and version counter, which identifies a sparsity pattern only while these tensors are alive: once they are freed, their memory can go to the index tensors of another pattern with as many entries, and that matrix then has the same signature. The condenser therefore keeps the row and column index tensors of the matrix its layout was computed from, as plain attributes (not in
state_dict). What stays alive, for the lifetime of the condenser, is the storage behind these two tensors (\(2\,\text{nnz}\) integers, or all of the larger tensor they are views of), on the device they were created on: moving the condenser withcondenser.to(...)does not move it. For a matrix assembled by anElementAssembleror aMixedElementAssemblerthis is storage the assembler caches anyway; other sources, such as aFacetBilinearAssembleror a hand-built matrix, have no such cache. The matrix itself and its values are not kept. A copy (copy.copy,copy.deepcopy,pickle) does not carry these references, since a copied tensor at another address would protect nothing: it has nolayout_signatureand recomputes its layout from the matrix of its next call instead of comparing signatures.Examples
import torch from tensormesh import Mesh, Condenser from tensormesh.assemble import LaplaceElementAssembler mesh = Mesh.gen_rectangle(chara_length=0.2) K = LaplaceElementAssembler.from_mesh(mesh)() f = torch.ones(mesh.n_points, dtype=mesh.dtype) # Homogeneous Dirichlet on the whole boundary condenser = Condenser(mesh.boundary_mask) # Condense: returns (K_inner, f_inner) — note this is __call__, # NOT a separate "condense_matrix" method. K_inner, f_inner = condenser(K, f) # Solve the inner system and recover the full solution u_inner = K_inner.solve(f_inner) u = condenser.recover(u_inner)
For time-dependent boundary data, update the prescribed values between solves via
update_dirichlet(), then re-condense only the right-hand side withcondense_rhs()(cheaper than rebuildingK_inner).- __init__(dirichlet_mask: Tensor, dirichlet_value: Tensor | None = None)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- update_dirichlet(dirichlet_value: Tensor)[source]¶
Replace the cached prescribed boundary values.
Useful for time-dependent or parameter-swept problems where only the right-hand side changes between solves; the cached \(K_{io}\) block (populated by
__call__) is preserved.- Parameters:
dirichlet_value (Tensor) – 1D tensor of shape \([n_{\text{dof}}]\) or \([n_{\text{outer\_dof}}]\), with the same conventions as the
dirichlet_valueargument to__init__(). The values may be complex even if the matrix and the earlier data were real;condense_rhs()andrecover()then return complex results.
- condense_rhs(rhs: Tensor) Tensor[source]¶
Condense the right-hand side only, reusing the cached matrix layout.
\[f_i \leftarrow f_i - K_{io}\, u_o.\]Use this after a first
__call__to re-condensefwhen the matrix is unchanged but the load vector changes (e.g. between time steps).- Parameters:
rhs (Tensor) – Global right-hand side of shape \([n_{\text{dof}}, \ldots]\).
- Returns:
Condensed right-hand side of shape \([n_{\text{inner\_dof}}, \ldots]\), on the device of the cached \(K_{io}\) whatever the device of
rhs. It is complex if the cached \(K_{io}\),rhsor the Dirichlet values are complex, and then has the precision of \(K_{io}\) (float32→complex64,float64→complex128). With real operands it has the dtype of \(K_{io}\), or that ofrhsifrhshas the higher precision (afloat64rhswith afloat32\(K_{io}\) givesfloat64).- Return type:
- Raises:
AssertionError – If
__call__has not been invoked yet: the operator has no cached \(K_{io}\) block to apply.
Notes
rhsand a local copy of the storeddirichlet_valueare moved to the device of \(K_{io}\). With a complex operand, the copy is cast to the precision of \(K_{io}\), staying complex if it is complex and real if it is real, and a real \(K_{io}\) is applied to the real and imaginary parts of complex Dirichlet values separately. With real operands, the copy takes the dtype ofrhsor of \(K_{io}\), whichever has the higher precision, so the values are never rounded to a lower precision than that of \(K_{io}\). The storeddirichlet_valueis neither reassigned nor modified.
- recover(u: Tensor) Tensor[source]¶
Recover the full-DOF solution from an inner-DOF solution.
Scatters the condensed solution
uback into the free-DOF slots and writes the prescribed boundary values into the constrained slots.- Parameters:
u (Tensor) – Inner-system solution of shape \([n_{\text{inner\_dof}}, \ldots]\).
- Returns:
Full-system solution of shape \([n_{\text{dof}}, \ldots]\), on the device of
u, with the dtype ofu, or the complex dtype of the same precision ifuis real and the Dirichlet values are complex.- Return type:
Notes
The boundary entries are a local copy of the stored
dirichlet_value, moved to the device ofuand written in the precision of the result. The stored tensor is neither reassigned nor modified, so the values written here do not depend on the precision or the device of the matrices condensed before. The cached DOF masks are used on the device ofuas well.
- restrict(f: Tensor) Tensor[source]¶
Project a full-DOF vector down to inner DOFs.
Pure linear restriction \(f_i \leftarrow f|_{\text{inner}}\), with no Dirichlet-value correction. Use this when the right-hand side has no implicit Dirichlet contribution to subtract — for example, the per-stage right-hand side of a time-integration scheme such as
tensormesh.ode.ImplicitLinearRungeKutta, where the time-derivative at a Dirichlet DOF is zero by construction and so the \(-K_{io}\,u_o\) term incondense_rhs()would over-apply the boundary correction.Unlike
Condenser.__call__/condense_rhs(),restrictdoes not require the matrix layout to be cached first: it only needsdirichlet_mask.
- prolong(f_inner: Tensor) Tensor[source]¶
Lift an inner-DOF vector up to full DOF with zeros on the boundary.
Pure linear prolongation: inner entries are scattered into the free-DOF slots, constrained slots are filled with zero — not with
dirichlet_value. Use this when the quantity being lifted should vanish on the boundary regardless of the prescribed Dirichlet value, e.g. the per-stage slope of a time integrator (since a fixed-value DOF has zero time-derivative).Like
restrict(),prolongonly needsdirichlet_maskand does not require the matrix layout to be cached first.
BlochReducer¶
- class BlochReducer(points: Tensor | ndarray | Sequence, lattice_vectors: Tensor | ndarray | Sequence, dofs_per_node: int = 1, tol: float | None = None, sign: int = -1)[source]¶
Bases:
ModuleBloch-Floquet periodic reduction of an assembled FEM operator.
- Parameters:
points (array-like, shape
[n_nodes, dim]) – Nodal coordinates of the unit-cell mesh. Opposite periodic faces must carry matching nodes (e.g. a mesh built withgmsh.model.mesh.setPeriodic); a node on the+a_jface is paired with its image one lattice vector back.lattice_vectors (array-like, shape
[n_lat, dim]) – The periodic lattice vectorsa_j(1, 2 or 3 of them). Pass only the directions that are actually periodic — e.g. a single vector for a waveguide periodic in one direction.dofs_per_node (int, optional) –
Number of DOFs per node (1 for scalar acoustics/Helmholtz,
dimfor elasticity, 6 for a 3D frame). Default 1.The components are assumed node-major (component-interleaved): DOF
dof nodeilives at global indexi * dofs_per_node + d, so the global vector is[n0_x, n0_y, n1_x, n1_y, ...]. This is the layout TensorMesh’s vector assemblers and projector produce – theNodeAssemblerintegral is returnedflatten()-ed from shape[n_nodes, dofs_per_node]– so a Bloch reduction of a vector operator assembled byLinearElasticityElementAssemblerlines up with itsK/Mwithout any DOF re-ordering.tol (float, optional) – Absolute coordinate tolerance for node matching (default scales with the bounding box:
1e-7 * diag).sign (int, optional) – Sign convention of the Floquet phase
exp(sign * i k·R);-1(default) givesu(r+R) = exp(-i k·R) u(r)on the master→slave map. The eigenvalues are independent of this choice.
- n_nodes, n_masters
Node counts before / after reduction.
- Type:
- n_dof, n_reduced_dof
DOF counts before / after reduction (
n_* * dofs_per_node).- Type:
Notes
Like
Condenser, this is atorch.nn.Module; the pairing buffers move with.to(device). The pairing is computed once at construction (geometry only);reduce()is called per wavevector.- __init__(points: Tensor | ndarray | Sequence, lattice_vectors: Tensor | ndarray | Sequence, dofs_per_node: int = 1, tol: float | None = None, sign: int = -1)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- reduce(matrix, k)[source]¶
Return the reduced operator
T(k)^H A T(k).- Parameters:
matrix (SparseMatrix or Tensor) – Assembled operator of shape
[n_dof, n_dof](real or complex). ASparseMatrixis reduced sparsely (COO index remap + coalesce) and returns aSparseMatrix; a densetorch.Tensoris reduced densely and returns a dense complextorch.Tensor(handy for hand-assembled systems such as a beam / truss lattice that does not go through the sparse assembler).k (array-like, shape
[dim]) – Wavevector.
- Returns:
Reduced operator of shape
[n_reduced_dof, n_reduced_dof](complex). Reduce a load vector withreduce_rhs().- Return type:
- reduce_rhs(rhs: Tensor, k) Tensor[source]¶
Return the reduced right-hand side
T(k)^H b.The load-vector counterpart of
reduce(): every DOF addsconj(exp(sign i k·R_i)) * b[i]to its master, soreduce(A, k) u_r = reduce_rhs(b, k)is the reduction ofA u = bandrecover()returnsu.- Parameters:
rhs (torch.Tensor, shape
[n_dof, ...]) – Assembled load vector (real or complex); trailing dimensions are carried along, e.g. several right-hand sides as columns.k (array-like, shape
[dim]) – Wavevector.
- Returns:
Shape
[n_reduced_dof, ...](complex).- Return type:
- reduce_mask(mask: Tensor) Tensor[source]¶
Map a DOF mask onto the reduced DOFs.
A reduced DOF is selected when any of the DOFs it stands for is selected. This is what a Dirichlet wall that reaches the periodic boundary needs: pass the result to
Condensertogether withreduce()andreduce_rhs().- Parameters:
mask (torch.Tensor, shape
[n_dof]) – Boolean mask over the full DOFs.- Returns:
Boolean mask of shape
[n_reduced_dof].- Return type:
- reduce_system(K: SparseMatrix, M: SparseMatrix, k)[source]¶
Convenience: reduce a stiffness/mass pair,
(K_r, M_r).
- recover(u_reduced: Tensor, k) Tensor[source]¶
Scatter a reduced-DOF field back to all DOFs with the Floquet phase.
The scatter-back counterpart of
reduce(), named to mirrorrecover():u_full[i] = exp(sign i k·R_i) * u_reduced[master(i)].- Parameters:
u_reduced (torch.Tensor, shape
[n_reduced_dof, ...])k (array-like, shape
[dim])
Wave boundary operators¶
Assembled boundary matrix / load of first-order absorbing and plane-wave-port conditions — see the open-domain wave examples.
- robin_operator(mesh: Mesh, boundary_mask: str | Tensor | None = None, coeff: float | complex | Tensor = 1.0, *, points: Tensor | None = None, quadrature_order: int = 2) SparseMatrix[source]¶
Boundary (Robin / impedance) matrix \(\int_\Gamma c\, N_i N_j\,\mathrm dS\).
- Parameters:
mesh (Mesh)
boundary_mask (str, Tensor, or None) – Which boundary to integrate over (a per-node boolean tensor, a named mask, or
Nonefor the full boundary) — passed toFacetBilinearAssembler.from_mesh.coeff (float, complex, or Tensor) – Impedance/absorption coefficient \(c\); a scalar (e.g.
1j*kfor a first-order absorbing boundary) or a nodal[n_points]field.points (Tensor, optional) – Node coordinates (defaults to
mesh.points).quadrature_order (int, optional) – Facet quadrature order (default
2).
- Returns:
The
[n_points, n_points]boundary matrix.- Return type:
- port_source(mesh: Mesh, boundary_mask: str | Tensor | None = None, incident: float | complex | Tensor = 1.0, *, points: Tensor | None = None, quadrature_order: int = 2) Tensor[source]¶
Port load vector \(\int_\Gamma u_{\text{inc}}\, N_i\,\mathrm dS\).
This is the consistent boundary load of an incident field
incident(a scalar amplitude for a uniform plane-wave port, or a nodal[n_points]field for a shaped one). Multiply by2j*kfor the plane-wave-port RHS.- Returns:
A
[n_points]load vector (nonzero only on the selected boundary).- Return type: