# solver

Thermal solver core: Joule source, steady and transient heat solves.

A pure functional core, independent of how the mesh was made. Inputs are a `skfem.MeshTri` with coordinates in µm, per-element (P0) material arrays in SI units, and named boundary facet groups (`dict[str, NDArray[int]]` of facet indices into `mesh.facets`).

Physics (v1, 2D cross-section of an infinitely long heater):

- The unknown is the temperature **rise** dT above ambient (K), solved with Lagrange elements of degree 2 (default), 1 or 3; there is no absolute temperature in the linear problem.
- `-div(k grad dT) = q` with dT = 0 on the heat-sink facets (Dirichlet), `-k d(dT)/dn = h dT` on convective facets (Robin) and adiabatic everywhere else. The transient adds `rho*c_p d(dT)/dt`.
- The source is per-length Joule heat from a **longitudinal current**: the field E is common to every conductor of a heater, so `q_i = sigma_i E²` exactly and no conduction solve is needed.

Units: every public argument is SI except lengths, which are in µm like the mesh (areas in µm², heater length in µm), and transient times, which are in µs. Internally the weak form is assembled in a µm-consistent system — k in W/(µm·K), q in W/µm³, h in W/(µm²·K), rho\*c\_p in J/(µm³·K), time in s — so dT comes out in K. That conversion happens once, in :class:`HeatOperator`, and nowhere else.

A solved dT is a vector of degrees of freedom (DOFs): the value at every mesh vertex, in `mesh.p` order, then -- for degree 2 and 3 -- the values at the extra Lagrange points on edges and inside triangles, in scikit-fem's order. Its length fixes the degree on a given mesh (:func:`lagrange_degree`), so a field carries its own degree.

scikit-fem is imported lazily so `import gsim.thermal` works without it; the solve paths raise an `ImportError` naming the extra.

Classes:

- **`HeatOperator`** –

  Factorised steady heat operator, reusable across many sources.
- **`JouleSource`** –

  Per-element Joule heat of a longitudinal-current heater.
- **`TransientHistory`** –

  Temperature-rise history of a step-on transient.

Functions:

- **`dof_count`** –

  Number of DOFs of a Lagrange field of one degree on a triangle mesh.
- **`drive_power_per_length`** –

  Convert one heater drive into dissipated power per length (W/m).
- **`element_dofs`** –

  Global DOF indices of every triangle, `(n_local, n_elements)`.
- **`graded_times`** –

  Step-response sample times that start fine and coarsen as it settles.
- **`joule_heat_density`** –

  Spread a heater's power per length over its conductors.
- **`lagrange_degree`** –

  The element degree of a field with `n_dofs` values on `mesh`.
- **`piecewise_linear`** –

  A Lagrange field as vertex values on a refined mesh, for plotting.
- **`rise_time_10_90`** –

  10-90 % rise time of a step response.
- **`shape_values`** –

  Local Lagrange basis functions at points of the reference triangle.
- **`solve_steady`** –

  Steady temperature rise of a 2D cross-section (one-shot).
- **`solve_transient`** –

  Temperature-rise response to a heat source stepped on at t = 0.
- **`step_crossing_time`** –

  First time a step response covers a fraction of its change.
- **`time_constant_1e`** –

  1/e time constant of a step response.

Attributes:

- **`LAGRANGE_DEGREES`** (`tuple[int, ...]`) –

  Element degrees the heat solve supports.

## LAGRANGE\_DEGREES

```python
LAGRANGE_DEGREES: tuple[int, ...] = (1, 2, 3)
```

Element degrees the heat solve supports.

## HeatOperator

```python
HeatOperator(
    mesh: MeshTri,
    conductivity_w_per_mk: ArrayLike,
    *,
    boundary_facets: Mapping[str, ArrayLike],
    sink: str | Sequence[str] = "bottom",
    convective: Mapping[str, float] | None = None,
    degree: int = 2,
)
```

Factorised steady heat operator, reusable across many sources.

Assembles `-div(k grad dT)` with Lagrange elements on a µm mesh, dT = 0 on the `sink` facets (eliminated), a Robin term `h dT` on each `convective` group and adiabatic facets everywhere else, then factorises it once, on the first :meth:`solve`, with `splu(permc_spec="MMD_AT_PLUS_A")`. The problem is linear, so :meth:`solve` costs only a load assembly and two triangular solves; dT scales linearly with q.

Parameters:

- **`mesh`** (`MeshTri`) –

  Triangle mesh, coordinates in µm.
