Python API¶
Use Config and SimulationController for ordinary runs. The API entries below are generated from public objects and their docstrings; Configuration lists every field and Plugins explains extension contracts.
SimulationController creates the grid, pump, potential, reservoir, boundary condition, state, model and solver, then records results while advancing to solver.total_time in ps. run.set_initial_state(psi, reservoir_state=None, t=0.0) accepts a field on the grid and optional reservoir arrays; t is the new origin in ps. save_checkpoint(path) and load_checkpoint(path) write and restore version 2 HDF5 state. run.run_directory identifies a created output directory. See Results format for saved shapes.
polarism.compute_engine.compute_engine exposes xp, the active NumPy or CuPy array namespace. cfg.compute_engine.use_gpu selects CuPy when available; plugin code should use backend arrays throughout each step. to_cpu(value) transfers a result to NumPy at an output boundary. See Running on GPUs.
Package exports¶
Public package exports for polarism.
available_profiles = Registry('profile')
module-attribute
¶
available_envelopes = Registry('envelope')
module-attribute
¶
BoundaryCondition
¶
Config
dataclass
¶
AbstractSolver
¶
Bases: ABC
Define the interface for solver backends.
A solver that injects the Wigner increment inside its own step, at the
point its scheme prescribes, sets injects_noise = True. The default
advance then does not add the increment again after each step.
Dispersion
¶
Model
¶
Collect the physical components passed to a solver.
potential_at(t)
¶
Return V(r) f(t) + CAP, keeping the absorber time independent.
drive_rhs(t)
¶
Return -i F(r, t)/ħ for the enabled coherent drive.
drive_contribution(field, t)
¶
Return (+i E_p/ħ)ψ - i F(r, t)/ħ.
For V = g = k = 0 without reservoir, dψ/dt = (i E_p/ħ - γ_C/2)ψ - i F/ħ, so ψ_ss = (-i F/ħ)/(γ_C/2 - i E_p/ħ).
extra_coefficients(field, reservoir_fields, t)
¶
Sum the extra terms into (energy, rate) coefficients.
Call only when terms is not empty.
extra_rhs(field, reservoir_fields, t)
¶
Return the extra terms' contribution to d field / dt.
rhs(field, reservoir_fields, t, out=None)
¶
Evaluate the finite-difference reference right-hand side.
Term
¶
Bases: ABC
Contribute a real coefficient to the condensate equation.
An "energy" term adds (-i/hbar) * E * psi to d psi / dt and a
"rate" term adds G * psi. coefficient returns the real array
E or G evaluated from the current stage values.
StepReport
dataclass
¶
Outcome of a solver step.
SolverCapabilities
dataclass
¶
Features accepted by a solver implementation.
Every field has a conservative default, so a solver declares only what differs. Set-valued fields accept any iterable and are stored as frozensets.
LaserFactory
¶
Build laser objects from config data.
create_laser(laser_config, X, Y, precision='double', grid=None)
staticmethod
¶
Create one or more lasers from the config.
RealTimeVisualization
¶
Plot fields and scalars during a run.
update(t, fields=None, scalars=None, scalar_groups=None)
¶
Update the plots with new fields and scalars.
ResultNode
¶
Describe one computed result.
A scalar observable in a batched run must compute a device vector with one value per member. Field observables must retain the member axis.
compute_field_device(**context)
¶
Compute the field on the active backend without evaluating the scalar reduction.
compute_device(**context)
¶
Compute the field and reduced value on the active backend.
compute_cpu(**context)
¶
Compute the field and reduced value on the CPU.
compute_field_cpu(**context)
¶
Compute the field value on the CPU.
compute_reduced_cpu(**context)
¶
Compute the reduced value on the CPU.
ResultProvider
¶
Bases: ABC
Define the interface for result providers.
make_result_nodes()
abstractmethod
¶
Build the result nodes exposed by this object.
SimulationController
¶
Set up and run a full simulation.
step_statistics
property
¶
Return adaptive trial counts and accepted step sizes.
add_visitor(visitor)
¶
Register a visitor and build result nodes if this is the first one.
set_initial_state(psi, reservoir_state=None, t=0.0)
¶
Set a real-space initial field and optional reservoir densities.
add_event(callback, every)
¶
Call a predicate at every fixed-time interval in ps.
save_checkpoint(path)
¶
Atomically save the current state to an HDF5 checkpoint.
load_checkpoint(path)
¶
Validate and restore a checkpoint for the current configuration.
run()
¶
Run the simulation loop.
Sweep
¶
Run Cartesian-product or zipped config overrides in deterministic order.
Multiple-laser entries use lasers[1].delay or
lasers[1].extra.name with zero-based indices into the laser YAML file.
run returns saved sweep results when output is enabled, otherwise a
list of dictionaries with final psi and reservoir arrays.
run(resume=None)
¶
Execute batches, optionally resuming a sweep directory.
SweepResults
¶
Results
¶
SimulationGrid
¶
Bases: Protocol
Spatial grid interface shared by model components.
SimulationState
¶
Store canonical fields and expose scalar public wavefunction views.
field
property
writable
¶
Return the canonical real-space field, materializing it if needed.
field_k
property
writable
¶
Return the cached canonical spectral field.
psi
property
writable
¶
Return a public-shape view of the real-space wavefunction.
psi_plus
property
¶
Return the σ+ circular component.
psi_minus
property
¶
Return the σ− circular component.
psi_k
property
writable
¶
Return a public-shape view of the cached spectral field.
materialize_psi(xp)
¶
Materialize the canonical real-space field from its spectral cache.
invalidate_psi_k()
¶
Clear the spectral cache after external real-space mutation.
get_simulation_state()
¶
Return the public wavefunction and current time.
Results2D
dataclass
¶
Describe one 2D field view.
ResultScalar
dataclass
¶
Describe one scalar result.
ResultScalarGroup
dataclass
¶
Describe a grouped scalar result.
ResultsManager
¶
Send result nodes to each registered visitor.
Visitors that declare data_location = "device" receive backend-native
arrays without a CPU conversion. Each node is computed at most once per
:meth:step call regardless of how many visitors request it.
When a node is only requested by device visitors, the scalar reduction
(reduce_dim_fn) is skipped so GPU stream synchronisation is avoided.
Nodes also needed by CPU visitors always compute both field and reduction.
Visitor exceptions are isolated: a visitor that raises is disabled for the
rest of the run so that it cannot abort the simulation loop. Visitors that
expose an abort(exc) method have it called before being disabled.
StorageVisitor
¶
Bases: ResultVisitor
Snapshot frames and write them on one bounded background worker.
needs(nodes)
¶
Return names of nodes that are flagged for saving.
visit_all(nodes, t, **context)
¶
Copy mutable device results before the solver can advance.
finalize()
¶
Drain pending frames, join the worker, and close all backends.
flush()
¶
Drain queued snapshots and persist each backend before checkpointing.
set_stop_times(stop_times)
¶
Persist final per-member stop times after all frame writes.
set_step_statistics(statistics)
¶
Persist adaptive statistics in supporting storage formats.
set_accumulated(results, metadata)
¶
Persist finalized accumulated arrays after draining frame writes.
VisualizationVisitor
¶
Bases: ResultVisitor
Send result nodes to the live visualizer.
ResultVisitor
¶
register_profile(name, *, params=())
¶
Register a (grid, params, xp) function and its accepted spec keys.
register_envelope(name, *, params=())
¶
Register a spec-to-callable factory and its accepted spec keys.
load_plugins(root=None)
¶
Import every module under <root>/polarism_plugins and return their names.
Plugin modules register their components with the usual registry
decorators (register_laser, register_potential, ...) on import.
root defaults to the current working directory.
load_results(path)
¶
Load one result run from its directory or HDF5 file.
Configuration dataclasses¶
Simulation config dataclasses.
GridParameters
dataclass
¶
Bases: StrictFields
Store grid size and box-length settings.
PhysicsConstants
dataclass
¶
Bases: StrictFields
Store the physics constants for the model.
BoundaryConditionParameters
dataclass
¶
Bases: StrictFields
Store boundary absorption settings.
PotentialParameters
dataclass
¶
Bases: StrictFields
Store potential settings.
DriveParameters
dataclass
¶
Bases: StrictFields
Store the coherent source and its rotating-frame energy.
NoiseParameters
dataclass
¶
Bases: StrictFields
Control initial and per-step condensate noise.
InitialConditionParameters
dataclass
¶
Bases: StrictFields
Select the deterministic part of the initial wavefunction.
LaserParameters
dataclass
¶
Bases: StrictFields
Store laser settings.
ReservoirParameters
dataclass
¶
Bases: StrictFields
Store reservoir settings.
SolverParameters
dataclass
¶
Bases: StrictFields
Store solver settings.
ResultParameters
dataclass
¶
Bases: StrictFields
Store result-output settings.
ComputeEngineParameters
dataclass
¶
Bases: StrictFields
Store backend settings.
StopParameters
dataclass
¶
Bases: StrictFields
Control optional steady-state stopping.
CheckpointParameters
dataclass
¶
Bases: StrictFields
Control periodic and signal-triggered checkpoints.
SweepParameters
dataclass
¶
Bases: StrictFields
Control sweep batching and GPU memory use.
Parameter sweeps¶
Run Cartesian-product or zipped config overrides in deterministic order.
Multiple-laser entries use lasers[1].delay or
lasers[1].extra.name with zero-based indices into the laser YAML file.
run returns saved sweep results when output is enabled, otherwise a
list of dictionaries with final psi and reservoir arrays.
run(resume=None)
¶
Execute batches, optionally resuming a sweep directory.
polarism.results.available_accumulators is the registry of available
accumulator classes.
Storage plugins receive a StorageContext with sweep member indices, seeds,
and resume state. See Storage format plugins for the
constructor contract.
Run storage state: member count, ordered indices and seeds, resume flag, and saved resume time.
members is the batch size when member output is present. member_indices
maps batch positions to sweep positions, and member_seeds records their
noise seeds. resume reopens existing output, while resume_time is
the last restored simulation time used to trim saved frames.
Controller and solver extension¶
Set up and run a full simulation.
step_statistics
property
¶
Return adaptive trial counts and accepted step sizes.
add_visitor(visitor)
¶
Register a visitor and build result nodes if this is the first one.
set_initial_state(psi, reservoir_state=None, t=0.0)
¶
Set a real-space initial field and optional reservoir densities.
add_event(callback, every)
¶
Call a predicate at every fixed-time interval in ps.
save_checkpoint(path)
¶
Atomically save the current state to an HDF5 checkpoint.
load_checkpoint(path)
¶
Validate and restore a checkpoint for the current configuration.
run()
¶
Run the simulation loop.
Bases: ABC
Define the interface for solver backends.
A solver that injects the Wigner increment inside its own step, at the
point its scheme prescribes, sets injects_noise = True. The default
advance then does not add the increment again after each step.
Collect the physical components passed to a solver.
potential_at(t)
¶
Return V(r) f(t) + CAP, keeping the absorber time independent.
drive_rhs(t)
¶
Return -i F(r, t)/ħ for the enabled coherent drive.
drive_contribution(field, t)
¶
Return (+i E_p/ħ)ψ - i F(r, t)/ħ.
For V = g = k = 0 without reservoir, dψ/dt = (i E_p/ħ - γ_C/2)ψ - i F/ħ, so ψ_ss = (-i F/ħ)/(γ_C/2 - i E_p/ħ).
extra_coefficients(field, reservoir_fields, t)
¶
Sum the extra terms into (energy, rate) coefficients.
Call only when terms is not empty.
extra_rhs(field, reservoir_fields, t)
¶
Return the extra terms' contribution to d field / dt.
rhs(field, reservoir_fields, t, out=None)
¶
Evaluate the finite-difference reference right-hand side.
Features accepted by a solver implementation.
Every field has a conservative default, so a solver declares only what differs. Set-valued fields accept any iterable and are stored as frozensets.
Model component extension¶
The laser, reservoir, solver, term, dispersion, grid, and absorption guides explain these bases and registration decorators in context.
Bases: ABC
Contribute a real coefficient to the condensate equation.
An "energy" term adds (-i/hbar) * E * psi to d psi / dt and a
"rate" term adds G * psi. coefficient returns the real array
E or G evaluated from the current stage values.
Bases: ABC
Define the interface for reservoir models.
step(dt, psi_mid, pump)
abstractmethod
¶
Advance canonical reservoir fields using a canonical condensate field.
get_reservoir_density()
abstractmethod
¶
Return total density in the public scalar shape.
make_result_nodes()
abstractmethod
¶
Build the result nodes exposed by this object.
get_state()
abstractmethod
¶
Return canonical (B, C_res, *S) state arrays.
set_state(state)
abstractmethod
¶
Set canonical (B, C_res, *S) state arrays.
get_derivatives(psi, pump, state, rho=None)
abstractmethod
¶
Return canonical derivatives from canonical condensate and state arrays.
get_active_density(state)
¶
Return the active reservoir density.
get_inactive_density(state)
¶
Return the inactive reservoir density, or zero if the model has none.
Batched state and reservoir API¶
SimulationState(grid, eps=1e-3, precision="double", *, mode="complex_gaussian_zero_mean", k_cutoff_um=None, seed=None, batch_size=None, initial_condition=None, components=1) creates seeded initial fields along the batch axis. create_reservoir(reservoir_config, physics, grid, precision="double", *, batch_size=None, batch_physics=None) creates matching zero density fields. Built-in reservoirs support reset(batch_size=None) to clear and resize their density fields. See Batched simulations for a working pattern.