phipict.MHDSimulation

class phipict.MHDSimulation(domain: phipict._C.Domain, dt: float, stuart_number: Tensor, e_b: Tensor, potential_tol: float | SolverTolerance | None = None, potential_use_BiCG: bool = False, potential_normalize: bool = True, potential_non_ortho_flags: int = 0, potential_use_face_transform: bool = False, potential_solve_max_iter: int = 5000, potential_solve_dtype: dtype | None = None, exclude_potential_solve_gradients: bool = False, potential_reuse_result: bool = True, potential_return_best_result: bool = True, potential_use_preconditioner: bool = False, potential_amg_options: dict | None = None, **kwargs: Any)[source]

MHD simulation using the inductionless approximation.

Parameters:
  • domain (_C.Domain) – The simulation domain (must be initialized via PrepareSolve).

  • dt (float) – Time step size.

  • stuart_number (torch.Tensor) – Stuart number N = Ha^2 / Re as a scalar tensor (learnable).

  • e_b (torch.Tensor) – Magnetic field. Either a uniform direction of shape (3,), or a spatially varying field of shape (3, *spatial), i.e. (3, nz, ny, nx) in 3D and (3, ny, nx) in 2D, whose spatial axes may be 1 to broadcast, e.g. (3, 1, 1, nx) for a field that only varies along the streamwise direction. It always carries 3 components, also in 2D. A spatially varying field requires a single-block domain.

  • potential_tol (float, SolverTolerance or None) – Tolerance for the electric potential Poisson solve. A float is an absolute tolerance on ||r||_2/sqrt(n); a SolverTolerance specifies it relative to the RHS instead, which keeps its meaning across domain sizes. If None, falls back to the dtype default.

  • potential_use_BiCG (bool) – Whether to use BiCGStab for the potential solve. Defaults to False (uses CG).

  • potential_normalize (bool) – Whether to subtract the mean from the electric potential result (analogous to normalize_pressure_result). Defaults to True. Ignored when a Dirichlet φ boundary anchors the matrix, since φ is then unique.

  • potential_non_ortho_flags (int) – Non-orthogonal correction flags for the epot matrix. Defaults to 0.

  • potential_use_face_transform (bool) – Whether to use face transforms for the epot matrix. Defaults to False.

  • potential_solve_max_iter (int) – Maximum iterations for the potential linear solver. Defaults to 5000.

  • potential_solve_dtype (torch.dtype or None) – Data type to use for the electric potential linear solve. If set (e.g. torch.float64), the Poisson matrix and RHS are up-cast to this dtype for the solve and the result is cast back to the domain’s global dtype, so the rest of the simulation keeps running at the global precision. Unlike solver_double_fallback (which only retries in double after a single-precision solve fails), this solves at the requested precision straight away. If None (default), the solve uses the global dtype.

  • exclude_potential_solve_gradients (bool) – Whether to exclude gradients from the electric potential Poisson solve (analogous to exclude_pressure_solve_gradients in the base Simulation). When True, the potential solve runs under torch.no_grad so no gradients flow through it. Defaults to False.

  • potential_reuse_result (bool) – Whether to warm start the potential solve from the previous step’s phi instead of a zero initial guess. Defaults to True. Forced off in differentiable mode, where the solver backend ignores an initial guess.

  • potential_use_preconditioner (bool) –

    Whether to solve the potential Poisson equation with AMG-preconditioned CG instead of unpreconditioned CG. Defaults to False.

    The unpreconditioned solve dominates the runtime of an MHD run, so this is the main lever on it. The hierarchy is built once (on the host, via pyamg) and reused for every subsequent solve, which is only sound because the epot matrix values are constant for a run (see phipict.solvers.amg). The first solve therefore pays a noticeable setup cost.

  • potential_amg_options (dict or None) – Extra keyword arguments for phipict.solvers.amg.hierarchy_for() (and phipict.solvers.amg.build_amg_hierarchy()), e.g. {"method": "ruge_stuben", "strength": 0.5, "num_pre_smooth": 2} or {"reuse_interpolation": False} for a dedicated setup.

  • potential_return_best_result (bool) – Whether a potential solve that fails to reach potential_tol should fall back to its best iterate (True, the default) or raise LinsolveError (False).

  • **kwargs – Additional keyword arguments passed to the parent Simulation class.