- **`conductivity_w_per_mk`** (`ArrayLike`) –

  Thermal conductivity per element (W/(m·K)), \> 0.
- **`boundary_facets`** (`Mapping[str, ArrayLike]`) –

  Named facet groups, indices into `mesh.facets`.
- **`sink`** (`str | Sequence[str]`, default: `'bottom'` ) –

  Facet group name(s) held at dT = 0 (heat sink).
- **`convective`** (`Mapping[str, float] | None`, default: `None` ) –

  Facet group name -\> heat-transfer coefficient h (W/(m²·K), \>= 0) of a Robin condition towards ambient.
- **`degree`** (`int`, default: `2` ) –

  Lagrange element degree: 1 (linear), 2 (default) or 3. Higher degrees converge faster with mesh size where the field is smooth, at more DOFs per triangle.

Raises:

- `ValueError` –

  On a shape mismatch, a non-positive or non-finite conductivity, an unknown or out-of-range facet group, a negative h, an unsupported degree, or when there is no heat path to ambient (no sink facets and no positive h), which leaves dT undefined.

Methods:

- **`load_vector`** –

  Assemble the load `integral of q phi_j` (W/µm) of a per-element q.
- **`mass_matrix`** –

  Assemble the consistent heat-capacity matrix.
- **`restrict`** –

  Restrict a DOF matrix to the free (non-sink) DOFs.
- **`solve`** –

  Steady temperature rise for one heat source.

### load\_vector

```python
load_vector(heat_w_per_m3: ArrayLike) -> NDArray[float64]
```

Assemble the load `integral of q phi_j` (W/µm) of a per-element q.

Parameters:

- **`heat_w_per_m3`** (`ArrayLike`) –

  Volumetric heat per element (W/m³).

Returns:

- `NDArray[float64]` –

  The load vector, one entry per DOF, in the internal µm units.

Raises:

- `ValueError` –

  On a shape mismatch or non-finite values.

### mass\_matrix

```python
mass_matrix(heat_capacity_j_per_m3k: ArrayLike) -> Any
```

Assemble the consistent heat-capacity matrix.

The matrix is `integral of rho*c_p phi_i phi_j`.

Parameters:

- **`heat_capacity_j_per_m3k`** (`ArrayLike`) –

  Volumetric heat capacity rho\*c\_p per element (J/(m³·K)), \> 0.

Returns:

- `Any` –

  Sparse CSR matrix in the internal µm units (J/(µm·K)).

Raises:

- `ValueError` –

  On a shape mismatch or a non-positive value.

### restrict

```python
restrict(matrix: Any) -> Any
```

Restrict a DOF matrix to the free (non-sink) DOFs.

Parameters:

- **`matrix`** (`Any`) –

  Sparse `(n_dofs, n_dofs)` matrix.

Returns:

- `Any` –

  The free-free block as CSC, ready to factorise.

### solve

```python
solve(heat_w_per_m3: ArrayLike) -> NDArray[float64]
```

Steady temperature rise for one heat source.

Parameters:

- **`heat_w_per_m3`** (`ArrayLike`) –

  Volumetric heat per element (W/m³), e.g. :attr:`JouleSource.heat_density`.

Returns:

- `NDArray[float64]` –

  dT (K) at every DOF; the first `mesh.p.shape[1]` are the
- `NDArray[float64]` –

  vertex values, aligned with the columns of `mesh.p`.
- `NDArray[float64]` –

  Exactly zero on the sink DOFs.

## JouleSource

```python
JouleSource(heat_density: NDArray[float64], field: float, resistance_per_length: float)
```

Per-element Joule heat of a longitudinal-current heater.

Attributes:

- **`heat_density`** (`NDArray[float64]`) –

  Volumetric heat per element (W/m³); zero outside the heater conductors.
- **`field`** (`float`) –

  Longitudinal electric field common to all heater conductors (V/m).
- **`resistance_per_length`** (`float`) –

  Heater resistance per unit length R' = 1 / sum sigma\_i A\_i (ohm/m).

## TransientHistory

```python
TransientHistory(time_us: NDArray[float64], values: NDArray[float64])
```

Temperature-rise history of a step-on transient.

Attributes:

- **`time_us`** (`NDArray[float64]`) –

  Sample times (µs), `steps + 1` values from 0 to the duration; index 0 is the initial state dT = 0.
- **`values`** (`NDArray[float64]`) –

  dT history (K): `(steps + 1, n_dofs)` DOF values when no `sample` was given, else the sampled values stacked along the first axis.

## dof\_count

```python
dof_count(mesh: MeshTri, degree: int) -> int
```

