Skip to content

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

Apply boundary actions around each solver step.

before_step_action()

Return the boundary potential term.

after_step_action(psi)

Apply the boundary action to psi.

Config dataclass

Bases: StrictFields

Store the full simulation configuration.

from_yaml(path) classmethod

Load nested configuration from YAML and validate its values.

to_yaml(path)

Write the complete configuration to YAML.

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.

step(model, state, dt) abstractmethod

Advance one fixed step or report an adaptive trial without changing its tick.

advance(model, state, n_steps)

Advance several steps and apply noise after accepted steps.

Dispersion

Bases: ABC

Provide the kinetic energy E(k) on the FFT grid.

energy(grid, physics) abstractmethod

Return real E(k) in meV, broadcastable to the field shape.

matrix(grid, physics, components)

Return the spectral Hamiltonian with axes (batch, C, C, *space).

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.

cuda_values()

Return argument values keyed by the names in cuda.arguments.

coefficient(field, reservoir, reservoir_fields, t) abstractmethod

Return a real array broadcastable to field.

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

Read a sweep manifest and provide lazy member and combined result views.

member(index)

Return a Results-compatible view of one global member index.

mean(name, members=None)

Return the sample-weighted mean of a linear accumulated result.

close()

Close every underlying batch result file.

Results

Saved arrays and metadata, with an optional open HDF5 handle.

kx property

FFT-shifted angular x wavenumbers in inverse micrometres.

ky property

FFT-shifted angular y wavenumbers in inverse micrometres.

close()

Close an open HDF5 file.

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.

add_visitor(visitor)

Register a result visitor.

step(t, **context)

Compute needed nodes once and dispatch to all visitors.

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.

needs(nodes)

Return names of nodes that are exposed for visualization.

visit_all(nodes, **context)

Send one result step to the visualizer.

ResultVisitor

Bases: ABC

Define the interface for result visitors.

needs(nodes)

Return the set of node names this visitor requires.

Override in subclasses to avoid computing unused nodes.

visit_all(nodes, **context) abstractmethod

Visit all result nodes.

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.

Config dataclass

Bases: StrictFields

Store the full simulation configuration.

from_yaml(path) classmethod

Load nested configuration from YAML and validate its values.

to_yaml(path)

Write the complete configuration to YAML.

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.

Read a sweep manifest and provide lazy member and combined result views.

member(index)

Return a Results-compatible view of one global member index.

mean(name, members=None)

Return the sample-weighted mean of a linear accumulated result.

close()

Close every underlying batch result file.

Base class for scheduled device-side accumulators.

update(state, t)

Accumulate one sample using device operations only.

state_dict()

Return raw array sums and common sampling metadata.

load_state_dict(values)

Restore common sampling metadata.

results()

Return normalized results after the run.

One finalized accumulated array and its axis metadata.

Register an accumulator class under a configuration name.

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.

Return the normalized, centered first-order spatial correlation.

Return the second-order correlation, zero at negligible density.

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.

step(model, state, dt) abstractmethod

Advance one fixed step or report an adaptive trial without changing its tick.

advance(model, state, n_steps)

Advance several steps and apply noise after accepted steps.

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.

Outcome of a solver step.

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.

Return a decorator that registers a solver under name.

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.

cuda_values()

Return argument values keyed by the names in cuda.arguments.

coefficient(field, reservoir, reservoir_fields, t) abstractmethod

Return a real array broadcastable to field.

Return a decorator that registers a term under name.

Bases: ABC

Provide the kinetic energy E(k) on the FFT grid.

energy(grid, physics) abstractmethod

Return real E(k) in meV, broadcastable to the field shape.

matrix(grid, physics, components)

Return the spectral Hamiltonian with axes (batch, C, C, *space).

Return a decorator that registers a dispersion and sets its kind.

Bases: ABC

Define the interface for laser profiles.

power_coefficient(t)

Return the scalar time coefficient of the cached spatial envelope.

batch_power_coefficient(lasers, times) classmethod

Return one power coefficient per time and laser.

get_power(X, Y, t)

Return the full pump field at time t; callers must treat it as read-only.

Return a decorator that registers a laser under name.

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.

Return a decorator that registers a reservoir under name.

Return a decorator that registers a potential under name.

Return a decorator that registers a grid under name.

Return a decorator that registers an absorption strategy under name.

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.

Compute engine

Track the active NumPy or CuPy backend.

configure(config)

Configure the compute backend.

to_gpu(array)

Move an array to the active backend.

to_cpu(value)

Move a value to NumPy memory.