Python API¶
enable_x64 explicitly enables JAX float64 arrays process-wide. Call it before
constructing meshes or tracing functions; importing HARTMAX does not change precision.
enable_x64, ChannelProblem and Q2DProblem also set JAX’s
jax_default_matmul_precision to 'highest' when it is unset. Float32 matrix
products on Ampere GPUs then run in float32 rather than TensorFloat-32, which
was 3e-4 from float64 on an RTX A4000. A value you set yourself, in
jax.config or through JAX_DEFAULT_MATMUL_PRECISION, is kept.
Solver(dtype="float32") or "float64" (default) selects the precision of a solve and calls
hartmax.configure; float32 is qualified only for the tested low-Hartmann cases, not high-Hartmann validation.
See JAX’s dtype and x64 contract.
import hartmax
result = hartmax.solve(hartmax.duct(2, 32), hartmax.Solver(dtype="float32"))
The package root is the small, stable convenience surface. Advanced workflows live in the module that owns their concepts.
Root API¶
Area |
Names |
|---|---|
Problems |
|
Presets |
|
Runtime |
|
Everything else is imported from its module: Wall, Sides, Open, Thermal from hartmax.problem; Uniform from
hartmax.fields; ChannelProblem, duct_problem, advance from hartmax.core3d; solve_steady_state from
hartmax.steady; make_q2d_case, evolve_q2d, Q2DProblem from hartmax.q2d; WallLayer, the ratios and the units
from hartmax.units. The energy budget is in hartmax.core3d and the analytical profiles in validation/.
solve(problem) accepts a Problem, a Q2D, a ThermalProblem, a ChannelProblem or a Q2DProblem. A duct with
an inlet and an outlet is solved by hartmax.axial.solve_open_duct. A pipe with an inlet and an outlet on the polar grid
(fringe_pipe of validation/open_pipe.py) is solved in the Stokes limit by solve_open_pipe there.
duct_problem(hartmann=..., cells=..., wall_conductance=...) is the ChannelProblem of the
preset duct: a square insulating or Hunt duct with meshes that resolve the layers that exist –
a/Ha against the walls normal to the field, a/sqrt(Ha) against the others – and
solve_steady_state finds its steady state as a differentiable root. advance
runs the same physics as one compiled trajectory when the transient is what is
wanted. The kernel result types expose converged, status, steps,
residual, fields, and diagnostics; specialized solve functions provide
restart, progress, logging, and timing hooks in their owning modules.
Problems, fields and the one verb¶
hartmax.solve(problem, solver=None, output=None, start=None) runs a Problem or a Q2D;
the guide is Problems, solvers and one verb.
hartmax.configure sets the runtime choices that importing the package leaves alone.
What is solved: Problem, its boundaries, and the presets that fill one.
A Problem is a frozen dataclass and a registered pytree. Its leaves are the inputs the
kernels differentiate: the forcing, the flow_rate, the field amplitude (hartmax.fields),
the Q2D state and coefficients, a heat source and the initial temperature, and the numbers of a
conducting Wall (its conductance, or conductivity and thickness, and those of its layers). The
grid, boundary kinds, which walls conduct, cell counts, material properties and scheme names are static,
so jax.grad never returns a silent zero for one; properties become leaves when the kernels take them
traced.
hartmax.solve() translates a problem to ChannelProblem,
ThermalProblem, PipeProblem or
Q2DProblem. The kernel constructors hartmax.core3d.duct_problem() and
hartmax.axial.fringe_duct() are the presets duct() and fringe_duct() passed through channel_kernel().
- class hartmax.problem.Open(profile: tuple | None = None)¶
The inflow-outflow axis (x): inflow at the lower end, free outflow at the upper.
profile=Nonetakes the fully developed profile atProblem.flow_rate; an array over the cross-section is an inlet of its own.
- class hartmax.problem.Problem(grid: Grid, bc: dict[str, Wall | Sides | Open | str] | tuple[Wall | Sides | Open | str, Wall | Sides | Open | str, Wall | Sides | Open | str] = ('periodic', 'wall', 'wall'), density: float = 1.0, viscosity: float = 1.0, conductivity: float = 1.0, B: Uniform | Fringe | Table | Func = Uniform(strength=0.0, direction=(0.0, 1.0, 0.0)), forcing: tuple[float, float, float] = (0.0, 0.0, 0.0), flow_rate: float | None = None, advection: str = 'off', thermal: Thermal | None = None)¶
A duct, channel or pipe: grid, boundaries, material, field and drive.
bchas one entry per axis, a 3-tuple ordict(x=, y=, z=), each"periodic","wall", aWall,SidesorOpen.forcingis the body force (a pressure gradient, positive drives the flow) andflow_ratethe volumetric flux that sets the drive instead (a periodic Stokes duct) or the inlet (anOpenaxis); one of them. A polar grid is a pipe: axes(r, theta, z),"wall"atr, unit material, the field’s strength the transverse one.thermaladds heat transport.
- class hartmax.problem.Q2D(initial_vorticity: ndarray, forcing: ndarray | None = None, viscosity: float = 0.01, hartmann_friction: float = 0.1, length: tuple[float, float] = (6.283185307179586, 6.283185307179586))¶
The periodic Sommeria-Moreau vorticity problem: state, source, viscosity and Hartmann friction.
All four are leaves, differentiable through
hartmax.q2d.evolve_q2d().dtandstepsbelong to thehartmax.solver.Solver.
- class hartmax.problem.Sides(lower: Wall | str = 'wall', upper: Wall | str = 'wall')¶
Different walls at the two ends of an axis.
- class hartmax.problem.Thermal(specific_heat: float, thermal_conductivity: float, reference_temperature: float, expansion_coefficient: float = 0.0, gravity: tuple[float, float, float] = (0.0, 0.0, 0.0), joule_heating: bool = True, advection: str = 'upwind', outlet_backflow: str = 'error', heat_source: float = 0.0, initial_temperature: float = 0.0, hold_flow: bool = False)¶
Heat capacity, conductivity, Boussinesq buoyancy and heating, as
hartmax.thermal.ThermalProblem;hold_flowcarries the heat by the start’s velocity, held (seehartmax.thermal.build_thermal_step()).
- class hartmax.problem.Wall(conductance: float = 0.0, layers: tuple[WallLayer, ...] = (), temperature: float | tuple | None = None, heat_flux: float | tuple | None = None, conductivity: float | None = None, thickness: float | None = None, conducting: bool = False)¶
A no-slip wall at one end of an axis, or at both.
conductanceis the thin-wallc = sigma_w t_w / (sigma L); or giveconductivityandthickness(Lthe grid’s unit), andcis formed from them.layersresolve the wall in cells instead, a tuple ofhartmax.units.WallLayerfrom the fluid outward (absolute conductivity, divided by the fluid’s here).temperatureorheat_flux(outward conductive flux, positive cools; a number or an array over the two other axes) set the thermal condition; neither is adiabatic. Both are static until the thermal kernels take traced data.The numbers of a conducting wall are leaves of the
Problem:conductance,conductivityandthickness, and each layer’s conductivity and thickness (the cells are static), sojax.grad,jax.jvpandjax.vmappass through them. A conductance that is the literal0.0is the insulating wall: it is structure, not a leaf, and a traced one that is zero has no derivative (ValueError; use a small positive value). Underjax.jitthe primal is unknown, so declare a traced conducting wall withconducting=True.
- hartmax.problem.channel(re: float | None = None, ha: float = 0.0, *, R: float | None = None, field: str = 'wall_normal', cells: tuple[int, int, int] = (64, 64, 64), lengths: tuple[float, float] | None = None, stretch: dict | None = None, **fields: object) Problem¶
A plane channel at constant bulk velocity, periodic in x and y, walls normal to z, half-width one.
The unit system has density, conductivity and bulk velocity one, so
viscosity = 1 / Re_avand the field isHa sqrt(viscosity). Give the bulk Reynolds numberre = Re_avor, for a Hartmann channel, Boeck, Krasnov and Zienicke’sR = U0 delta / nu(U0the laminar centreline velocity,delta = 1/Ha), which givesRe_av = R Ha Uav/U0withbulk_ratio().fieldis"wall_normal"(a Hartmann channel, B along z) or"spanwise"(B along y).lengths = (Lx, Ly)default to the row of the BKZ 2007 Table 1 or of Krasnov, Zikanov and Boeck 2011 (spanwise, Re 6667, Ha 30); other cases give them. The wall axis usesstretch(default the KZB blenddict(blend=0.96);dict(beta=2.0)is their tanh grid).flow_rateis the bulk velocity times the section,2 Ly.
- hartmax.problem.duct(ha: float, cells: int = 48, *, wall_conductance: float = 0.0, cells_in_layer: int = 6, walls: dict[str, Wall | Sides | Open | str] | None = None, flow_rate: float | None = None, **fields: object) Problem¶
A square duct of unit half-width at Hartmann number
ha, field along y, periodic in x, asduct_problem().The section resolves the layers that exist,
1/Haat the Hartmann walls (y) and1/sqrt(Ha)at the others, incells_in_layercells each.wall_conductanceis the thin conductance of the Hartmann walls;walls=dict(y=Wall(...), z=...)replacesbcentries (resolved Hunt walls). The drive is a unit pressure gradient unlessflow_rate(the volumetric flux) is given. Any otherProblemfield is a keyword.
- hartmax.problem.fringe_duct(ha: float, wall_conductance: float = 0.0, half_length: float = 3.0, upstream: float = 15.0, downstream: float = 10.0, spacing: float = 0.25, cells: int = 24, cells_in_layer: int = 6, flow_rate: float = 4.0, solenoidal: bool = False, advection: str = 'off', growth: float = 1.1, **fields: object) Problem¶
The ANL fringe (TM-228) in a square duct with an inlet and an outlet, as
hartmax.axial.fringe_duct().The field falls as
B_y = Ha (1 - sin(pi x / 2 x0)) / 2over|x| <= half_lengthand is uniform outside, withupstreamanddownstreamhalf-widths of buffer; the conductance is on all four walls;flow_rate4 is a unit mean velocity.
- hartmax.problem.pipe(ha: float, radial: int = 48, azimuthal: int = 64, *, wall_conductance: float = 0.0, cells_in_layer: int = 6, forcing: float = 1.0) Problem¶
A circular pipe of unit radius in a transverse field of strength
ha, ashartmax.pipe.pipe_problem().
- hartmax.problem.q2d(shape: tuple[int, int] = (64, 64), length: tuple[float, float] = (6.283185307179586, 6.283185307179586), mode: tuple[int, int] = (1, 1), amplitude: float = 1.0, viscosity: float = 0.01, hartmann_friction: float = 0.1) Q2D¶
A Taylor-Green decay case with an exponential rate, the state of
hartmax.q2d.make_q2d_case().
Imposed magnetic fields of a hartmax.problem.Problem: four small pytrees.
Each field samples itself on a grid with sample(grid), which returns what the kernels take (three
numbers or an hartmax.core3d.ImposedField) and a scale that multiplies it. The scale is the
channel the kernels differentiate a field through (field_scale of
hartmax.steady.solve_steady_state()), so a field’s continuous leaf is its amplitude
(Uniform.strength, Fringe.strength, Table.scale): under jax.grad() the field is sampled
at the primal value and scale carries the derivative, exact because the force is linear in the
amplitude. Sampling needs a concrete primal: use jax.grad(), or close over the field under
jax.jit().
- class hartmax.fields.Fringe(strength: float, half_length: float = 3.0, centre: float = 0.0, solenoidal: bool = False)¶
The ANL fringe of
hartmax.core3d.fringe_field(),strengthtimes its profile.
- class hartmax.fields.Func(fn: Callable, params: object = ())¶
A field
fn(x, y, z, params) -> (Bx, By, Bz)sampled at the cell centres;paramsis any pytree.
- class hartmax.fields.Table(path: str, scale: float = 1.0)¶
A tabulated field: an NPZ with
y, z, bx, by, bz(a cross-section) orx, y, z, ..., timesscale.
- class hartmax.fields.Uniform(*value: float, strength: float | None = None, direction: tuple[float, ...] = (0.0, 1.0, 0.0))¶
A uniform field,
strengthtimes the fixed unit vectordirection.Uniform(bx, by, bz)orUniform(strength=, direction=). The derivative is the one through the amplitude; turning the field changesdirection, which is static.
One verb, solve(problem, solver=None, start=None, output=None), over the kernels that exist.
solve() reads a hartmax.problem.Problem (or Q2D) and calls
the kernel it describes, so a concrete problem gives that kernel’s result bit for bit.
method maps to the kernels as follows: stokes is hartmax.steady.solve_compiled()
(hartmax.axial.solve_open_duct() on an Open axis,
hartmax.pipe.solve_pipe() on a polar grid), newton the same with advection on, march the
open duct with advection on solved by the RK3 march instead of Newton (hartmax.axial.solve_open_duct()), euler the
projection step (hartmax.core3d.advance(), or hartmax.thermal.advance_thermal() with
Problem.thermal), rk3 the same step with the three-stage IMEX scheme (hartmax.core3d.RK3, a
mechanical run) and ifrk4 hartmax.q2d.solve_q2d(). auto takes euler if steps
is given, else stokes or newton, which on an open duct is march where hartmax.axial.method_for()
says it is faster; implicit is reserved and raises.
An unsteady run is a loop of compiled chunks (Output.every steps each; one chunk without an
Output), so a run in chunks, or restarted from a record, is the run in one, bit for bit.
jax.grad() through the leaves of a problem runs the implicit derivative of the steady solve.
The factorizations are built on the host from the primal values, so jax.jit() is for the
objective with the problem closed over; the exception is a conducting wall’s numbers, which the Stokes solve
of a periodic duct takes as arguments (their potential factorization is built in the trace).
- class hartmax.solver.Case(problem: object, solver: Solver | None = None, start: object = None, name: str = '', output: Output | None = None)¶
A problem with its solver, start and output, as
hartmax.config.load()reads them from a TOML file.- name: str¶
Alias for field number 3
- problem: object¶
Alias for field number 0
- start: object¶
Alias for field number 2
- exception hartmax.solver.NumericalFailure¶
Raised when a solver produces nonfinite numerical state or a run is rejected.
A rejected run that wrote files carries its
summary.
- class hartmax.solver.Solution(fields: dict, pressure_gradient: object = None, flow_rate: object = None, residual: object = None, iterations: object = None, history: object = None, summary: object = None, status: object = None)¶
The result of
solve();fieldsholds the named arrays and each is also an attribute.velocityis the staggered components;pressure,potential,currents,temperatureandvorticityappear where the run has them.pressure_gradientis the drive of a periodic duct (the body force, or the one that meetsflow_rate),flow_ratethe flux through the first x face,residualthe kernel’s residual norm,statushow a marched open duct ended (hartmax.axial.CONVERGED,STAGNATEDorUNSTEADY) andsummarywhat anOutputwrote tosummary.json(None without one).- fields: dict¶
Alias for field number 0
- flow_rate: object¶
Alias for field number 2
- history: object¶
Alias for field number 5
- iterations: object¶
Alias for field number 4
- pressure_drop(start: float, end: float)¶
The pressure drop between two stations of an open duct.
- pressure_gradient: object¶
Alias for field number 1
- residual: object¶
Alias for field number 3
- status: object¶
Alias for field number 7
- summary: object¶
Alias for field number 6
- class hartmax.solver.Solver(method: str = 'auto', dt: float | None = None, steps: int | None = None, tol: float | None = None, precision: str = 'state', dtype: str = 'float64', checkpoint: bool = True, history: int | None = None, advective_cfl_limit: float | None = None, buoyancy_courant_limit: float | None = None, divergence_tolerance: float = 1e-10, magnetic_damping: str = 'implicit', cfl: float | None = None, statistics: bool = False)¶
How a problem is solved.
dtandstepsare the time step and count of an unsteady run (a steady solve takesdtonly as the pseudo-step of its preconditioner).tolis the relative residual of the steady solve (default 1e-9 in float64 and 1e-5 in float32; the pipe’s 1e-11);Solution.residualis the absolute norm, so it is compared withtoltimes the drive, not withtol. A solve that missestolraises.historyis the stride of the thermal diagnostics returned (default every step; every step is checked against the limits) or of the Q2D frames (default none).precisionis"state"or"mixed",dtype"float64"or"float32";solve()applies it, so a float32 run needsSolver(dtype="float32")andhartmax.configure(dtype="float32")alone does not give one. A heated run is rejected, at its start or at the first step past them, when its advective Courant number exceedsadvective_cfl_limit(default the transport scheme’s own) or its buoyancy Courant numberbuoyancy_courant_limit(default none), or when the start’s divergence exceedsdivergence_tolerance.cflmakesdtthe largest step of a mechanical run and holds each step at that fraction of the scheme’s central-transport limit (hartmax.core3d.advance()); itsdtis an argument of the compiled run, so a new one does not compile.statisticsintegrates the plane averages of a mechanical run inside its scan, through every chunk; the solution’sstatisticsare then their means and covariances (hartmax.core3d.turbulence_statistics()). The sums start at the run’s first step and are plain sums in the state’s dtype: use float64 for variances far below their mean squared, and note a record written without them cannot be resumed with them. A heated run with solid walls refuses them. Only an unsteady projection run takescfl, a heated one underrk3(its Euler step refuses it), and it is held at the smaller ofcfltimes the RK3 limit and the heat transport’sadvective_cfl_limit. Undercflthe log’sendis the latest the run can reach,start + steps * dt.magnetic_dampingis aneulerorrk3run’s Lorentz force (hartmax.core3d.ChannelProblem):"implicit"slows a balanced transient by1 + dt sigma B^2/rho;"explicit"is time-accurate, that product under 2 atdt, so a mechanical run undercflcompiles again for a newdt. Viscosity is implicit in either case.- resolve(problem) str¶
Return the concrete method for
problem, refusing what the kernels cannot do.
- hartmax.solver.solve(problem: object, solver: Solver | None = None, output: Output | None = None, start: object = None) object¶
Solve
problemwithsolver; ahartmax.core3d.ChannelProblemor ahartmax.q2d.Q2DProblemgoes to its kernel.A
hartmax.thermal.ThermalProblem, which may have solid walls theProblemhas not, is an unsteady run at its flow’sdtwith Joule heating alone, from rest at zero temperature, the"steady"flow or a givenThermalState; its temperature is onthermal_gridand so are the ParaView cells, the velocity zero in a wall. An open duct’s flow evolves with it, its rest being the inlet profile carried along the duct and its steady flowhartmax.axial.solve_open_duct()’s. A flow that evolves gives its pressure, as a mechanical run does; a held flow does not.startis the initial state of an unsteady run: for a thermal runNone(rest, at the problem’s initial temperature),"steady"(the steady flow, temperature at rest) or ahartmax.thermal.ThermalState; for a mechanical run a velocity orNone; for either the path of a record, or aStart, which resumes the run that wrote it (bit for bit) or imports its state. A steady solve takes none. ACasebrings its own solver, start and output unless they are given.With an
Outputthe run writes its files (Solution.summaryis the summary); a steady solve writes its fields once. Without one it does no I/O andjax.jit,gradandvmapapply as before.
Where a run goes: restart records, ParaView files, a summary and a log (see docs/how_to/restart_and_output.md).
solve(problem, solver, output=Output("out", every=20)) runs in compiled chunks of 20 steps. An accepted chunk
writes the record {name}_{step:06d}.npz (the state, exactly) and the ParaView file {name}_{step:06d}.vtr
(.vts on a polar grid), gathered in {name}.pvd; the first rejected chunk stops the run and writes only
{name}_{step:06d}_rejected.npz, which imports but does not resume. {name}_summary.json holds accepted,
the rejection and the finite flag, last and largest of each diagnostic, folded chunk by chunk so that it does not
grow with the run; the log is the solver’s text (StreamingSolverLogger, to stderr and {name}.log)
beside a JSON line per chunk in {name}.jsonl. A record resumes the run that wrote it bit for bit, because a
step boundary is the whole state; Start(path=, mode="import") takes only its fields.
- class hartmax.output.Output(dir: str = 'out', name: str = '', every: int = 0, fields: tuple[str, ...] | None = None, paraview: bool = True, restart: bool = True, summary: bool = True, log: bool = True)¶
Where a run is written:
dirand the filename(default the case’s, elserun);everysteps per chunk (0: one chunk).fieldsnames the arrays drawn in ParaView (None: every field the run has);paraview,restart,summaryandlogswitch the four kinds of file.
- class hartmax.output.Start(state: str = 'rest', path: str | None = None, mode: str = 'resume')¶
Where an unsteady run starts:
state"rest"or the"steady"flow, or the record atpath.mode"resume"continues the run that wrote the record (it refuses another problem or solver),"import"takes the state of any record of the same fields.
- hartmax.output.read_record(path: str | Path, template, identity: str | None = None)¶
Return
(state, step)of a record, shaped liketemplate; refuse a record that does not fit.Every leaf must be finite and have the template’s shape and dtype. Given
identitythe load is a resume and the record must come from that problem and solver; without, it is an import.
- hartmax.output.write_pvd(entries: list[tuple[float, str]], out_dir: str | Path, name: str = 'series') Path¶
Gather
(time, file)frames of one series into{name}.pvd.
- hartmax.output.write_record(path: str | Path, state, identity: str, step: int, **notes) Path¶
Write the leaves of
stateexactly, with theidentityof its run, itsstepandnotes(JSON).
- hartmax.output.write_vtk(path: str | Path, grid, **cells) Path¶
Write named cell arrays as a ParaView file; returns
pathwith the.vtror.vtssuffix.gridis aGridor the three axes’ face coordinates. A Cartesian grid is a rectilinear grid (any stretching); a polar grid a structured one, with the points at(r cos t, r sin t, z). Each array is(nx, ny, nz)or has a trailing component axis of three, and is written x fastest.
TOML schema 3: a table is a constructor call (see docs/reference/cli.md).
[problem] is Problem(**table), or preset = "duct" (channel, fringe_duct, pipe, q2d)
with the preset’s arguments; keys are keyword arguments, nested tables nested objects, and kind picks the
class where several fit. load() refuses an unknown key, a missing key, a wrong TOML type or an unknown
kind with the table path; dumps() writes a problem back as the same text; upgrade() converts
schema 1 (thermal) and 2 (case) files.
- hartmax.config.dumps(problem, solver=None, start=None, name: str = '', output=None) str¶
The TOML text of a problem with its solver, start and output, or of a
Case;load()reads it back.startis"steady"or aStart. A lambda, a function defined in a script, a traced value or aThermalStatestart cannot be written.
- hartmax.config.load(path: str | Path, *overrides: str) Case¶
Read a schema 3 file as a
hartmax.solver.Case;overridesare TOML,"solver.steps=100".solve(load(path))runs it.
- hartmax.config.run(path: str | Path, *overrides: str) dict[str, object]¶
Solve a schema 3 file and return its summary: the
summary.jsonof its[output], else its scalars.A rejected run returns its summary too (
acceptedfalse); a run without an[output]raises.
- hartmax.config.upgrade(path: str | Path) str¶
The schema 3 text of a schema 1 (thermal) or schema 2 (case) file.
Schema 1’s
[output],[run]limits and chunk, and[restart]become[output],[solver]and[start]. What schema 3 cannot hold (a schema 2 file’s output, logging and restart) heads the text as comments. A layered duct, a conducting wall and a tabulated or analytic field are refused.
- hartmax.configure(dtype: str | None = None, gpu_gemm: bool = False) None¶
Set the process-wide choices that importing the package leaves alone, each announced once on
hartmax.dtype="float64"enables float64 and pins the matmul precision (enable_x64());"float32"keeps JAX as it is.gpu_gemm=Trueadds--xla_gpu_enable_triton_gemm=falsetoXLA_FLAGS(cuBLAS instead of Triton GEMMs shortens the GPU compile of a steady solve at a small warm cost); XLA reads the flag when the GPU backend starts, so call it before the first array is made, and a flag the user already set is kept.hartmax.solve()callsconfigure(dtype=solver.dtype).
- hartmax.grid.axis(cells: int, lower: float, upper: float, *, beta: float | None = None, ratio: float | None = None, blend: float | None = None, layer_thickness: float | None = None, cells_in_layer: int = 8, max_ratio: float | None = 1.15) ndarray¶
Return the faces of one axis: uniform, or the one stretching asked for.
betaistanh_faces(),ratiogeometric_faces(),layer_thickness(withcells_in_layerandmax_ratio)wall_resolving_faces(), andblend=athe Krasnov-Zikanov-Boeck gridz = a sin(pi xi / 2) + (1 - a) xiof a uniformxi(a = 0.96): the uniform part keeps the central cells and the Poisson conditioning in hand.
Units and wall models¶
Material and nondimensional relations: Hartmann, Reynolds and interaction numbers, wall conductance ratios and wall stacks.
WallLayer is one solid layer of a wall stack; Wall(layers=...) of hartmax.problem resolves a
stack in cells, and the ratios here reduce it to a thin-wall conductance for duct(..., wall_conductance=c).
- class hartmax.units.WallLayer(name: str, conductivity: float, thickness: float, cells: int = 1)¶
Bases:
objectOne solid layer in a fluid-facing electrical wall stack.
- hartmax.units.dynamic_to_kinematic_viscosity(dynamic_viscosity: float, density: float) float¶
Return kinematic viscosity
nu = mu / rhoinm^2/s.
- hartmax.units.effective_pinhole_conductance_ratio(*, intact_conductance_ratio: float, metal_conductance_ratio: float, pinhole_fraction: float) float¶
Return the area-weighted conductance ratio for a pinholed coating.
- hartmax.units.equivalent_single_layer(layers: Sequence[WallLayer], *, name: str = 'equivalent_wall') WallLayer¶
Return one layer with the same tangential surface conductance.
- hartmax.units.hartmann_number(*, magnetic_field: float, length_scale: float, conductivity: float, density: float, kinematic_viscosity: float) float¶
Return
Ha = B a sqrt(sigma / (rho nu)).
- hartmax.units.interaction_parameter(*, magnetic_field: float, length_scale: float, conductivity: float, density: float, velocity: float) float¶
Return
N = sigma B^2 a / (rho U).
- hartmax.units.kinematic_to_dynamic_viscosity(kinematic_viscosity: float, density: float) float¶
Return dynamic viscosity
mu = rho nuinPa s.
- hartmax.units.magnetic_field_from_hartmann(*, hartmann: float, length_scale: float, conductivity: float, density: float, kinematic_viscosity: float) float¶
Return
Bfrom a target Hartmann number using kinematic viscosity.
- hartmax.units.magnetic_reynolds_number(*, velocity: float, length_scale: float, conductivity: float, magnetic_permeability: float = 1.2566370614359173e-06) float¶
Return
Rm = mu0 sigma U a.
- hartmax.units.nested_wall_layer_resolution_summary(layers: Sequence[WallLayer], *, minimum_cells_per_layer: int = 3) dict[str, object]¶
Return mesh-resolution metrics for a wall-layer stack.
- hartmax.units.normal_leakage_ratio(*, coating_conductivity: float, coating_thickness: float, fluid_conductivity: float, length_scale: float) float¶
Return normal shunt ratio
g_perp.
- hartmax.units.normal_stack_leakage_ratio(layers: Sequence[WallLayer], *, fluid_conductivity: float, length_scale: float) float¶
Return the normal leakage ratio for layers in series.
- hartmax.units.reynolds_number(*, velocity: float, length_scale: float, kinematic_viscosity: float) float¶
Return
Re = U a / nu.
- hartmax.units.tangential_stack_conductance_ratio(layers: Sequence[WallLayer], *, fluid_conductivity: float, length_scale: float) float¶
Return the thin-wall tangential ratio for layers in parallel.
- hartmax.units.wall_conductance_ratio(*, wall_conductivity: float, wall_thickness: float, fluid_conductivity: float, length_scale: float) float¶
Return thin-wall tangential conductance ratio
c.
Ducts with an inlet and an outlet¶
Ducts with an inlet and an outlet: the non-periodic axial direction.
The axial axis is the first. Its conditions follow the published practice of HIMAG, FreeMHD, GridapMHD and the 2025 six-code benchmark, chosen so that every solve stays direct and every derivative implicit:
Inlet. The velocity is HARTMAX’s own fully developed profile at the inlet field, solved on the same cross-section and scaled to the imposed flow rate. It is array-valued Dirichlet data on the inlet face (
hartmax.grid.BoundaryCondition). The flow rate is exact and the pressure drop is an output; there is no extra unknown.Outlet. Zero axial gradient of every velocity component and
p = 0. The pressure operator is then non-singular, and the axial axis stays diagonalizable (Neumann at the inlet, Dirichlet at the outlet).No normal current at either end,
dphi/dn = (u x B).n, with the potential’s gauge fixed by removing its mean.
The inlet enters as a lift. The fully developed profile carried unchanged along
the whole duct is discretely divergence free, so the solution is that lift plus
a correction with a zero inlet face. The correction lives in a linear space on
which the Stokes-limit operator is symmetric in the face-volume inner product,
the two end faces owning half a cell each, so the solve is the same
preconditioned conjugate-gradient solve as a periodic duct’s
(hartmax.steady.solve_steady_state()) and differentiates the same way. Far
upstream of a field change the lift is the discrete solution, which is why the
uniform region carries its fully developed gradient.
With advection on, the steady problem is nonlinear and has two solvers,
method="march" and method="newton", chosen by "auto" (method_for()). The march goes to the fixed
point: the IMEX Runge-Kutta stepper of hartmax.core3d (central transport, Crank-Nicolson
damping and viscosity, the exact constrained stage) advances the departure from the lift at a
Courant-limited step, in chunks, until the physical steady residual falls to tolerance of the
lift’s. The march is a fixed point of the step, so its root is the root of the steady residual, whatever the
step. The result carries one of three statuses: converged; stagnated, a residual that stopped
falling above the tolerance, which Kelley and Keyes (1998) report as the failure of pseudo-transient
continuation; and unsteady, a residual that grows or whose change keeps turning, the signature of a
flow with no steady state (a limit cycle or bursts). Newton’s method takes the same residual from the
same Stokes-limit start, each update a preconditioned solvax.gcrot() solve, and is the cheaper where damping
sets the step. Either root is differentiated by the implicit function theorem (solvax.root_solve()) on the
fixed point of one step, its tangent and transposed solves GMRES on that step’s linearization.
- class hartmax.axial.OpenDuctSolution(velocity: tuple[Field, Field, Field], pressure: Field, potential: Field, currents: tuple[Field, Field, Field], magnetic_field: tuple[Field, Field, Field], residual_norm: jnp.ndarray, initial_residual_norm: jnp.ndarray, iterations: jnp.ndarray, status: jnp.ndarray)¶
Fields of an inflow-outflow duct, a pytree;
pressureis the physical one, zero at the outlet.- currents: tuple[Field, Field, Field]¶
Alias for field number 3
- initial_residual_norm: Array¶
Alias for field number 6
- iterations: Array¶
Alias for field number 7
- magnetic_field: tuple[Field, Field, Field]¶
Alias for field number 4
- potential: Field¶
Alias for field number 2
- pressure: Field¶
Alias for field number 1
- residual_norm: Array¶
Alias for field number 5
- status: Array¶
Alias for field number 8
- velocity: tuple[Field, Field, Field]¶
Alias for field number 0
- hartmax.axial.axial_faces(lower: float, upper: float, core: tuple[float, float], spacing: float, growth: float = 1.1) ndarray¶
Faces of spacing
spacingovercore, growing bygrowthper cell into the buffers.Buffer cells stop growing at
8 * spacing; the last cell on each side absorbs the remainder, so the ends land exactly onlowerandupper.
- hartmax.axial.charge_balance(solution: OpenDuctSolution, problem: ChannelProblem) Array¶
Largest net current out of a cell, relative to the largest motional current through a cell.
The motional current
sigma (u x B).nis what the potential balances; the net current is a small difference of it and the potential gradient, so it is the scale the charge equation is solved to.
- hartmax.axial.fringe_duct(*, hartmann: float, wall_conductance: float = 0.0, half_length: float = 3.0, upstream: float = 15.0, downstream: float = 10.0, spacing: float = 0.25, cells: int = 24, cells_in_layer: int = 6, flow_rate: float = 4.0, solenoidal: bool = False, advection: str = 'off', growth: float = 1.1, **controls) ChannelProblem¶
The ANL fringe (TM-228) in a square duct with an inlet and an outlet.
The field falls as
B_y = Ha (1 - sin(pi x / 2 x0)) / 2over|x| <= half_lengthand is uniform outside;upstreamanddownstreamhalf-widths of buffer (15 and 10) separate the ramp from the ends.solenoidal=Falseis TM-228’s field,B_yalone, which is divergence free. The conductance applies to all four walls, and the default flow rate is a unit mean velocity; half-width, density, viscosity and conductivity being one, the Reynolds number is the mean velocity,flow_rate / 4, andN = Ha^2 / Re.growthis the buffer cells’ growth per cell (axial_faces()); with transport keep it at 1 so the buffers stay atspacing(seesolve_open_duct()). This is the kernel problem of the presethartmax.fringe_duct();controlsgo tofully_developed_inlet().
- hartmax.axial.fully_developed_inlet(problem: ChannelProblem, flow_rate: float, *, tolerance: float = 1e-09, **controls) tuple[ndarray, float]¶
Solve the fully developed flow of
problem’s first cross-section at its first cell’s field.The inlet field must be uniform over the cross-section, as it is upstream of a magnet. Returns the axial velocity on that cross-section scaled to
flow_rate, and the axial pressure gradient that drives it (negative for a positive flow). The cross-section, conductances and field are the duct’s own, so upstream of any field change the three-dimensional solution reproduces it to round-off.
- hartmax.axial.mass_balance(velocity: tuple[Field, Field, Field]) Array¶
Largest net volume flux out of a cell, relative to the largest flux through a cell.
- hartmax.axial.method_for(problem: ChannelProblem, cfl: float = 0.9) str¶
The method
autopicks:marchwhile the Courant step of the inlet flow is at most_MARCH_RATIOdamping steps,newtonwhere the field binds harder (numerics notes: four measured ducts).
- hartmax.axial.open_duct(problem: ChannelProblem, flow_rate: float, **controls) ChannelProblem¶
Turn the first axis of
probleminto an inlet and an outlet at the imposedflow_rate.problemsupplies the mesh, walls, field and properties; its first condition and forcing are replaced.controlsgo tofully_developed_inlet().
- hartmax.axial.pressure_drop(pressure: Field, start: float, end: float) Array¶
Mean pressure at
startminus that atend, interpolated linearly between centres.
- hartmax.axial.solve_open_duct(problem: ChannelProblem, *, field_scale: float | jnp.ndarray = 1.0, tolerance: float = 1e-09, max_iterations: int = 36000, method: str = 'auto', max_steps: int = 40000, check: int = 50, cfl: float = 0.9) OpenDuctSolution¶
Solve an inflow-outflow duct; differentiable in
field_scale.In the Stokes limit, one preconditioned conjugate-gradient solve for the correction to the lift, certified on its residual (
tolerancerelative to the lift’s residual); a rejected solve raises eagerly and gives nonfinite fields under tracing.max_iterationsfollows the tolerance rule of #150 (600 restarts of 60).With advection,
methodis"march"(RK3 steps atcfltimes the Courant limit of the current state,checksteps between tests of the steady residual, at mostmax_steps),"newton"or"auto", which ismethod_for();iterationscounts the steps of the march and the Krylov iterations of Newton, andstatusis one ofCONVERGED,STAGNATEDandUNSTEADY; onlyCONVERGEDis a steady state, and its derivatives are the only ones to trust.Central transport needs the axial cells to keep the cell Reynolds number
U dx / nusmall: withfringe_duct()’s default buffer growth the downstream cells reach8 * spacing(cell Reynolds number 66 at Re 33), and at Ha 100 the iteration stalls between Re 31 and 33; withgrowth=1.0it converges.
- hartmax.axial.station_flow_rates(velocity: tuple[Field, Field, Field]) Array¶
The flow rate through every axial face.
- hartmax.axial.station_pressure(pressure: Field) tuple[ndarray, Array]¶
The axial cell centres and the area-mean pressure over each cross-section.
Heat transport¶
Heat transport in the duct fluid: the temperature equation on the Cartesian core.
The equation is
with constant properties in each material, the temperature at the cell centres
of the staggered grid, and its own boundary conditions. The fluid is the only medium unless
solid walls are added (ThermalProblem): a wall otherwise enters through
a prescribed temperature or heat flux, not through its own conduction. Either
way, electrical power entering a conducting wall is not fluid heat.
Viscous heating is omitted.
Boundary conditions. An axis is periodic, or each end prescribes a temperature
or an outward conductive heat flux, independently of the electrical and
mechanical conditions: an electrically insulating wall need not be adiabatic. A
flux enters hartmax.grid.BoundaryCondition as the derivative along the
axis that hartmax.grid.pad() applies, q/k at the lower end and -q/k
at the upper, so a positive outward flux cools through both;
thermal_boundary() makes that conversion.
Conduction. Implicit, through one cell-centred factorization of
I - dt alpha L_0, alpha = k/(rho_0 c_p), under the homogeneous
conditions. The boundary data enter as the fixed lift b = L(0), since
hartmax.grid.pad() is affine and L(T) = L_0(T) + b. The unit shift keeps
the operator nonsingular under insulated and periodic walls, so the solve keeps
the mean: stored heat is never removed as a gauge. With solid walls, the step
solves for its increment by PCG instead (hartmax.poisson.variable_helmholtz()).
Transport. Conservative and first-order upwind: each velocity face carries
u_f T_up, the temperature of the cell the flow comes from, and the transport
term is minus the divergence of those fluxes. A wall face carries none, whatever
its thermal condition; a periodic axis reads its wrap face from the last and the
first cell, so a one-cell axis carries the same flux in and out. Forward in time
on a discretely divergence-free carrier, the update makes no new extremum while
dt times every cell’s outgoing volume-flux rate stays below one; 0.8 is the
documented envelope. Upwinding adds a numerical diffusivity of about |u| h/2,
which is measured against alpha before a heat-transfer number is quoted.
Buoyancy. With expansion coefficient beta and gravity g the force
density -rho_0 beta (T - T_r) g joins the Lorentz force before the division
by density and the projection. It reaches the velocity faces by
the same average as the Lorentz force and is zeroed on wall faces. Without
beta or g there is no force term at all, so the flow is the isothermal
one. The fractional step does not hold every hydrostatic state exactly; the
claim is convergence in the time step.
The developed duct. Along a duct periodic in its flow direction, a uniform
axial heat input makes T = gamma x + theta, and developed_heat()
solves theta once on the cross-section: the bulk, mean and
peak wall temperatures and the Nusselt number of a station, at fixed flow and
heat load, with derivatives. With the walls held at one temperature instead,
the excess over the wall decays along the duct in a fixed shape, and
developed_wall_temperature() finds that shape and its decay rate as the
smallest eigenvalue of the cross-section.
- class hartmax.thermal.DevelopedHeat(temperature: Field, axial_gradient: jnp.ndarray, flow_rate: jnp.ndarray, bulk_temperature: jnp.ndarray, wall_temperature: jnp.ndarray, peak_wall_temperature: jnp.ndarray, wall_heat_flux: jnp.ndarray, hydraulic_diameter: float, nusselt: jnp.ndarray, heat_balance_residual: jnp.ndarray, flux_walls: bool)¶
The thermally fully developed duct of
developed_heat(), at its stationx = 0.temperatureisthetaon the cells. The wall values are taken on the wall faces of the cross-section, means weighted by face area over every transverse wall, heated or not: the wall temperature and the heat flux into the fluid.nusseltisq_w D_h / (k (T_w - T_b)), with the hydraulic diameterD_h = 4 A / P. With an internal source it is an apparent number for that source, not a coefficient of the duct alone. It is NaN, undefined, where|T_w - T_b|is within64 eps (L/h)^2of the largest temperature scale, withL/hthe section’s largest extent over its smallest cell, the conditioning of the solve; the scales are|T_w|,|T_b|,max |theta|, and each heat input’s own,D_h^2 max |rho c_p u gamma| / k,D_h^2 max |q + q_J| / kandD_h max |q_w| / k, so a difference cancelled to rounding is undefined; the temperatures and the balance stay valid.heat_balance_residualisrho c_p gamma Qless the heat entering per unit length, a power per length.With heat-flux walls only,
flux_walls,thetahas an arbitrary constant, its zero mean, andanchored_peaks()gives the physical temperatures.- anchored_peaks(inlet_bulk_temperature: float | Array, length: float) tuple[Array, Array]¶
Return the hottest wall face and hottest cell over
0 <= x <= length, for heat-flux walls.The bulk temperature is
inlet_bulk_temperatureatx = 0, so the temperature isT_in + gamma x + theta - theta_b, the same for any constant added totheta. It is linear inx: each peak is at the endgammarises toward. A prescribed wall temperature fixes the reference itself, so there both are NaN: use its station values. The profile is taken as developed fromx = 0, with no entrance region.
- axial_gradient: Array¶
Alias for field number 1
- bulk_temperature: Array¶
Alias for field number 3
- flow_rate: Array¶
Alias for field number 2
- flux_walls: bool¶
Alias for field number 10
- heat_balance_residual: Array¶
Alias for field number 9
- hydraulic_diameter: float¶
Alias for field number 7
- nusselt: Array¶
Alias for field number 8
- peak_wall_temperature: Array¶
Alias for field number 5
- temperature: Field¶
Alias for field number 0
- wall_heat_flux: Array¶
Alias for field number 6
- wall_temperature: Array¶
Alias for field number 4
- class hartmax.thermal.DevelopedWallTemperature(temperature: Field, eigenvalue: jnp.ndarray, decay_rate: jnp.ndarray, flow_rate: jnp.ndarray, hydraulic_diameter: float, nusselt: jnp.ndarray, eigen_residual: jnp.ndarray, iterations: jnp.ndarray, converged: jnp.ndarray)¶
The duct of
developed_wall_temperature();docs/physics/thermal/developed.mdgives the equations.temperatureis(T - T_w)/(T_b - T_w),eigenvalueisLambdain-L(theta) = Lambda f thetawithf = u/u_mean, andnusseltaverages the wall flux over the held walls.eigen_residualanditerationsaresolvax.inverse_iteration()’s;convergedis its own and the flow’s certificate.- converged: Array¶
Alias for field number 8
- decay_rate: Array¶
Alias for field number 2
- eigen_residual: Array¶
Alias for field number 6
- eigenvalue: Array¶
Alias for field number 1
- flow_rate: Array¶
Alias for field number 3
- hydraulic_diameter: float¶
Alias for field number 4
- iterations: Array¶
Alias for field number 7
- nusselt: Array¶
Alias for field number 5
- temperature: Field¶
Alias for field number 0
- class hartmax.thermal.LoadAttribution(imposed: jnp.ndarray, delivered: jnp.ndarray, conducted: jnp.ndarray, stored: jnp.ndarray, residual: jnp.ndarray, loaded: ThermalDiagnostics)¶
Where a load’s heat goes, by difference at the last step of
load_attribution(); each a power.imposedis the load’s power.deliveredis what it adds to the enthalpy leaving through the outlet, net of the inlet.conductedis what it adds to the conduction out: a prescribed wall flux cancels, so this is what leaks through the inlet and any prescribed-temperature wall, together.storedis what it still adds to storage, zero once steady, andresidualisimposed - delivered - conducted - stored: the two ledgers’ residuals differenced, with the opposite sign, zero to their rounding.loadedis the load-on run’s last diagnostics.- conducted: Array¶
Alias for field number 2
- delivered: Array¶
Alias for field number 1
- imposed: Array¶
Alias for field number 0
- loaded: ThermalDiagnostics¶
Alias for field number 5
- residual: Array¶
Alias for field number 4
- stored: Array¶
Alias for field number 3
- class hartmax.thermal.ThermalDiagnostics(mass_residual: jnp.ndarray, charge_residual: jnp.ndarray, temperature_min: jnp.ndarray, temperature_max: jnp.ndarray, sensible_energy: jnp.ndarray, joule_power: jnp.ndarray, external_power: jnp.ndarray, conductive_heat_out: jnp.ndarray, advective_heat_out: jnp.ndarray, storage_rate: jnp.ndarray, heat_balance_residual: jnp.ndarray, heat_solve_residual: jnp.ndarray, advective_cfl: jnp.ndarray, boussinesq_measure: jnp.ndarray, finite: jnp.ndarray, outlet_backflow_rate: jnp.ndarray, outlet_outflow_rate: jnp.ndarray, outlet_backflow_enthalpy_in: jnp.ndarray, backflow_boundary_valid: jnp.ndarray, buoyancy_courant: jnp.ndarray, conduction_iterations: jnp.ndarray)¶
The scalars of one step, in the problem’s units.
heat_balance_residualisstorage_rate + conductive_heat_out + advective_heat_out - joule_power - external_power, a power, whereadvective_heat_outis the enthalpy the flow carries out through an outlet less what it brings in through the inlet and through returning outlet faces (zero in a closed duct);heat_solve_residualis the largest local residual of the temperature equation, a temperature per time;advective_cflisdttimes the largest outgoing volume-flux rate of the old velocity;boussinesq_measureis the largestbeta |T - T_r|of the old and new temperatures.finitesays every value is a number, not that the step is accepted.At the outlet of an inflow-outflow axis,
outlet_backflow_rateandoutlet_outflow_rateare the volume rates returning and leaving, andoutlet_backflow_enthalpy_inisCtimes the returning rate weighted by the reservoir temperature: whatadvective_heat_outcounts in at the returning faces.backflow_boundary_validis false where the flow returns underoutlet_backflow="error", whose enthalpy in is then reported as zero. All four are zero, and the boundary valid, in a closed duct.buoyancy_courantisdt sqrt(beta |g| G)of the old temperature, the step over the buoyancy time scale, withGthe largest absolute face-normal gradient on any face: one component, not a colocated gradient magnitude. It is zero without buoyancy and counts infinite. The partitioned step is first order in it; in the Benard onset of #252 the critical Rayleigh number reads 1675.9 near 0.4 and 1675.6 near 0.025 (flat to 0.02 % in the step), a calibration of that case, not a general bound.With solid walls (
ThermalProblem) the ledger covers the fluid and the walls: storage and the sensible heat weigh each cell by its ownrho c_p, the conduction out crosses the outer surface, the extremes are over every cell,boussinesq_measureover the fluid’s andbuoyancy_courantover the fluid’s faces, andheat_solve_residualis each cell’s residual over itsrho c_p. The ledger then closes to PCG’s tolerance, relative to the step’s change.conduction_iterations, an integer count outsidefinite, is that solve’s PCG iterations, zero without walls, where the solve is direct.- advective_cfl: Array¶
Alias for field number 12
- advective_heat_out: Array¶
Alias for field number 8
- backflow_boundary_valid: Array¶
Alias for field number 18
- boussinesq_measure: Array¶
Alias for field number 13
- buoyancy_courant: Array¶
Alias for field number 19
- charge_residual: Array¶
Alias for field number 1
- conduction_iterations: Array¶
Alias for field number 20
- conductive_heat_out: Array¶
Alias for field number 7
- external_power: Array¶
Alias for field number 6
- finite: Array¶
Alias for field number 14
- heat_balance_residual: Array¶
Alias for field number 10
- heat_solve_residual: Array¶
Alias for field number 11
- joule_power: Array¶
Alias for field number 5
- mass_residual: Array¶
Alias for field number 0
- outlet_backflow_enthalpy_in: Array¶
Alias for field number 17
- outlet_backflow_rate: Array¶
Alias for field number 15
- outlet_outflow_rate: Array¶
Alias for field number 16
- sensible_energy: Array¶
Alias for field number 4
- storage_rate: Array¶
Alias for field number 9
- temperature_max: Array¶
Alias for field number 3
- temperature_min: Array¶
Alias for field number 2
- class hartmax.thermal.ThermalProblem(flow: ChannelProblem, thermal_conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], specific_heat: float, thermal_conductivity: float, reference_temperature: float, joule_heating: bool = True, expansion_coefficient: float = 0.0, gravity: tuple[float, float, float] = (0.0, 0.0, 0.0), advection: str = 'upwind', outlet_backflow: str = 'error', walls: tuple = ((None, None), (None, None), (None, None)))¶
A flow problem with the fluid’s heat capacity, conductivity and temperature conditions.
flowis unchanged: its grid, time step, mechanics and electrics carry over, andflow.densityis therho_0of the heat capacity.thermal_conditionsholds onehartmax.grid.BoundaryConditionper axis, best built withthermal_boundary(); an axis is periodic exactly where the flow’s is. A polar flow serves the developed pipe ofdeveloped_heat()anddeveloped_wall_temperature()only; its time steps are not qualified, and are refused. Along an inflow-outflow axis the condition is the inlet temperature, a number or a profile, with no conductive flux at the outlet:thermal_boundary("temperature", T_in, upper_kind="heat_flux", conductivity=k).joule_heatingdeposits the fluid’s Joule heat.reference_temperatureis theT_rof the Boussinesq densityrho_0 [1 - beta (T - T_r)]and of the reported sensible heat.expansion_coefficientisbeta, zero for passive transport, andgravitythe gravitational acceleration, pointing down, along the grid’s three axes; whilebeta > 0it has no component along a periodic axis, where no periodic pressure balances its mean.advectionis"upwind", first order;"van_leer", a van Leer-limited second-order face value, bounded by the two cells it lies between;"central", the mean of the two cells, which conserves the temperature’s variance and needs the RK3 step; or"off"for conduction alone, whatever the flow’s own momentum transport.outlet_backflowsays what enters where the flow returns through the outlet of an inflow-outflow axis:"error"refuses such a run, and"reservoir_flux"brings in the reservoir temperature each step is given asbackflow_temperature, a prescribed total heat fluxC u T_res.wallsadds solid walls that conduct and store heat: per axis(lower, upper), eachNoneor ahartmax.core3d.SolidWall, on axes 1 and 2. The temperature then lives onthermal_grid,thermal_conditionshold on its outer surface, and the flow stays on its own grid (docs/physics/thermal/walls.md, “Conduction through solid walls”). A flow withsolid_wallsgives them as the thermal walls, whichwallsmay repeat but not change: the charge and the heat share one grid.- boundary_lift() Field¶
Return
b = L(0), what the boundary data add to the Laplacian of any temperature (no walls).
- conduction() VariableHelmholtz¶
The implicit conduction of the fluid and its walls on
thermal_grid, built on the host.
- diffusion_factorization() FastDiagonalHelmholtz¶
Factorize
I - dt alpha L_0at the cell centres under the homogeneous conditions.Build it once on the host, as
hartmax.core3d.ChannelProblem.viscous_factorizations(); the flow’sprecisionselects the mixed-precision solve. With solid walls, useconduction().
- property diffusivity: float¶
The thermal diffusivity
k / (rho_0 c_p).
- property fluid_block: tuple[slice, slice, slice]¶
The fluid’s cells in
thermal_grid.
- property has_walls: bool¶
Whether any solid wall is resolved, its cells then part of
thermal_grid.
- property heat_capacity: float¶
The volumetric heat capacity
rho_0 c_p.
- on_thermal_grid(data: Array, axes: tuple[int, ...] = (0, 1, 2)) Array¶
Fluid data on the cells, or on the faces, of
axes, padded with zeros ontothermal_grid.
- property thermal_grid: Grid¶
The temperature’s grid: the flow’s, with the cells of any
walls.
- class hartmax.thermal.ThermalState(velocity: tuple[Field, Field, Field], temperature: Field, time: jnp.ndarray, pressure: Field | None = None, statistics: dict | None = None)¶
What a thermal step advances: the staggered velocity, the cell temperature, the time and the pressure.
pressureis the momentum stage’s, on the flow’s cells, ashartmax.core3d.step()returns it, and it starts the next step’s pressure solve as there; zero at rest, and kept as it is by a held flow. A state built without one starts from zero.statistics, when supplied, are the time integrals of the plane averages, including temperature.- pressure: Field | None¶
Alias for field number 3
- statistics: dict | None¶
Alias for field number 4
- temperature: Field¶
Alias for field number 1
- time: Array¶
Alias for field number 2
- velocity: tuple[Field, Field, Field]¶
Alias for field number 0
- hartmax.thermal.advance_thermal(thermal_step: Callable[[ThermalState, Field], tuple[ThermalState, ThermalDiagnostics]], state: ThermalState, heat_source: Field, steps: int, *, checkpoint: bool = True, backflow_temperature: float | Array | None = None, diagnostics: int = 1) tuple[ThermalState, ThermalDiagnostics]¶
Take
stepssteps of a prepared step as one compiled scan; return the end state and the history.diagnosticsis the stride of the history: the diagnostics of everydiagnostics-th step are kept (the last step of each block),steps // diagnosticsof them, andstepsmust be a multiple. The default keeps every step’s.A state that carries
statistics(a fluid without solid walls) integrates the plane averages of velocity and temperature inside the scan, so a run in chunks integrates as the run in one.A step whose new state is not finite is not taken, under either scheme: the run holds the last finite state and its time, while the step’s diagnostics still report.
backflow_temperaturegoes to every step, constant over the call as the heat source is. The carry is the state alone and only the scalar diagnostics are stacked, one per step, so no field history is kept.stepsis static and the heat source is constant over the call.checkpointrecomputes each step in reverse mode rather than storing its intermediates; a differentiated run still keeps one state per step.
- hartmax.thermal.build_thermal_step(problem: ThermalProblem, *, dtype: dtype | type | str, hold_flow: bool = False, force: Callable[[Array], tuple[Field, Field, Field]] | None = None, scheme: Tableau = ((1.0,), (0.0,), (1.0,), 0.0), cfl: float | None = None) Callable[[ThermalState, Field], tuple[ThermalState, ThermalDiagnostics]]¶
Factorize on the host and return the pure step
(state, heat_source) -> (state, diagnostics).dtypemust be the core’s compute dtype,jnp.result_type(float): float64 with x64 enabled before setup, else float32. The step is bound to this problem’s time step, properties, boundary data and precision; rebuild it when any of them changes.heat_sourceis the external heat per unit volume and time on the cells.Under Euler, the default, everything is taken from the old state, a first-order partitioned step: one electric solve gives the Lorentz force and the Joule heat, buoyancy comes from the old temperature, the momentum takes
hartmax.core3d.step()’s predictor and projection with the flow’s implicit viscous factorizations, and the temperature takes its transport by the old velocity, then implicit conduction. Withscheme=RK3(no solid walls, held flow or open axis) the flow and the temperature advance together through the stages ofhartmax.core3d.RK3, each stage’s heat carried by that stage’s velocity, with its buoyancy and Joule heat, second order in time;cflholds the step at that fraction of the scheme’s limit. The projection starts from the state’s pressure and carries the returned pressure forward.hold_flowkeeps the state’s velocity, a steady flow the heat is carried by, without buoyancy, and prepares no viscous inverses: for an inflow-outflow duct, the physical velocity ofhartmax.axial.solve_open_duct(). Without it such a duct’s flow evolves with the heat through the stagehartmax.axial.solve_open_duct()marches, its inlet profile carried as a lift. With buoyancy its outlet holds the hydrostatic pressure of its own last layer of cells (_outlet_hydrostatic()), notp = 0, so a stratified outlet at rest stays at rest; gravity along the open axis is refused.force(t)is a further force density on the velocity faces of the flow’s grid, evaluated at the state’s time, ashartmax.core3d.step()takes it: a manufactured solution’s source, say; a held flow refuses it. The step is marked forload_attribution():hold_flow, andaffine, true for a held flow and"upwind"or"off"transport, where the temperature is affine in the heat source.Beyond the update, the diagnostics apply the temperature’s Laplacian and wall gradients to the new temperature, for
heat_solve_residualandconductive_heat_out, and a divergence each to the new velocity and the currents, formass_residualandcharge_residual, besides their reductions: no further solve.With solid walls the transport runs on
ThermalProblem.thermal_gridwith the velocity padded by zeros, the conduction isThermalProblem.conduction()’s PCG solve for the step’s increment, whose divergence the diagnostics apply, and the buoyancy takes the fluid’s cells.affinethen holds to PCG’s tolerance.
- hartmax.thermal.developed_heat(problem: ThermalProblem, velocity: tuple[Field, Field, Field], heat_source: Field, *, axial_gradient: float | Array | None = None) DevelopedHeat¶
Solve the thermally fully developed temperature of a duct carrying
velocity.The duct is periodic along exactly one axis, the flow’s, and the velocity and heat sources are uniform along it. Then
T = gamma x + thetawithk L(theta) = rho c_p u gamma - q - q_J, one linear solve on the cells; the bulk temperature is weighted by the axial flow. With heat-flux walls only,gammafollows from the heat balancerho c_p gamma Q= heat in per unit length, andthetahas zero mean. A prescribed-temperature wall takes in heat the solve decides, soaxial_gradientmust then be given, and that wall temperature rises along the duct atgammatoo. A uniform axial heat input with a peripherally uniform wall temperature is the H1 condition; a uniform wall heat flux is H2. The flow rate must be positive, whichvalidate_developed_inputs()checks with the rest of the reduction; otherwise the bulk temperature and Nu are NaN, as aregammaand the temperatures of heat-flux walls. Differentiable in the velocity, the heat source andaxial_gradient, and compiled whole byjax.jit(). Withjoule_heatingoff no current is formed.
- hartmax.thermal.developed_wall_temperature(problem: ThermalProblem, velocity: tuple[Field, Field, Field], *, tolerance: float | None = None, max_iterations: int = 2000) DevelopedWallTemperature¶
The thermally fully developed duct with its walls held at one temperature (the T condition).
thetaandLambdaare the smallest eigenpair, bysolvax.inverse_iteration()on the fast-diagonal factorization totolerance(1e-10 in float64, 1e-4 in float32), with its derivative contract. The duct is as fordeveloped_heat(); the held walls share one temperature, a heat-flux wall is adiabatic, and sources and Joule heat are left out.convergedalso certifies the raw flow, in traced arithmetic: a finite positive mean, every cell forward, the same axial velocity on both axial faces and no transverse velocity (to 1e-9 of the largest in float64, 1e-4 in float32). If not, the eigenvalue, the decay rate and the Nusselt number are NaN.
- hartmax.thermal.initial_thermal_state(problem: ThermalProblem, temperature: float | ndarray, velocity: tuple[Field, Field, Field] | None = None, time: float = 0.0) ThermalState¶
Return a state from an explicit temperature, a number or an array over the cells.
The velocity is the flow at rest unless given; a given one must already meet the face constraints and be divergence free, as
validate_thermal_inputs()checks.
- hartmax.thermal.load_attribution(thermal_step: Callable[[ThermalState, Field], tuple[ThermalState, ThermalDiagnostics]], state: ThermalState, background: Field, load: Field, steps: int, *, backflow_temperature: float | Array | None = None) LoadAttribution¶
Run
stepssteps withbackground + loadand withbackgroundalone, and attribute the load.Both runs share the start, the held velocity and so its Joule heat, the inlet and reservoir temperatures and the walls, so their difference is the load’s own response: neither Joule heat nor
backgroundis credited to it. That holds only where the temperature is affine in the heat source: a step ofbuild_thermal_step()withhold_flow=True, constant properties and"upwind"or"off"transport, markedaffine. A flow the load moves, by buoyancy, is not affine in it, nor is van Leer’s face value, a nonlinear function of the temperature even on a held flow. Each is refused, and so is a wrapper of the step that drops its marks, such as a lambda;jax.jitandjax.checkpointkeep them.The load is a heat source on the cells. A heat flux
qthrough a wall is part of the step’s boundary data, so it is in both runs and cancels; to credit it, pass it as the sourceq A / Vin the cells along that wall, with that wall’s flux set to zero. With the transports accepted here the cell temperatures are then the same: a face flux enters its cell’s equation exactly as that source.
- hartmax.thermal.thermal_boundary(kind: str, lower: float | ndarray = 0.0, upper: float | ndarray = 0.0, *, upper_kind: str | None = None, conductivity: float | ndarray | None = None) BoundaryCondition¶
Return the temperature condition of one axis from physical data.
kindnames both ends, or the lower end only whenupper_kinddiffers:"temperature"prescribes the wall temperature,"heat_flux"the conductive heat flux leaving through that end (positive cools), and"periodic"wraps the axis. A flux is stored as the derivative along the axis,q/kbelow and-q/kabove, soconductivity, thekof the cells at that end, is required with any flux end: the fluid’s, or a solid wall’s, or an array over the end where they differ. A condition built for onekdoes not hold the same flux under another. Either value may be an array over the two other axes, in their order; it is copied.
- hartmax.thermal.validate_developed_inputs(problem: ThermalProblem, velocity: tuple[Field, Field, Field], heat_source: Field, *, flow_rate_tolerance: float, velocity_tolerance: float, axial_gradient: float | None = None) None¶
Check a velocity and heat source for
developed_heat()on the host, raisingValueErroron the first fault.The duct is periodic along one axis, one cell long, with a finite
axial_gradientgiven exactly when a wall prescribes its temperature; the fields are finite, of the compute dtype, at their offsets on the problem’s grid. The flow is the reduction’s single throughflow: a flow ratesum A uaboveflow_rate_tolerance, a volume rate; the same on both axial faces, and no transverse velocity or reversed axial velocity, beyondvelocity_tolerance, a speed. Nothing is changed or returned.
- hartmax.thermal.validate_thermal_inputs(problem: ThermalProblem, state: ThermalState, heat_source: Field, *, divergence_tolerance: float, backflow_temperature: float | ndarray | None = None, advective_cfl_limit: float | None = None, buoyancy_courant_limit: float | None = None) None¶
Check a state and heat source on the host before a run, raising
ValueErroron the first fault.Grids, offsets and shapes; the core’s compute dtype; finite values; the wall and periodic face constraints; a velocity divergence within
divergence_tolerance, in inverse time; with transport, a Courant numberdt max(sum_f max(u_f . n_f, 0) A_f / V)withinadvective_cfl_limit, by default the scheme’s own, 0.8 for"upwind", inside its bound of one for no new extremum, and for"van_leer"0.5, a tested envelope rather than a derived bound; and, at an outlet with transport, no returning face underoutlet_backflow="error", or a finite, realbackflow_temperatureof the outlet’s shape under"reservoir_flux"; and, givenbuoyancy_courant_limit, the start’sbuoyancy_courant(ThermalDiagnostics) within it. Nothing is changed or returned.A held flow keeps its Courant number for the whole run. An evolving flow is checked at its start only, which a start from rest passes trivially; compare the
advective_cfleach step ofadvance_thermal()reports with the limit, ashartmax.solver.solve()does at every step.
Fast-diagonal Poisson and Helmholtz solvers¶
Direct Poisson solves by fast diagonalization on a tensor-product grid.
The finite-volume Laplacian of hartmax.ops separates: on a tensor-product
grid it is the Kronecker sum of three one-dimensional operators. Each of those is
symmetric once the cell widths are folded in, so diagonalizing them on the host
turns a Poisson solve into three tensor contractions and one elementwise divide.
The cost is a handful of matrix multiplies rather than an iteration whose count
depends on the Hartmann number, the result is exact to round-off rather than to a
tolerance, and the solve is a linear map, so it differentiates for free.
The one-dimensional operators are read out of hartmax.ops itself, by applying
the assembled Laplacian to unit vectors on a grid that is one cell wide across
the other two axes. The factorization therefore cannot drift away from the
stencil the rest of the code uses.
A pure Neumann or fully periodic problem determines its solution only up to a constant. The compatible component is removed from the right-hand side and the returned field has zero volume-weighted mean.
The factorization represents the homogeneous operator. Inhomogeneous boundary data is affine, not linear, so it belongs in the right-hand side; passing a condition that carries a value is refused rather than silently linearized.
precision="mixed" runs the contractions of a float64 solve in float32 and
recovers float64 accuracy by defect correction: the residual against the
assembled operator is formed in float64 and solved again in float32,
refinements times (solvax.iterative_refinement()). The orthogonal
transforms keep their relative accuracy mode by mode, so the shifted viscous
operator reaches the float64 floor after one correction; the singular
Laplacian on a layer-resolving mesh contracts more slowly and takes two, which
are the factory defaults. The contraction assumes true float32
matmuls; on Ampere GPUs pin jax_default_matmul_precision to "float32",
because TensorFloat-32 stalls the correction near 1e-4. Float32 states are
solved in float32 as before.
The fully developed pipe built on the polar solver lives in hartmax.pipe;
its public names stay importable from here.
- class hartmax.poisson.FastDiagonalHelmholtz(grid: Grid, offset: tuple[float, float, float], conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], shift: float, coefficient: float, vectors: tuple[ndarray, ndarray, ndarray], values: tuple[ndarray, ndarray, ndarray], scales: tuple[ndarray, ndarray, ndarray], slices: tuple[slice, slice, slice], precision: str = 'state', refinements: int = 1)¶
A factorized
shift * I - coefficient * laplacianfor one staggered position.This is what an implicit viscous solve needs. The operator separates exactly as the pressure Laplacian does, so the same host-side eigendecomposition turns the solve into three contractions and a divide, and the step is no longer bounded by the mesh.
- solve(rhs: Field) Field¶
Return the field this operator maps to
rhs.Prescribed entries are returned as zero: they are boundary data the caller owns, not unknowns this solve may set.
- class hartmax.poisson.FastDiagonalPoisson(grid: Grid, conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], vectors: tuple[ndarray, ndarray, ndarray], values: tuple[ndarray, ndarray, ndarray], scales: tuple[ndarray, ndarray, ndarray], singular: bool, precision: str = 'state', refinements: int = 2, corrections: int = 0)¶
A factorized Laplacian that solves
laplacian(u) = rhsin three contractions.- residual_norm(solution: Field, rhs: Field) Array¶
Return the maximum absolute residual of a candidate solution.
- solve(rhs: Field) Field¶
Return the field whose Laplacian is
rhs.
- class hartmax.poisson.FastDiagonalPolarPoisson(grid: Grid, conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], radial_vectors: ndarray, radial_values: ndarray, radial_scale: ndarray, axial_vectors: ndarray, axial_values: ndarray, axial_scale: ndarray, singular: bool, shift: float = 0.0, coefficient: float = -1.0, precision: str = 'state', refinements: int = 2, wall_conductance: float = 0.0)¶
A factorized polar Laplacian: one radial eigendecomposition per azimuthal mode.
- solve(rhs: Field) Field¶
Return the field this operator maps to
rhs.The operator is
shift*I - coefficient*laplacian; the Poisson factory passes(0, -1), which leaves the Laplacian itself.
- solve_with_wall(rhs: Field) tuple[Field, Field]¶
Return the cell potential and, on the radial faces, the outer thin wall’s potential.
As
hartmax.ops.thin_wall_current()reads it: the outer entry is the sheet, the inner entry repeats the adjacent cell so it carries no current.
- class hartmax.poisson.FastDiagonalThinWallPoisson(grid: Grid, conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], vectors: tuple[ndarray, ndarray, ndarray], values: tuple[ndarray, ndarray, ndarray], scales: tuple[ndarray, ndarray, ndarray], singular: bool, precision: str = 'state', refinements: int = 2, corrections: int = 0, operators: tuple[ndarray, ...] = (), weights: tuple[ndarray, ...] = (), corner_gain: ndarray | None = None, pads: tuple[tuple[int, int], ...] = ((0, 0), (0, 0), (0, 0)), fractions: tuple[tuple[float, float], ...] | None = None, corner_fix: tuple | None = None)¶
The potential Laplacian closed by thin conducting walls, factorized exactly.
Each conducting axis carries a sheet node at both walls (
assemble_thin_wall_operator()), so the solve is still three contractions and a divide, symmetric in the cell volumes extended byctimes the wall area. Where two conducting walls meet, the corner node joins the two sheets in series, so the charge one delivers is what the other receives (Hua et al. 1988 split the corner the same way). The Kronecker sum would also let that node conduct along the edge, which has no sheet area; a rank-four Woodbury correction per mode of the third axis removes it, and vanishes when that axis does not vary.- solve(rhs: Field) Field¶
Return the cell potential whose charge balance is
rhs.
- solve_with_walls(rhs: Field) tuple[Field, tuple[Field | None, Field | None, Field | None]]¶
Return the cell potential, with zero volume mean, and each conducting axis’s sheet potentials.
Sheet potentials come back on the faces normal to their axis, as
hartmax.ops.thin_wall_current()reads them: wall entries set, interior zero.
- class hartmax.poisson.VariableHelmholtz(grid: Grid, conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], shift: ndarray | None, coefficient: float, conductances: tuple[ndarray, ndarray, ndarray], preconditioner: FastDiagonalHelmholtz | FastDiagonalPoisson, max_steps: int = 200, tolerance: float | None = None)¶
V (shift x - coefficient div(G grad x))on cell-wise coefficients, solved by SOLVAX.SOLVAX 0.34.0’s
separable.flux_form_operatoris the same operator; this one stays until SOLVAX takes an axis with mixed ends (uwplasma/SOLVAX#172). HARTMAX keeps the materials andconjugate_grid.The face-conductance contract, stated once.
Gis each face’s conductance per unit area, the harmonic mean of its two half cells (hartmax.ops.face_conductivity()), soGtimes the gradient over the centre distance is the series resistance of the two half cells: what leaves one cell enters the next, and a material interface is a series resistance. The face area and the cell volume enter once, in the divergence. A boundary face takes its cell’s conductivity, which a Neumann datum, a gradient, is multiplied by. With a positiveshiftthe operator is symmetric positive definite: an implicit conduction step through solid walls,shiftthe cells’rho c_pandcoefficientthe time step. Withshift=Noneit is the charge balance through them, insulated or periodic everywhere and so singular: only the compatible part of a right-hand side is solved, for zero volume mean, preconditioned by the fast-diagonal Poisson inverse, and a right-hand side with a net source is refused (defect()).conditionsare homogeneous; boundary data enter throughlift().with_coefficients()takes other cell values in the trace.- apply(values: Array) Array¶
The operator,
V (shift x - coefficient div(G grad x)), without the first term when singular.
- defect(rhs: Array) Array¶
The volume mean of
rhs, which a singular solve’s gauge would remove: rounding for a compatible right-hand side, such as a charge balance through insulated walls, and a net source otherwise.
- divergence(values: Array, conditions=None) Array¶
div(G grad x)per unit volume, underconditions.
- face_fluxes(values: Array, conditions=None) tuple[Field, Field, Field]¶
G grad xon the faces of each axis, underconditions, the homogeneous ones by default.
- lift(conditions) Array¶
What the boundary data of
conditions, of the operator’s own kinds, add todivergence().
- solve(rhs: Array) tuple[Array, Array]¶
Return
xwithshift x - coefficient div(G grad x) = rhs, and the PCG iterations; NaN unconverged.PCG starts from zero and stops at
toleranceofrhs, by default 1e-11 in float64 and 1e-5 in float32, so a time step solves for its increment.solvax.pcg_linear_solve()differentiates it implicitly, its tangent and adjoint solves also from zero. Singular, it solves the operator plusa V (V . x) / sum V, positive definite, with the preconditioner exact on the constants; removing the volume mean after leaves the compatible part’s solution, so every solve converges, a right-hand side compatible only to rounding included; one whose volume mean exceeds rounding, a net source the gauge would absorb, gives NaN.
- with_coefficients(conductivity=None, shift=None) VariableHelmholtz¶
The operator at other cell conductivities or shifts, built in the trace from
jnparrays.Either may be traced, so a wall’s conductivity or heat capacity is a leaf of
solve()and a new value does not recompile. The preconditioner keeps the volume means it was built at: it only steers the iteration.
- hartmax.poisson.assemble_axis_laplacian(grid: Grid, axis: int, condition: BoundaryCondition) ndarray¶
Return the dense one-dimensional Laplacian
hartmax.opsapplies alongaxis.The other two axes are collapsed to a single cell with a homogeneous Neumann condition, which contributes nothing, so the result is exactly the stencil the three-dimensional operator uses along
axis.
- hartmax.poisson.assemble_radial_laplacian(grid: Grid, condition: BoundaryCondition) ndarray¶
Return the dense radial Laplacian the polar flux form applies.
The azimuth is collapsed to a single periodic cell, which contributes nothing because its two faces carry the same value, and the axial direction to a single cell with a homogeneous Neumann condition. The metric factors of the azimuth and the axis cancel between the face areas and the cell volume, so what is left is exactly
(1/r) d/dr (r d/dr)as the production stencil discretizes it, including the zero-area face on the axis.
- hartmax.poisson.assemble_staggered_axis_operator(grid: Grid, axis: int, offset: tuple[float, float, float], condition: BoundaryCondition) ndarray¶
Return the dense one-dimensional operator
hartmax.opsapplies alongaxis.As with
assemble_axis_laplacian(), the other axes are collapsed to a single cell under a homogeneous Neumann condition so they contribute nothing, and the operator is read out of the production stencil rather than written a second time.
- hartmax.poisson.assemble_thick_wall_operator(grid: Grid, axis: int, layers: tuple) tuple[ndarray, ndarray, tuple[float, float]]¶
Return the one-dimensional potential operator with a wall resolved in cells at each end, and its weights.
layersis(lower, upper):Nonefor an insulating wall, else(ratios, widths), each cell’s conductivity over the fluid’s (one number for all) and its width, from the fluid outwards, insulated outside; adjacent cells join through their half cells in series. A wall cell is weighted by the ratio times its width, so the tangential axes conduct through it at the wall’s conductivity and the operator stays a Kronecker sum, as forassemble_thin_wall_operator(); the wall must span the fluid’s tangential extent. The fluid reaches the first wall cell through the two half cells in series. Also returned, per end, is the fraction of the potential difference across the fluid’s half cell, whichFastDiagonalThinWallPoisson.solve_with_walls()uses to report the interface potentialhartmax.ops.thin_wall_current()reads. Ratios and widths may be traced: the links are added to the operator one by one, in the order the host path always used.
- hartmax.poisson.assemble_thin_wall_operator(grid: Grid, axis: int, conductance: tuple) tuple[ndarray, ndarray]¶
Return the one-dimensional potential operator with a sheet node on each conducting wall, and its weights.
A thin wall of conductance ratio
chas a potential of its own: the fluid reaches it across the half cell,j_n = (phi_P - phi_w)/(h_P/2), and the sheet carries that current along itself,j_n = -c lap_t phi_w(Walker’s condition). The sheet is one more node on the wall-normal axis, weighted byctimes the wall’s face measure where a cell is weighted by its own measure, so the tangential axes act on it as on a cell and the operator stays a Kronecker sum. The rows are read out of the production stencil: the coupling is the difference between the prescribed-value and the insulating wall cell. An end with zero conductance gets no node. Only the sheet’s row depends onc, so a tracedc(an array result) is added to the host-built remainder.
- hartmax.poisson.azimuthal_eigenvalues(grid: Grid) ndarray¶
Return the eigenvalue of the azimuthal second difference for every mode.
The discrete Fourier basis diagonalizes a uniform periodic second difference, so mode
mcontributes-4 sin^2(pi m / N) / dtheta^2divided byr^2. That last division is what stops the polar Laplacian separating into a sum of one-dimensional operators – and what makes it separate again once the azimuth is transformed, one radial operator per mode.
- hartmax.poisson.fast_diagonal_helmholtz(grid: Grid, offset: tuple[float, float, float], conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], *, shift: float = 1.0, coefficient: float = 1.0, precision: str = 'state', refinements: int = 1) FastDiagonalHelmholtz¶
Factorize
shift * I - coefficient * laplacianat one staggered position.precision="mixed"solves float64 right-hand sides in float32 withrefinementsfloat64 corrections (module docstring).
- hartmax.poisson.fast_diagonal_poisson(grid: Grid, conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], *, precision: str = 'state', refinements: int = 2) FastDiagonalPoisson¶
Factorize the separable Laplacian for
gridunderconditions.precision="mixed"solves float64 right-hand sides in float32 withrefinementsfloat64 corrections (module docstring).
- hartmax.poisson.fast_diagonal_polar_poisson(grid: Grid, conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], *, shift: float = 0.0, coefficient: float = -1.0, precision: str = 'state', refinements: int = 2, wall_conductance: float = 0.0) FastDiagonalPolarPoisson¶
Factorize
shift*I - coefficient*laplacian, one eigendecomposition per azimuthal mode.The default leaves the Laplacian itself. A positive shift with a positive coefficient is the damped operator that preconditions a pipe at large Hartmann number.
precision="mixed"solves float64 right-hand sides in float32 withrefinementsfloat64 corrections (module docstring).wall_conductancecloses the outer radius of the potential Laplacian with a thin conducting wall: a sheet node on the radial operator (assemble_thin_wall_operator()) that sees the azimuthal eigenvalue at the wall radius, so each mode is still one eigendecomposition.
- hartmax.poisson.fast_diagonal_thin_wall_poisson(grid: Grid, conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], conductance: tuple[float, float, float], *, precision: str = 'state', refinements: int = 2, layers: tuple | None = None) FastDiagonalThinWallPoisson¶
Factorize the potential Laplacian with a thin wall of ratio
conductance[axis]on both walls of an axis.conductanceand thelayersratios and widths may be traced: the wall axis is then diagonalized in the trace and the result is a pytree of its arrays, differentiable in them. A traced entry conducts (whether an end conducts is static); two resolved walls (_corner_fix()) cannot be traced. Zero keeps the insulating closure ofconditions; a conducting axis must have insulating (Neumann) walls to replace, and one axis at least must not conduct.layersgives axes walls resolved in cells instead (assemble_thick_wall_operator()),(lower, upper)per axis orNone, with no thin wall. Two axes may have them when the third has one cell: the Kronecker sum would give a corner cell the product of its two walls’ ratios, which_corner_fix()corrects exactly.
- hartmax.poisson.free_slice(grid: Grid, axis: int, offset_value: float, condition: BoundaryCondition) slice¶
Return the entries of a staggered axis that a solve may change.
A cell-centred axis is free everywhere. A face-centred axis with a wall has its two boundary faces prescribed, and a periodic one carries a duplicate of its first face at the end. Solving on anything else would either invent a value for a prescribed face or treat one face as two unknowns.
- hartmax.poisson.variable_helmholtz(grid: Grid, conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition], conductivity: float | ndarray, shift: float | ndarray | None, coefficient: float, *, precision: str = 'state', max_steps: int = 200, tolerance: float | None = None) VariableHelmholtz¶
Build
VariableHelmholtzon the host;conductivityandshiftare numbers or cell arrays.The preconditioner is the fast-diagonal inverse at their volume means, in
precision. On a duct walled on four sides, 6 to 24 cells across, atdt0.05 and 100: 7-8 iterations at the benchmark’s steel and PbLi (kratio 0.9,rho c_p2.3), 14-33 at copper’skratio of 19, and 21-63 at 100. A high contrast costs more iterations as the mesh refines. Without ashift, the preconditioner is the singular Poisson inverse, under conditions that are insulated or periodic everywhere.tolerancereplaces the dtype’s default relative stop.
Fully developed pipe flow¶
The pipe names remain importable from hartmax.poisson, where they lived in 1.9.
Fully developed flow along a circular pipe in a transverse magnetic field.
A pipe is the other half of the duct validation, and the geometry the ALEX B1 experiment used. Nothing about the physics changes – the same inductionless system, the same insulating or thin conducting wall – but the coordinates do, and with them what separates and what does not.
Fully developed means the velocity is axial and depends only on the cross section, \(\mathbf u = u(r,\theta)\hat z\). With \(\mathbf B = B\hat x\) the Lorentz force is then purely axial as well, so the transverse momentum equations are satisfied by rest and the whole problem is one scalar equation coupled to the potential:
with \(\mathbf J = -\nabla\varphi + \mathbf u\times\mathbf B\). Both
unknowns are cell centred, which is why this needs none of the staggered vector
machinery of hartmax.core3d: there is no cross flow to project.
The electromotive force is where the coordinates show. A uniform Cartesian field is not uniform in polar components, \(B_r = B\cos\theta\) and \(B_\theta = -B\sin\theta\), so \(\mathbf u\times\mathbf B\) has \(B u\sin\theta\) through a radial face and \(B u\cos\theta\) through an azimuthal one. The same face currents then carry the potential equation and the axial force, which is the consistency the whole package is built on.
The system is linear in the velocity, so it is one preconditioned Krylov solve,
not a Newton iteration. The preconditioner is the damped operator
\((B^2 - \nabla^2)^{-1}\), factorized exactly by
hartmax.poisson.fast_diagonal_polar_poisson(), which is what keeps the
iteration count from growing with the Hartmann number.
- class hartmax.pipe.PipeProblem(grid: Grid, hartmann: float, wall_conductance: float = 0.0, forcing: float = 1.0)¶
A circular pipe of unit radius in a transverse field of magnitude
hartmann.- property conditions: tuple[BoundaryCondition, BoundaryCondition, BoundaryCondition]¶
Conditions on the potential: insulating at the wall, periodic elsewhere.
- factorization()¶
Factorize the potential Laplacian, with the thin wall’s sheet node when the wall conducts.
- preconditioner()¶
Factorize the damped operator that preconditions the velocity solve.
- hartmax.pipe.flow_rate(velocity: Field) float¶
Return the mean axial velocity over the cross-section.
- hartmax.pipe.pipe_grid(radial: int, azimuthal: int, hartmann: float, *, cells_in_layer: int = 6) Grid¶
Return a polar grid whose radial cells resolve the
1/Hawall layer.
- hartmax.pipe.pipe_problem(*, hartmann: float, radial: int = 48, azimuthal: int = 64, wall_conductance: float = 0.0) PipeProblem¶
Build a pipe whose mesh resolves the layer its Hartmann number implies.
- hartmax.pipe.pipe_residual(velocity: Field, problem: PipeProblem, factorization) Field¶
Return the steady axial momentum residual of a candidate velocity.
- hartmax.pipe.solve_pipe(problem: PipeProblem, *, tolerance: float = 1e-11, max_restarts: int = 40)¶
Return the axial velocity and the potential of a fully developed pipe.
The system is linear in the velocity, so this is one preconditioned Krylov solve. The preconditioner inverts the damped operator exactly, which is the stiff part of the problem and the reason the iteration does not lengthen with the Hartmann number.
Quasi-two-dimensional flow¶
Quasi-two-dimensional inductionless MHD on periodic planes.
- class hartmax.q2d.Q2DDiagnostics(kinetic_energy_initial: float, kinetic_energy_final: float, enstrophy_final: float, energy_budget_residual: float, max_divergence: float, max_courant: float)¶
Compact physical and numerical gates for a Q2D solve.
- class hartmax.q2d.Q2DProblem(initial_vorticity: Array, forcing: Array | None = None, length: tuple[float, float] = (6.283185307179586, 6.283185307179586), viscosity: float = 0.01, hartmann_friction: float = 0.1, dt: float = 0.01, steps: int = 100, history_stride: int = 0, adjoint_checkpoint_size: int | None = None, energy_budget_tolerance: float = 0.001, spectrum: Array | None = None)¶
Periodic Sommeria–Moreau vorticity problem.
forcingis a vorticity source. The linear Hartmann-layer closure is-hartmann_friction * vorticity; lengths, viscosity, time, and forcing must use one consistent unit system. All inputs determine a common real working dtype through JAX promotion, with at least float32 precision.energy_budget_tolerancebounds the normalized trapezoidal energy defect for host acceptance; it does not change the numerical trajectory.spectrum, a result’s, continues that run exactly (the physical field would lose a round-off to the transform);initial_vorticitythen only gives the shape.
- class hartmax.q2d.Q2DResult(problem: Q2DProblem, x: Array, y: Array, vorticity: Array, spectrum: Array, velocity_x: Array, velocity_y: Array, frame_times: Array, vorticity_history: Array, diagnostics: Q2DDiagnostics, status: str)¶
Final Q2D fields, optional frames, and acceptance diagnostics.
- property converged: bool¶
Whether the finite trajectory passed acceptance, not steady convergence.
- hartmax.q2d.evolve_q2d(initial_vorticity: Array, *, forcing: Array | None = None, length: tuple[float, float] = (6.283185307179586, 6.283185307179586), viscosity: float | Array = 0.01, hartmann_friction: float | Array = 0.1, dt: float | Array = 0.01, steps: int = 100, adjoint_checkpoint_size: int | None = None) tuple[Array, Array, Array]¶
Return final Q2D fields through a JIT- and autodiff-safe numerical core.
Array state, forcing, domain lengths, viscosity, Hartmann friction, and timestep are differentiable.
stepsandadjoint_checkpoint_sizeare static controls; the default checkpoint schedule retainsO(sqrt(steps))trajectory states in reverse mode. State, forcing and coefficients use JAX’s common real dtype, with at least float32 precision; float64 requires enabling JAX x64 before constructing inputs.
- hartmax.q2d.make_q2d_case(*, shape: tuple[int, int] = (64, 64), length: tuple[float, float] = (6.283185307179586, 6.283185307179586), mode: tuple[int, int] = (1, 1), amplitude: float = 1.0, viscosity: float = 0.01, hartmann_friction: float = 0.1, dt: float = 0.01, steps: int = 100, history_stride: int = 0, energy_budget_tolerance: float = 0.001) Q2DProblem¶
Build a Taylor–Green decay case with an analytical exponential rate.
- hartmax.q2d.solve_q2d(problem: Q2DProblem) Q2DResult¶
Evolve IFRK4 fields and enforce Courant and normalized energy-budget gates.
The command line¶
The hartmax command: run a schema 3 TOML file, or convert an older one (docs/reference/cli.md).
- hartmax.cli.main(argv: list[str] | None = None) int¶
Run
hartmax; the exit status is 0, or 2 when a run was rejected.