Number of DOFs of a Lagrange field of one degree on a triangle mesh.

Parameters:

- **`mesh`** (`MeshTri`) –

  Triangle mesh.
- **`degree`** (`int`) –

  Element degree, one of :data:`LAGRANGE_DEGREES`.

Returns:

- `int` –

  `n_vertices` for degree 1, plus one per edge for degree 2, plus
- `int` –

  two per edge and one per triangle for degree 3.

Raises:

- `ValueError` –

  On an unsupported degree.

## drive\_power\_per\_length

```python
drive_power_per_length(
    resistance_per_length_ohm_per_m: float,
    *,
    power_per_length_w_per_m: float | None = None,
    power_w: float | None = None,
    voltage_v: float | None = None,
    current_a: float | None = None,
    length_um: float | None = None,
) -> float
```

Convert one heater drive into dissipated power per length (W/m).

With R = R'·L: a total power gives `P/L`; a voltage gives `V² / (R' L²)`; a current gives `I² R'` (independent of L).

Parameters:

- **`resistance_per_length_ohm_per_m`** (`float`) –

  Heater R' (ohm/m), e.g. from :func:`joule_heat_density`.
- **`power_per_length_w_per_m`** (`float | None`, default: `None` ) –

  Drive given directly as P/L (W/m).
- **`power_w`** (`float | None`, default: `None` ) –

  Total dissipated power (W); needs `length_um`.
- **`voltage_v`** (`float | None`, default: `None` ) –

  Voltage across the heater (V); needs `length_um`.
- **`current_a`** (`float | None`, default: `None` ) –

  Current through the heater (A).
- **`length_um`** (`float | None`, default: `None` ) –

  Heater length (µm).

Returns:

- `float` –

  Power per unit length (W/m).

Raises:

- `ValueError` –

  Unless exactly one drive is given, or when a drive that needs `length_um` lacks a positive one.

## element\_dofs

```python
element_dofs(mesh: MeshTri, degree: int) -> NDArray[int64]
```

Global DOF indices of every triangle, `(n_local, n_elements)`.

Rows follow the element's local basis functions: the three vertices first, then edge and interior points.

Parameters:

- **`mesh`** (`MeshTri`) –

  Triangle mesh.
- **`degree`** (`int`) –

  Element degree, one of :data:`LAGRANGE_DEGREES`.

Returns:

- `NDArray[int64]` –

  The DOF index of every local basis function of every triangle.

## graded\_times

```python
graded_times(duration_us: float, steps: int, *, blocks: int = 8) -> NDArray[float64]
```

Step-response sample times that start fine and coarsen as it settles.

`steps` time steps over `duration_us` in `blocks` blocks of equal step count; the step length doubles from one block to the next. A step response changes fastest just after switch-on, so the early steps set the accuracy of its time constants, and one grid then serves any duration long enough to settle. Each block costs one factorisation in :func:`solve_transient`.

Parameters:

- **`duration_us`** (`float`) –

  Simulated time (µs), \> 0.
- **`steps`** (`int`) –

  Number of time steps, \>= `blocks`.
- **`blocks`** (`int`, default: `8` ) –

  Number of blocks, \>= 1; 1 gives constant steps.

Returns:

- `NDArray[float64]` –

  `steps + 1` times from 0 to `duration_us`.

Raises:

- `ValueError` –

  On a non-positive duration or too few steps.

## joule\_heat\_density

```python
joule_heat_density(
    conductivity_s_per_m: ArrayLike,
    heater_mask: ArrayLike,
    element_area_um2: ArrayLike,
    *,
    power_per_length_w_per_m: float,
) -> JouleSource
```

Spread a heater's power per length over its conductors.

The current flows along the waveguide, out of the cross-section, so every heater conductor sees the same field E and carries `J_i = sigma_i E`. With `G' = sum sigma_i A_i` over the heater elements, `P/L = G' E²`, hence `E = sqrt((P/L) / G')` and `q_i = sigma_i E²`: parallel strips split the power in proportion to their conductance.

Parameters:

- **`conductivity_s_per_m`** (`ArrayLike`) –

  Electrical conductivity per element (S/m). Only elements in `heater_mask` are used.
- **`heater_mask`** (`ArrayLike`) –

  Boolean per element, True on the heater conductors.
- **`element_area_um2`** (`ArrayLike`) –

  Area of each element (µm²).
- **`power_per_length_w_per_m`** (`float`) –

  Dissipated power per unit heater length (W/m), \>= 0.

Returns:

- `JouleSource` –

  The per-element heat density, the common field and the