__init__(domain: phipict._C.Domain, dt: float, stuart_number: Tensor, e_b: Tensor, potential_tol: float | SolverTolerance | None = None, potential_use_BiCG: bool = False, potential_normalize: bool = True, potential_non_ortho_flags: int = 0, potential_use_face_transform: bool = False, potential_solve_max_iter: int = 5000, potential_solve_dtype: dtype | None = None, exclude_potential_solve_gradients: bool = False, potential_reuse_result: bool = True, potential_return_best_result: bool = True, potential_use_preconditioner: bool = False, potential_amg_options: dict | None = None, **kwargs: Any) → None[source]

Methods

__init__(domain, dt, stuart_number, e_b[, ...])

advect_static(iterations[, time_step])

Advect only the passive scalar in the current velocity field.

clear_pressure_guess()

Drop the warm-start cache, e.g. after the domain or dt changed.

detach()

Detach the cross-step state kept outside the Domain.

end_step([time_step])

Advance the step counter and the simulated time.

get_current_density(block)

Compute the current density j = -grad(phi) + u x e_b for a block.

linear_solve(csrMat, rhs[, x, use_BiCG, ...])

Solve A x = b with the configured solver.

linear_solve_AMG(rhs, x, amg_hierarchy, tol, ...)

Solve with AMG-preconditioned CG (host setup, on-device V-cycle).

linear_solve_GPU(csrMat, rhs[, x, use_BiCG, ...])

Solve A x = b with the CUDA solvers.

linear_solve_scipy(csrMat, rhs[, x])

Solve A x = b with SciPy's direct sparse solver on the host.

make_current_divergence_free([max_iter])

Solve the potential for the current velocity so that div(j) = 0.

make_divergence_free([iterations, max_iter])

Run pressure corrections to make the velocity divergence free.

resample(field[, out_indices])

Resample a field of all blocks onto the uniform output grid.

reset_image_out_idx()

Reset the index of written images to 0.

reset_step_counters()

Reset the step, time and image counters.

reset_total_step()

Reset the total step counter to 0.

reset_total_time()

Reset the total simulated time to 0.

run(iterations[, static, log_domain])

Run the simulation.

save_domain([name])

Save the domain to the log directory, logging failures.

save_domain_images([idx, max_mag, vel_exr])

Write images of the domain fields to the log directory.

set_magnetic_field(e_b)

Replace the magnetic field between steps, keeping its autograd graph.

single_step([static])

Perform a single simulation step.

Attributes

NON_ORTHO_CENTER_MATRIX

NON_ORTHO_DIAGONAL_MATRIX

NON_ORTHO_DIAGONAL_RHS

NON_ORTHO_DIRECT_MATRIX

NON_ORTHO_DIRECT_RHS

adaptive_CFL

CFL number for adaptive substeps.

advect_non_ortho_steps

Non-orthogonal correction steps of the advection.

advection_tol

Advection solver tolerance, the dtype default if unset.

advection_use_BiCG

Whether the advection is solved with BiCGStab.

block_layout

Block arrangement of images.

convergence_tol

Velocity change below which the simulation stops.

corrector_steps

Number of PISO corrector steps.

density_viscosity

Superseded by Domain.scalarViscosity; always None.

differentiable

Whether the differentiable backend is used.

domain

The simulation domain.

hooks

The callbacks run at the hooks of every PISO step.

log_dir

Output directory, created on assignment.

log_images

Whether images are written.

log_interval

Iterations between log outputs, 0 if disabled.

magnetic_field

The magnetic field in the internal layout, see _prepare_e_b().

non_orthogonal

Whether non-orthogonal corrections are used.

norm_vel

Whether velocity images are normalized.

normalize_pressure_result

Whether the mean pressure is subtracted.

output_resampling_coords

Vertex coordinates for resampled images, defaulting to the domain's.

potential_solve_max_iter

Iteration limit of the electric potential Poisson solve.

potential_tol

Tolerance of the electric potential Poisson solve.

prep_fn

The former name of hooks, kept for compatibility.

pressure_guess_state

The warm-start cache as one stacked tensor, or None if empty.

pressure_non_ortho_steps

Non-orthogonal correction steps of the pressure.

pressure_return_best_result

Whether a non-converged pressure solve returns its best iterate.

pressure_tol

Pressure solver tolerance, the dtype default (as tensor) if unset.

pressure_tol_intermediate

Tolerance for every pressure solve that is not the final corrector.

pressure_use_BiCG

Whether the pressure is solved with BiCGStab.

pressure_warm_start

Seed each pressure solve with the previous sub-step's result.

scipy_solve_advection

Whether the advection is solved with SciPy.

scipy_solve_pressure

Whether the pressure is solved with SciPy.

stop_fn

Function returning True to stop the simulation.

substeps

Substeps per iteration, -1 for adaptive substeps.

time_step

Time step per substep.

velocity_corrector

Pressure gradient discretization of the velocity correction.