- `JouleSource` –

  resistance per length.

Raises:

- `ValueError` –

  On shape mismatches, a negative power or area, or a heater with no positive conductance.

## lagrange\_degree

```python
lagrange_degree(mesh: MeshTri, n_dofs: int) -> int
```

The element degree of a field with `n_dofs` values on `mesh`.

Parameters:

- **`mesh`** (`MeshTri`) –

  The mesh the field was solved on.
- **`n_dofs`** (`int`) –

  Length of the field's DOF vector.

Returns:

- `int` –

  The degree, one of :data:`LAGRANGE_DEGREES`.

Raises:

- `ValueError` –

  When no supported degree has that many DOFs.

## piecewise\_linear

```python
piecewise_linear(mesh: MeshTri, values: ArrayLike) -> tuple[MeshTri, NDArray[float64]]
```

A Lagrange field as vertex values on a refined mesh, for plotting.

Degree 1 comes back as is; degree p is sampled on the mesh refined p - 1 times, which places a vertex on every Lagrange point.

Parameters:

- **`mesh`** (`MeshTri`) –

  The mesh the field was solved on.
- **`values`** (`ArrayLike`) –

  The field's DOF vector; its length gives the degree.

Returns:

- `tuple[MeshTri, NDArray[float64]]` –

  The (refined) mesh and one value per its vertex.

## rise\_time\_10\_90

```python
rise_time_10_90(t: ArrayLike, y: ArrayLike) -> float
```

10-90 % rise time of a step response.

Levels are taken relative to the first and last samples (the last is assumed settled); each crossing is the first one, linearly interpolated between samples.

Parameters:

- **`t`** (`ArrayLike`) –

  Sample times (any unit; the result has the same unit).
- **`y`** (`ArrayLike`) –

  Response values, same length as `t`.

Returns:

- `float` –

  `t90 - t10`.

Raises:

- `ValueError` –

  On mismatched shapes or a response with no net change.

## shape\_values

```python
shape_values(degree: int, reference_points: NDArray[float64]) -> NDArray[float64]
```

Local Lagrange basis functions at points of the reference triangle.

Parameters:

- **`degree`** (`int`) –

  Element degree, one of :data:`LAGRANGE_DEGREES`.
- **`reference_points`** (`NDArray[float64]`) –

  `(2, N)` points in the reference triangle with vertices (0, 0), (1, 0), (0, 1) -- the second and third barycentric coordinates of a physical point.

Returns:

- `NDArray[float64]` –

  `(n_local, N)` values, rows in the order of :func:`element_dofs`.

## solve\_steady

```python
solve_steady(
    mesh: MeshTri,
    conductivity_w_per_mk: ArrayLike,
    heat_w_per_m3: ArrayLike,
    *,
    boundary_facets: Mapping[str, ArrayLike],
    sink: str | Sequence[str] = "bottom",
    convective: Mapping[str, float] | None = None,
    degree: int = 2,
) -> NDArray[float64]
```

Steady temperature rise of a 2D cross-section (one-shot).

Builds a :class:`HeatOperator` and solves once; build the operator yourself to reuse its factorisation across many sources or powers.

Parameters:

- **`mesh`** (`MeshTri`) –

  Triangle mesh, coordinates in µm.
- **`conductivity_w_per_mk`** (`ArrayLike`) –

  Thermal conductivity per element (W/(m·K)).
- **`heat_w_per_m3`** (`ArrayLike`) –

  Volumetric heat per element (W/m³).
- **`boundary_facets`** (`Mapping[str, ArrayLike]`) –

  Named facet groups, indices into `mesh.facets`.
- **`sink`** (`str | Sequence[str]`, default: `'bottom'` ) –

  Facet group name(s) held at dT = 0.
- **`convective`** (`Mapping[str, float] | None`, default: `None` ) –

  Facet group name -\> h (W/(m²·K)) of a Robin condition.
- **`degree`** (`int`, default: `2` ) –

  Lagrange element degree: 1, 2 (default) or 3.

Returns:

- `NDArray[float64]` –

  dT (K) at every DOF; the vertex values come first, aligned with
- `NDArray[float64]` –

  the columns of `mesh.p`.

## solve\_transient

```python
solve_transient(
    mesh: MeshTri,
    conductivity_w_per_mk: ArrayLike,
    heat_capacity_j_per_m3k: ArrayLike,
    heat_w_per_m3: ArrayLike,
    *,
    duration_us: float | None = None,
    steps: int | None = None,
    time_us: ArrayLike | None = None,
    theta: float = 1.0,
    boundary_facets: Mapping[str, ArrayLike],
    sink: str | Sequence[str] = "bottom",
    convective: Mapping[str, float] | None = None,
    sample: Callable[[NDArray[float64]], ArrayLike] | ArrayLike | None = None,
    degree: int = 2,
) -> TransientHistory
```

Temperature-rise response to a heat source stepped on at t = 0.

Theta-scheme on `M d(dT)/dt + K dT = F` from dT = 0, with F constant for t \> 0: `(M/dt + theta*K) dT_next = (M/dt - (1-theta)K) dT + F`. The time grid is either `steps` constant steps over `duration_us` or the given `time_us` (e.g. :func:`graded_times`); one `splu` factorisation of `M/dt + theta*K` serves every step of the same length. Boundary conditions are those of :class:`HeatOperator`. In this linear model the fall response after switching off from steady state is the complement of the rise, so one run gives both.

Parameters:

- **`mesh`** (`MeshTri`) –

  Triangle mesh, coordinates in µm.
- **`conductivity_w_per_mk`** (`ArrayLike`) –

  Thermal conductivity per element (W/(m·K)).
- **`heat_capacity_j_per_m3k`** (`ArrayLike`) –

  Volumetric heat capacity rho\*c\_p per element (J/(m³·K)).
- **`heat_w_per_m3`** (`ArrayLike`) –

  Volumetric heat per element while on (W/m³).
- **`duration_us`** (`float | None`, default: `None` ) –

  Simulated time (µs), \> 0, with `steps`.
- **`steps`** (`int | None`, default: `None` ) –

  Number of constant time steps, \>= 1, with `duration_us`.
- **`time_us`** (`ArrayLike | None`, default: `None` ) –

  Sample times (µs) instead of `duration_us` and `steps`: strictly increasing, from 0.
- **`theta`** (`float`, default: `1.0` ) –

  1.0 for backward Euler (default, robust for a step drive), 0.5 for Crank-Nicolson (second order, may ring at the step); must lie in \[0.5, 1\]. Backward Euler is first order: it delays a step response by about `dt / 2`, so a time constant read from it is long by about half the step in use at that time.
- **`boundary_facets`** (`Mapping[str, ArrayLike]`) –

  Named facet groups, indices into `mesh.facets`.
- **`sink`** (`str | Sequence[str]`, default: `'bottom'` ) –

  Facet group name(s) held at dT = 0.
- **`convective`** (`Mapping[str, float] | None`, default: `None` ) –

  Facet group name -\> h (W/(m²·K)) of a Robin condition.
- **`sample`** (`Callable[[NDArray[float64]], ArrayLike] | ArrayLike | None`, default: `None` ) –

  What to record per step. `None` keeps the full DOF vector (memory `(steps + 1) x n_dofs`); an array of DOF weights records `weights @ dT`; a callable records `sample(dT)`.
- **`degree`** (`int`, default: `2` ) –

  Lagrange element degree: 1, 2 (default) or 3.

Returns:

- `TransientHistory` –

  The sample times and the recorded dT history.

Raises:

- `ValueError` –

  On invalid materials, boundaries (see :class:`HeatOperator`), time grid, theta or sample weights.

## step\_crossing\_time

```python
step_crossing_time(t: ArrayLike, y: ArrayLike, level: float) -> float
```

First time a step response covers a fraction of its change.

The response is rescaled to run from 0 at its first sample to 1 at its last; the crossing is linearly interpolated between samples.

Parameters:

- **`t`** (`ArrayLike`) –

  Sample times (any unit; the result has the same unit).
- **`y`** (`ArrayLike`) –

  Response values, same length as `t`.
- **`level`** (`float`) –

  Fraction of the change, in \[0, 1\].

Returns:

- `float` –

  The first time the rescaled response reaches `level`.

Raises:

- `ValueError` –

  On mismatched shapes, a response with no net change or a level outside \[0, 1\].

## time\_constant\_1e

```python
time_constant_1e(t: ArrayLike, y: ArrayLike) -> float
```

1/e time constant of a step response.

The time, from `t[0]`, at which the response first covers `1 - 1/e` (\~ 63.2 %) of its change from the first to the last sample; equal to tau for a single exponential.

Parameters:

- **`t`** (`ArrayLike`) –

  Sample times (any unit; the result has the same unit).
- **`y`** (`ArrayLike`) –

  Response values, same length as `t`.

Returns:

- `float` –

  The 1/e time constant.

Raises:

- `ValueError` –

  On mismatched shapes or a response with no net change.
