UltrafastEngine

Python API (generated)

Signatures and the first paragraph of every public docstring. The narrative guide is Python; every element and option the builders accept is in the option reference. Editors get the same information through the type hints and the TypedDicts in ultrafast.types (autocompletion of system and run dictionaries).

ultrafast

Top level: import ultrafast as uf.

UltrafastEngine -- nonlinear ultrafast pulse propagation through complete optical systems.

Exported names: ElementContext, ResponseContext, Result, Run, System, UltrafastError, algorithms, benchmark, build, calc, capabilities, cells, coherence, command, components, crystal, devices, instruments, laser, load, materials, measured, plot, plugins, results, retrieve, retrieve_multi, run, set_default_backend, sources, study, system, types, version

plot(result, what: str = 'overview', ax = None)

Quick matplotlib plots of a :class:Result or a CLI results folder ("overview", "measurements", "spectrum", "temporal", "phase", "losses", "elements"). Full reports: :func:ultrafast.plotting.report.

load(directory)

Open a results folder written by the CLI (summary.json + result.npz) -- no engine needed.

ultrafast.core

Running systems, results, commands (studies, retrieval, materials).

Pythonic wrapper over the C API: :class:System, :class:Run, :class:Result.

class UltrafastError(RuntimeError)

An error reported by the engine (bad JSON, unknown model, failed run...).

  • __init__(code: int, message: str)

version() -> str

Engine version string.

capabilities() -> dict

Built-in model kinds, element types, materials and instruments.

command(request: Mapping[str, Any]) -> dict

Run a JSON command of the engine (uf_command): {"command": "study" | "retrieve" | "materials.list" | "materials.show" | "materials.import" | "devices" | "compute.default", ...}. The higher-level :func:study, :func:retrieve and :mod:ultrafast.materials wrap it.

devices(selftest: bool = False, benchmark: bool = False, backend: Optional[str] = None, device: Optional[int] = None) -> dict

Compute back-ends and devices (docs/reference/speed.md): {"defaultBackend", "fft", "backends": [...], "devices": [{"backend", "index", "name", "memoryBytes", "doublePrecision", "usable", ...}]} -- the CPU first, then CUDA / OpenCL devices found by the gpu plugin. selftest=True compares every usable device (or only backend / device) with the CPU on standard problems (result in "selftest"); benchmark=True also times both.

benchmark(backend: Optional[str] = None, device: Optional[int] = None) -> List[dict]

Seconds per run on the CPU and on each device for growing 1-D and spatial problems, with the speed-up ([{"problem", "n", "cpuSeconds", "deviceSeconds", "speedup", "relativeError", ...}]; the first device of each available back-end unless backend / device are given). Takes a few minutes.

set_default_backend(backend: Optional[str] = None, fft: Optional[str] = None) -> dict

Process-wide defaults: the back-end of runs whose spec has no compute.backend ("cpu", "auto", "cuda", "opencl"; None keeps the current one) and the CPU FFT provider ("auto", "managed", "fftw", "accelerate"). Returns the settings in force. The ULTRAFAST_BACKEND / ULTRAFAST_FFT environment variables set the initial values.

study(system: Any, run_spec: Any, parameters: Sequence[Mapping[str, Any]] = (), outputs: Sequence[str] = (), mode: str = 'scan', output: Optional[PathLike] = None, **options) -> dict

Parameter study (docs/reference/studies.md): mode "scan" (sampling grid | random | lhs | sobol, samples), "optimize" (objective={"output": ..., "goal": "min" | "max" | "target", "target": ...}) or "sensitivity" (sensitivity={"method": "local" | "sobol"}) or "coherence" (coherence={"trials": 10, "at": "end"}: repeated runs with independent quantum noise, result in analysis["coherence"]). Parameters are {"path": "element:ID/key", "min", "max"}; outputs are names like "pulse:end/fwhmS", "record:plate/BIntegralRad", "instrument:ac/fwhmS". Returns the study result (rows, analysis); output also writes study.json / study.csv.

coherence(system: Any, run_spec: Any, trials: int = 10, at: str = 'end', parallel: int = 4, seed: int = 1, output: Optional[PathLike] = None) -> dict

First-order spectral coherence |g12(lambda)| over trials runs with independent one-photon-per-mode noise (docs/reference/fibers.md#noise-and-coherence). Returns {"meanCoherence", "wavelength_m", "g12", "spectrum", ...}.

retrieve(method: str, trace: Any, kind: Optional[str] = None, fundamental: Optional[PathLike] = None, material: Optional[str] = None, output: Optional[PathLike] = None, energy: float = 1e-09, instrument: Optional[str] = None, **options) -> dict

Pulse retrieval (docs/reference/retrieval.md): method "pcgpa" | "epie" (FROG) or "dscan"; trace an NPZ / JSON file or a dict of arrays (delay_s or insertion_m, omega_rad_s or wavelength_m, trace). A results folder's result.npz works too: instrument names the frog / xfrog / dscan instrument when there are several (its kind is read from summary.json). kind is "shg-frog", "pg-frog", "sd-frog", "xfrog" or "dscan"; a dict may carry it as "kind". Without a kind an SHG-FROG is assumed only if the trace is symmetric in the delay, otherwise the call fails. An XFROG dict also needs reference_time_s, reference_field_re, reference_field_im and reference_omega_rad_s (a one-element list) -- the arrays of an xfrog instrument. Returns the result with a ready-to-use run-spec "pulse".

retrieve_multi(traces: Sequence[dict], output: Optional[PathLike] = None, energy: float = 1e-09, **options) -> dict

Retrieve several FROG traces that share unknown pulses together (double FROG, docs/reference/retrieval.md#multi-trace-retrieval).

class System(_Handle)

An optical system (a .ufs system file, or a dict with the same structure).

  • load(source: JsonLike) -> 'System'
  • to_dict() -> dict
  • validate() -> dict -- Structural checks + a trial compilation. Returns {'ok', 'errors', 'warnings', 'notes', 'provenance', ...}.

class ResponseContext

What a Python time-response callback sees (NumPy views, valid only during the call).

  • __init__(c: N.ResponseCtx, dn_re, dn_im)

class ElementContext

What a Python user element sees ({"type": "user", "callback": "@name"}).

  • __init__(c: N.ElementCtx)
  • set(ax, ay = None)
  • time_x() -- Temporal envelope of x (sqrt(W)) on t (engine convention: A(t) = (1/N) sum A(W) exp(-i W t)).

class Run(_Handle)

A system + a run spec (+ callbacks). Call :meth:execute to propagate.

  • __init__(system: System, spec: JsonLike)
  • time_response(name: str, fn: Callable[[ResponseContext], Any], carrier_resolved: bool = False) -> 'Run' -- Register a Delta n(t) model under name; reference it from the run spec / system file as {"kind": "callback", "name": name} (e.g. an override with "property": "timeResponse"). fn(ctx) may write ctx.dn_re / ctx.dn_im in place, or return dn_re or (dn_re, dn_im).
  • index(name: str, fn: Callable[[np.ndarray], np.ndarray]) -> 'Run' -- Register n(omega) under name (use as a material "index": "@name").
  • field(name: str, fn: Callable[[np.ndarray, np.ndarray, np.ndarray], np.ndarray]) -> 'Run' -- Register a position-dependent property f(x, y, z) (arrays in m, x/y from the beam axis, z from the element start) -> values; use it as "indexProfile": "@name", "absorptionProfile": "@name", "n2Scale": "@name" or in gain media (docs/reference/spatial-properties.md).
  • filter(name: str, fn: Callable[[np.ndarray], Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]]) -> 'Run' -- Register a spectral filter: fn(omega) -> T or (T, phase) (power transmission, rad).
  • beam(name: str, fn: Callable[[np.ndarray], Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]]) -> 'Run' -- Register a beam model: fn(z) -> radius or (radius_x, radius_y) (1/e^2 radii, m).
  • array_function(name: str, fn: Callable[[np.ndarray], np.ndarray]) -> 'Run' -- Register a generic y = f(x) (e.g. a Raman response h(t), or attenuation via name + '#index').
  • element(name: str, fn: Callable[['ElementContext'], Any]) -> 'Run' -- Register a user element under name; use it as {"type": "user", "callback": "@name", "params": {...}}. fn(ctx) returns (ax, ay), ax, or None (see :class:ElementContext).
  • execute(progress: Optional[Callable[[str, int, int, float], Optional[bool]]] = None) -> 'Result' -- Propagate. progress(element_id, index, count, fraction) may return True to cancel.

class Result(_Handle)

Everything a run produced. result.summary (dict), result['output_power_w'] (NumPy), result.arrays (lazy mapping), result.write(directory).

  • __init__(h)
  • summary() -> dict
  • provenance() -> list
  • names() -> list
  • arrays() -> Mapping[str, np.ndarray]
  • elements() -- Per-element table as a list of dicts (also in summary['elements']).
  • instrument(name: str) -> dict
  • comparisons() -> 'List[_measured.Comparison]' -- Instruments compared with recorded data (their measured key): chi^2, rms error, scalar readings, notes. See :mod:ultrafast.measured.
  • comparison(instrument: str) -> '_measured.Comparison' -- The comparison of one instrument with its recorded data (KeyError if it has none).
  • write(directory: PathLike) -> Path

run(system: Union[System, JsonLike], spec: JsonLike, callbacks: Optional[Mapping[str, Any]] = None, progress = None, elements: Optional[Mapping[str, Any]] = None, fields: Optional[Mapping[str, Any]] = None) -> Result

One-call simulation. callbacks: {"name": function} time responses (take a ResponseContext); elements: {"name": function} user elements (take an ElementContext); fields: {"name": f(x, y, z)} position-dependent properties. Use :class:Run directly for index/filter/beam callbacks or carrier-resolved responses.

ultrafast.build

Builders for system files and run specs (from ultrafast import build as b).

Helpers to write system files and run specs from Python (plain dicts, so they can be inspected, edited, saved with :func:save and versioned). Every helper simply returns the JSON the engine reads; see docs/reference/system-file.md and docs/reference/run-spec.md for all fields.

class Sequential(list)

The elements of a system in order: each continues into the next (the default for a plain list).

class Branched(list)

The elements of a branched system: each states where its light goes, with :func:link. Pass it to :func:system.

link(element: Mapping[str, Any], next: Any = None, inputs: Optional[Mapping[str, Any]] = None, loop: Optional[Mapping[str, Any]] = None) -> Dict[str, Any]

An element of a :class:Branched system, with where its light goes. next is "bs:1", {"id": "bs", "port": 1}, "end", "virtual", or a dict of those by output port. inputs holds virtual beams by input port (:func:virtual_input); loop is :func:loop on the element where light enters a loop.

same_as(id: str, source: str, *, label: Optional[str] = None, enabled: Optional[bool] = None, aoi_deg: Optional[float] = None, aoi_rad: Optional[float] = None, tilt_x_rad: Optional[float] = None, next: Any = None, inputs: Optional[Mapping[str, Any]] = None, loop: Optional[Mapping[str, Any]] = None, side: Optional[int] = None) -> Dict[str, Any]

An element that is the same physical object as source (an element id): the same type and numbers, e.g. a transform used on every pass of a multipass cell. The fit parameters of source move all its copies. The copy gets its own pulse and beam, and its own record and loss booking. It may set only label, enabled, the geometry that changes from pass to pass (aoi_deg / aoi_rad, tilt_x_rad, side: the side of a beam splitter that is met) and the wiring of a Branched system (next, inputs, loop).

virtual_input(pulse: Optional[Mapping[str, Any]] = None, delay_s: Optional[float] = None, phase_rad: Optional[float] = None, coherent_with: Optional[str] = None, **extra) -> Dict[str, Any]

A beam on an input port with no beamline behind it. With no pulse, the port is empty on purpose.

loop(kind: str = 'ringDown', max_round_trips: Optional[int] = None, tolerance: Optional[float] = None) -> Dict[str, Any]

Settings of a loop: "ringDown" keeps every pass that leaves, "steadyState" runs until the shape repeats.

beam_splitter(id: str, reflectivity: float = 0.5, output: Optional[str] = None, **extra) -> Dict[str, Any]

A lossless 2x2 splitter, c = t a - r b, d = r a + t b. output is the port a Sequential system keeps.

polarizing_splitter(id: str, transmission_p: Optional[float] = None, reflectivity_s: Optional[float] = None, output: Optional[str] = None, **extra) -> Dict[str, Any]

A polarising splitter: x mostly to port c, y mostly to port d.

leak_mirror(id: str, transmission: float = 0.01, gdd_fs2: Optional[float] = None, leak_gdd_fs2: Optional[float] = None, output: Optional[str] = None, **extra) -> Dict[str, Any]

A mirror whose leak is a port (out, leak).

dichroic(id: str, edge_wavelength_m: float, edge_width_m: Optional[float] = None, reflect_long: Optional[bool] = None, output: Optional[str] = None, **extra) -> Dict[str, Any]

A spectral splitter: port d reflects one side of the edge, port c transmits the other.

delay(id: str, delay_s: Optional[float] = None, length_m: Optional[float] = None, tilt_x_rad: Optional[float] = None, tilt_y_rad: Optional[float] = None, offset_x_m: Optional[float] = None, offset_y_m: Optional[float] = None, **extra) -> Dict[str, Any]

A pure delay on a stage: a time, or a path in vacuum. Tilts and offsets misalign the arm, for mode overlap and tilt fringes.

system(name: str, elements: Sequence[Mapping[str, Any]], materials: Optional[Mapping[str, Any]] = None, coatings: Optional[Mapping[str, Any]] = None, wavelengths_m: Optional[Sequence[float]] = None, overrides: Optional[list] = None, environment: Optional[Mapping[str, Any]] = None, description: Optional[str] = None, substrates: Optional[Mapping[str, Any]] = None) -> 'T.System'

A system file. substrates defines mirror substrates by name (see :func:substrate); environment is the lab air (:func:environment).

bulk(id: str, material: str, length_m: float, beam: Optional[Mapping[str, Any]] = None, nonlinear: Optional[bool] = None, **extra) -> 'T.BulkElement'

fiber(id: str, length_m: float, betas: Optional[Sequence[float]] = None, gamma: Any = None, *, betas_ps_km: Optional[Sequence[float]] = None, loss_db_per_km: Optional[float] = None, gain_db_per_m: Optional[float] = None, raman: Any = None, **extra) -> 'T.FiberElement'

Single-mode fibre (docs/reference/fibers.md): Taylor betas [beta2, beta3, ...] in s^k/m (or betas_ps_km in ps^k/km), gamma in 1/(W m) (or an expression in z), loss, gain, raman = "silica" | "linAgrawal" | "hollenbeck" | "none". extra: dispersion, material, n2, effectiveAreaM2, gain (spectrum), ...

gap(id: str, length_m: float, medium: str = 'Air', air: Optional[Mapping[str, Any]] = None, **extra) -> 'T.GapElement'

Free space (air by default). air (see :func:air) gives this gap its own temperature, pressure, humidity or gas lines instead of the system's environment.air.

interface(id: str, before: str = 'Air', after: str = 'Air', aoi_deg: float = 0.0, coating = None, mode: str = 'refract', **extra) -> 'T.InterfaceElement'

mirror(id: str, coating = None, aoi_deg: float = 0.0, medium: str = 'Air', substrate: Any = None, ripple: Optional[Mapping[str, Any]] = None, delayed_scatter: Optional[Mapping[str, Any]] = None, **extra) -> 'T.MirrorElement'

A reflecting surface. substrate: a name ("FS-12.7mm", or one defined with system(substrates=...)) or :func:substrate -- light leaking through the coating returns as an echo delayed by 2 n_g d cos(theta) / c. ripple: :func:coating_ripple. delayed_scatter: :func:delayed_scatter. aoi_deg defaults to 0 (a Herriott cell: a few mrad).

dispersion(id: str, gdd_s2: float = 0.0, tod_s3: float = 0.0, fod_s4: float = 0.0, **extra) -> 'T.DispersionElement'

grating_pair(id: str, lines_per_mm: float, aoi_deg: float, separation_m: float, order: int = -1, passes: int = 2, efficiency: float = 1.0) -> 'T.GratingPairElement'

chirped_mirror(id: str, gdd_s2: float, bounces: int = 1, reflectance: float = 0.999, tod_s3: float = 0.0, **extra) -> 'T.ChirpedMirrorElement'

Dispersive mirror (GDD/TOD per bounce). extra: e.g. rippleGddFs2=30, ripplePeriodNm=25, complementaryPairs=True.

aperture(id: str, radius_m: Optional[float] = None, beam_radius_m: Optional[float] = None, *, half_width_x_m: Optional[float] = None, half_width_y_m: Optional[float] = None, decenter_x_m: Optional[float] = None, decenter_y_m: Optional[float] = None) -> 'T.ApertureElement'

A hard aperture: round (radius_m) or rectangular (half_width_x_m, half_width_y_m), optionally decentred. On a carried transverse profile it masks the field (edge cells transmit their area fraction) and the light diffracts in the spatial elements after it (docs/reference/transverse.md#diffraction-and-apertures); without one it clips the beam model of radius beam_radius_m.

mask(id: str, kind: str, *, cone_angle_rad: Optional[float] = None, focal_length_m: Optional[float] = None, binary_phase: Optional[bool] = None, design_wavelength_m: Optional[float] = None, charge: Optional[int] = None, count: Optional[int] = None, width_m: Optional[float] = None, separation_m: Optional[float] = None, height_m: Optional[float] = None, file: Optional[str] = None, **extra) -> 'T.MaskElement'

A thin mask on the carried transverse profile (docs/reference/transverse.md#masks): "axicon" (cone_angle_rad), "zonePlate" (focal_length_m, binary_phase), "vortex" (charge), "slits" (count, width_m, separation_m, height_m) or "file" (an NPZ with x_m, y_m or r_m, amplitude, optionally phase_rad). Vortex and slits need a cartesian grid.

modulator(id: str, pitch_m: float, *, phase_rad: Any = None, opd_m: Any = None, amplitude: Any = None, file: Optional[str] = None, cells_x: Optional[int] = None, cells_y: Optional[int] = None, pitch_y_m: Optional[float] = None, offset_x_m: Optional[float] = None, offset_y_m: Optional[float] = None, rotation_rad: Optional[float] = None, design_wavelength_m: Optional[float] = None, chromatic: Optional[str] = None, fill_factor: Optional[float] = None, gap_transmission: Optional[float] = None, outside_transmission: Optional[float] = None, zero_order_leak: Optional[float] = None, crosstalk_sigma_cells: Optional[float] = None, quantisation_levels: Optional[int] = None, phase_wrap_rad: Optional[float] = None, crosstalk_kernel: Any = None, delta_index_cauchy: Any = None, delta_index: Any = None, delta_index_wavelengths_m: Any = None, **extra) -> 'T.ModulatorElement'

A pixelated thin phase / amplitude modulator (SLM, deformable-mirror surface, tile mask) on the carried transverse profile (docs/reference/modulator.md). phase_rad (the phase at design_wavelength_m) or opd_m (an optical path) and amplitude are arrays of shape [cells_x][cells_y] (numpy arrays are converted), a "@name" callback f(x, y, z) -> values evaluated at the cell centres (pass it with uf.run(..., fields={"name": f}): no file, no JSON for a 1920 x 1080 map), or file (NPZ phase_rad / opd_m / amplitude). chromatic: "opd" (default, also "phaseAtDesign"; a wrapped map is a grating), "fixedPhase" (the phase does not change with frequency) or "index" (a liquid-crystal cell: the phase scales as omega dn(omega); give delta_index_cauchy = [A, B_m2, C_m4] or a table delta_index over delta_index_wavelengths_m). crosstalk_kernel: explicit odd-length cross-talk weights in cells (overrides crosstalk_sigma_cells).

tiles_profile(tile_radius_m: float, *, layout: str = 'square', pitch_m: Optional[float] = None, count: Optional[int] = None, count_x: Optional[int] = None, count_y: Optional[int] = None, rings: Optional[int] = None, ring_radius_m: Optional[float] = None, positions_m: Any = None, tile_shape: Optional[str] = None, amplitudes: Any = None, piston_rad: Any = None, tile_tilt_x_rad: Any = None, tile_tilt_y_rad: Any = None, delays_s: Any = None, piston_rms_rad: Optional[float] = None, seed: Optional[int] = None) -> dict

A coherent tiled-aperture source for transverse(initial_profile=...) (docs/reference/transverse.md#coherent-tiles): N sub-beams of 1/e^2 radius tile_radius_m on a "square" (count_x x count_y), "hex" (rings: 1, 7, 19, 37, 61 tiles) or "ring" layout, or at positions_m. Per-tile piston_rad, tile_tilt_*_rad, delays_s and amplitudes take a number or one value per tile.

prism(id: str, material: str, apex_deg: float, aoi_deg: float, path_m: float = 0.0, *, medium: str = 'Air', fresnel: Optional[bool] = None, **extra) -> dict

A prism: two refracting faces and path_m of glass on the carrier's ray. aoi_deg is signed in the unfolded beam; a second prism that undoes the angular dispersion takes the first's exit angle (see the note it writes) as its aoi_deg. Disperses the tracked beam (docs/reference/components.md#spatio-temporal-couplings).

resonator(id: str, elements: Sequence[Mapping[str, Any]], geometry: str = 'ring', *, transverse: Optional[Mapping[str, Any]] = None, round_trips: Optional[Mapping[str, Any]] = None) -> dict

A passive resonator around elements (docs/reference/oscillators.md#resonators): round-trip matrix, stability, eigenmode on the tracked beam; with a transverse grid, the Fox-Li mode and its round-trip loss. geometry "ring" or "linear" (forward and back, end elements once).

coherence(m2: float, modes: Optional[int] = None, *, dimensions: Optional[int] = None, element: Optional[str] = None) -> dict

A partially coherent source (run_spec(coherence=...); docs/reference/transverse.md#partial-coherence): a Gaussian-Schell beam of quality m2 as an incoherent sum of Hermite-Gauss modes, one complete run each, on a cartesian grid.

grating(id: str, lines_per_mm: float, aoi_deg: float, order: int = -1, efficiency: Optional[float] = None, **extra) -> 'T.GratingElement'

One diffraction grating. With the beam tracked (an inputBeam) it disperses the beam: sin(theta_out) = sin(theta_in) + m lambda / period with signed angles in the unfolded beam (a second grating that undoes it has aoi_deg = the first's diffraction angle and the opposite order), anamorphic magnification, angular dispersion, pulse-front tilt, and the group-delay dispersion of the spatio-temporal couplings (docs/reference/components.md#spatio-temporal-couplings).

waveplate(id: str, plate: str = 'half', axis_deg: float = 0.0, design_wavelength_m: Optional[float] = None, *, material: Optional[str] = None, order: Optional[int] = None, thickness_m: Optional[float] = None, construction: Optional[str] = None, plate_thickness_m: Optional[float] = None) -> 'T.WaveplateElement'

Waveplate: dispersionless design model, or with material (Quartz, MgF2, ...) a thick plate with full dispersion (multi-order order / thickness_m, or construction="compound" zero-order).

plate(id: str, material: str, thickness_m: float, aoi_deg: float = 0.0, ghosts: Any = False, coating: Any = None, wedge_deg: float = 0.0, beam: Optional[Mapping[str, Any]] = None, delayed_scatter: Optional[Mapping[str, Any]] = None, **extra) -> 'T.PlateElement'

Plane-parallel plate / window: surfaces, bulk (dispersion, nonlinearity with a beam), optional ghost replicas. The ghosts use the reflectance of coating at each wavelength (a table coating or a stack), not a flat value. delayed_scatter: bulk back-scatter returned as delayed light (:func:delayed_scatter; the default delay is 0 .. 2 n_g d / c).

nd_filter(id: str, od: Any, kind: str = 'absorptive', material: Optional[str] = None, thickness_m: Optional[float] = None, wavelengths_m: Optional[Sequence[float]] = None, aoi_deg: float = 0.0, ghosts: Any = False, **extra) -> 'T.NdFilterElement'

Neutral-density filter: OD (or OD per wavelength with wavelengths_m), absorptive or reflective.

thin_film_polarizer(id: str, output: str = 'transmitted', axis_deg: float = 0.0, aoi_deg: float = 56.0, model: str = 'stack', **extra) -> 'T.ThinFilmPolarizerElement'

Thin-film polariser (physical quarter-wave stack or ideal); output "transmitted" (p) or "reflected" (s).

faraday_rotator(id: str, rotation_deg: float = 45.0, material: Optional[str] = None, length_m: Optional[float] = None, **extra) -> 'T.FaradayRotatorElement'

Faraday rotator (non-reciprocal, Verdet ~ 1/(lambda^2 - lambda0^2)); with a crystal material and length_m.

wavefront(id: str, zernike_noll_waves: Optional[Sequence[float]] = None, radius_m: Optional[float] = None, random_rms_m: Optional[float] = None, correlation_length_m: Optional[float] = None, **extra) -> 'T.WavefrontElement'

A wavefront error: Zernike terms (Noll order, waves) over radius_m and/or a random figure (cartesian grids).

substrate(material: str = 'FusedSilica', thickness_m: Optional[float] = None, *, back_reflectance: Optional[float] = None, back_coating: Any = None, wedge_deg: Optional[float] = None, orders: Optional[int] = None, beam_radius_m: Optional[float] = None) -> dict

A mirror substrate (for mirror(substrate=...) or system(substrates={name: ...})). Light that leaks through the HR coating reflects from the back face (bare Fresnel unless back_reflectance -- a flat power reflectance, e.g. 1e-3 for an AR coating -- or back_coating is given) and returns orders times as an echo delayed by 2 n_g(lambda) d cos(theta_t) / c. Built-in names: FS-3mm, FS-6.35mm, FS-9.5mm, FS-12.7mm, FS-25.4mm, BK7-6.35mm, BK7-12.7mm (fused silica / N-BK7, bare back face).

coating_ripple(phase_rms_rad: float = 0.0, amplitude_rms: float = 0.0, max_delay_s: float = 5e-12, *, seed: Optional[int] = None, components: Optional[int] = None) -> dict

Random phase / amplitude ripple of a mirror coating (for mirror(ripple=...)). The first-order pedestal holds a fraction phase_rms_rad squared of the energy within +-max_delay_s of the pulse. Measured ripple: use a table coating.

delay_uniform(max_s: Optional[float] = None, min_s: float = 0.0) -> dict

Delays uniform in [min_s, max_s] (default max: 2 n_g d cos(theta) / c of the plate, or of the mirror substrate).

delay_exponential(tau_s: float, max_s: Optional[float] = None) -> dict

Delays with an exponential weight exp(-t / tau_s).

delay_table(delays_s: Sequence[float], weights: Sequence[float]) -> dict

Delays from a table (weights are normalised).

delayed_scatter(fraction: Optional[float] = None, delay: Optional[Mapping[str, Any]] = None, spectral_exponent: Optional[float] = None, *, seed: Optional[int] = None, components: Optional[int] = None, model: Optional[str] = None, roughness_rms_m: Optional[float] = None, correlation_length_m: Optional[float] = None, beam_radius_m: Optional[float] = None, surfaces: Optional[int] = None) -> dict

Scatter as delayed light, not loss. Generic model: fraction of the power returns incoherently after delay (:func:delay_uniform, :func:delay_exponential, :func:delay_table) with an intensity weight lambda^-spectral_exponent. Analytic surface model (model="surface"): rms roughness roughness_rms_m gives the total integrated scatter (4 pi sigma / lambda)^2 per surface; the share 1 - exp(-(l/w)^2) of it (correlation length l, beam radius w) stays in the mode and returns after delay (none: at once), the rest is lost (booked as scatter). surfaces defaults to 1 (mirror) / 2 (plate).

air(*, temperature_c: Optional[float] = None, pressure_pa: Optional[float] = None, humidity: Optional[float] = None, co2_ppm: Optional[float] = None, apply_to_gaps: Optional[bool] = None, kind: Optional[str] = None, **model) -> 'T.Air'

Lab air (Ciddor index from temperature, pressure, relative humidity 0..1 and CO2), for environment(air=...) or one gap(air=...). apply_to_gaps=True uses it as the "Air" of every gap (off by default: existing results do not change). kind="hitran" (hitran plugin) adds line-by-line absorption and dispersion: see ultrafast_hitran.air.

environment(air: Optional[Mapping[str, Any]] = None, index_reference: Optional[str] = None) -> 'T.Environment'

The system's environment: the lab air and whether quoted data are relative to "air" or "vacuum".

grid(*, n: Optional[int] = None, window_s: Optional[float] = None, window_ps: Optional[float] = None, auto: Optional[bool] = None, max_n: Optional[int] = None, snap_carrier: Optional[bool] = None, spectral_margin: Optional[float] = None, min_span_fraction: Optional[float] = None, min_points_per_fwhm: Optional[float] = None, satellite_level: Optional[float] = None, extend_for_satellites: Optional[bool] = None, strict: Optional[bool] = None, tail: Any = None) -> 'T.Grid'

The time grid. tail=True (or :func:tail_grid) adds the delayed-light ledger: a second, long, linear grid with the same time step that carries ghosts, echoes, scatter and gas-line tails while the nonlinear solver stays on the small main grid. extend_for_satellites=True grows a manual window to hold the satellites; strict=True makes a wrapping satellite an error.

tail_grid(window_s: Optional[float] = None, warn_energy_fraction: Optional[float] = None, *, exact_steps: Optional[bool] = None, cross_phase: Optional[bool] = None) -> dict

grid(tail=tail_grid(window_s=2e-9)): the long tail grid of the delayed-light ledger (default window: from the satellites, at least 8 x the main window). A warning is added when the tail holds more than warn_energy_fraction (0.01) of the energy. exact_steps=True takes the exact long-grid step for every linear element (default: smooth elements -- dispersion, flat loss, bare surfaces -- act on main and tail separately, much cheaper); cross_phase=False leaves out the first-order cross-phase of the tail by the main pulse in nonlinear elements.

detector_response(wavelengths_m: Sequence[float], values: Sequence[float]) -> dict

A spectral response table (e.g. the quantum efficiency) for detector(response=...): linear in wavelength, held at the ends.

detector(*, calibration: Optional[float] = None, noise: Optional[float] = None, noise_floor: Optional[float] = None, dynamic_range_db: Optional[float] = None, saturation_level: Optional[float] = None, bit_depth: Optional[int] = None, response: Optional[Mapping[str, Any]] = None, counting: Optional[str] = None, seed: Optional[int] = None, preset: Optional[str] = None) -> Dict[str, Any]

The read-out of an instrument (instrument(..., detector=detector(...))). response (:func:detector_response) is the spectral response of a spectral instrument; counting="photons" converts the energy spectrum to photon counts first. preset names an entry of run_spec(detectors=...) (or a JSON file) that the other keys override.

detector_preset(*, instrument: Optional[Mapping[str, Any]] = None, detector: Optional[Mapping[str, Any]] = None) -> dict

A reusable detector preset for run_spec(detectors={name: ...}): instrument keys fill instrument parameters the instrument does not set (saturationLevel, segments from :func:detector_segment, noiseFloor, ...); detector is the read-out. An instrument uses it with detector="name". Numbers are yours (a manual, a calibration): none are built in.

detector_segment(from_s: float, to_s: float, attenuation: float = 1.0, noise_floor: Optional[float] = None) -> dict

One delay range of a cross-correlator scan measured through an attenuation (a power factor): for the instrument's segments=[...] (stitching) together with saturation_level-style keys saturationLevel and noiseFloor.

pedestal(kind: str, **params) -> dict

A pedestal / contrast component for pulse(..., pedestal=[...]): kind replica | prePulse | postPulse | ase | phaseNoise | exponential (docs/reference/run-spec.md#pedestal); parameters in the engine's spelling (delayS, relativeIntensity, rmsRad, ...).

polarizer(id: str, axis_deg: float = 0.0, extinction_ratio: float = 100000.0) -> 'T.PolarizerElement'

filter_element(id: str, model: Mapping[str, Any]) -> dict

probe(id: str) -> 'T.ProbeElement'

lens(id: str, focal_length_m: float, material: Optional[str] = None, thickness_m: float = 0.0, medium: str = 'Air') -> 'T.LensElement'

Thin lens acting on a carried transverse profile (chromatic if a lens material is given).

user(id: str, callback: str, params: Optional[Mapping[str, Any]] = None, length_m: float = 0.0) -> 'T.UserElement'

User element: callback is the name registered with Run.element(name, fn).

transverse(model: str = 'radial', points: Optional[int] = None, radius_m: Optional[float] = None, nx: Optional[int] = None, ny: Optional[int] = None, half_width_m: Optional[float] = None, transport: Optional[str] = None, initial_profile: Optional[Mapping[str, Any]] = None, *, absorbing_boundary: Any = None, spectral_samples: Optional[int] = None, frequency_block: Optional[int] = None, **extra) -> dict

Transverse (spatial) model for an element: "radial" (Hankel) or "cartesian" (x-y FFT). absorbing_boundary (True, or {"widthFraction": 0.15}) absorbs light leaving the grid in linear elements instead of reflecting / wrapping it (booked as "grid boundary"); spectral_samples (48) is the number of frequencies at which the profile is stored -- fewer is faster for narrowband pulses; frequency_block streams linear propagation over the stored frequencies in blocks of that many (same result; saves memory for blocks under half the stored frequencies).

initial_profile(kind: str = 'gaussian', *, order: Optional[int] = None, radius_m: Optional[float] = None, geometry: Optional[str] = None, radius_x_m: Optional[float] = None, radius_y_m: Optional[float] = None, radius_of_curvature_m: Optional[float] = None, mode_x: Optional[int] = None, mode_y: Optional[int] = None, mode_p: Optional[int] = None, mode_l: Optional[int] = None, cone_angle_rad: Optional[float] = None, truncation: Optional[float] = None, file: Optional[str] = None, background: Any = None, ripple: Optional[Mapping[str, Any]] = None, noise: Optional[Mapping[str, Any]] = None, **extra) -> dict

The field at the first spatial element (transverse(initial_profile=...)): "gaussian", "superGaussian" (order), "flatTop" (super-Gaussian of order 10), "tophat" (hard edge), "hermiteGauss" (mode_x, mode_y), "laguerreGauss" (mode_p, mode_l), "besselGauss" (cone_angle_rad, Gaussian envelope of radius_m), "airy" (scale radius_m, truncation) or "measured" (file: an NPZ with x_m, y_m or r_m, fluence or amplitude, optionally phase_rad; background: a number or "auto"). geometry "round" (default) or "square" (separable in x and y; cartesian grids). radius_m (or radius_x_m / radius_y_m) is the 1/e^2 radius, or the edge radius / half-width of a tophat; it replaces the element's beam size, so no beam is needed. ripple / noise (cartesian grids) seed small-scale self-focusing: :func:profile_ripple, :func:profile_noise.

profile_ripple(period_m: float, relative_amplitude: float, angle_deg: float = 0.0, phase_rad: float = 0.0) -> dict

A sinusoidal amplitude ripple a cos(2 pi (x cos t + y sin t) / period + phase) on the field: the Bespalov-Talanov seed. The ripple of the fluence is 2 a; with a plane wave of intensity I it grows as cosh(g z), g^2 = q (2 Delta - q), q = K^2 / 2k, Delta = k0 n2 I.

profile_noise(relative_amplitude_rms: float = 0.0, correlation_length_m: float = 5e-05, phase_rms_rad: float = 0.0, seed: int = 1, components: Optional[int] = None) -> dict

Seeded smooth random amplitude (relative rms) and phase noise with the given correlation length: the seed of small-scale self-focusing. The element reports fluenceContrastIn / Out and smallScaleGain.

aux_beam(role: str, pulse: Optional[Mapping[str, Any]] = None, *, from_results: Optional[str] = None, energy: Optional[float] = None, radius_m: Optional[float] = None, profile: str = 'gaussian', order: Optional[int] = None, delay_s: Any = 'auto', radius_of_curvature_m: Optional[float] = None, from_port: bool = False) -> dict

Auxiliary beam for a crystal: a pulse spec (see :func:pulse), from_results (a results folder), or from_port=True in a Branched system: the beam arriving at the input port named role (docs/reference/branches.md#crystals).

crystal(id: str, crystal: Any, length_m: float, process: str = 'shg', type: Optional[str] = None, *, cut: Any = 'auto', noncollinear: Any = None, external_angle_deg: Optional[float] = None, qpm: Any = None, aux: Optional[list] = None, output: Optional[str] = None, main_role: Optional[str] = None, record: Optional[list] = None, beam: Optional[Mapping[str, Any]] = None, transverse: Optional[Mapping[str, Any]] = None, deff_pm_per_v: Optional[float] = None, seed_noise: Optional[bool] = None, temperature_c: Optional[float] = None, overlap: Any = None, chi3: Optional[bool] = None, **extra) -> 'T.CrystalElement'

A chi(2) crystal element (docs/reference/crystals.md).

pump(kind: str = 'cw', wavelength_m: float = 9.4e-07, radius_m: float = 0.0005, power_w: Optional[float] = None, energy_j: Optional[float] = None, profile: str = 'tophat', order: Optional[int] = None, passes: int = 1, delay_s: Optional[float] = None) -> dict

A pump for gain / amplifier elements: kind "cw" (power_w) or "pulsed" (energy_j, delay_s before the seed); profile "tophat" | "gaussian" | "superGaussian" (order); passes 2 = reflected back through the crystal.

gain(id: str, medium: Any, length_m: float, pump: Optional[Mapping[str, Any]] = None, inversion: Optional[Mapping[str, Any]] = None, beam: Optional[Mapping[str, Any]] = None, mode_radius_m: Optional[float] = None, transverse: Optional[Mapping[str, Any]] = None, thermal_lens: Any = None, slices: Optional[int] = None, steady_state: Any = None, **extra) -> 'T.GainElement'

A pumped gain medium crossed once (docs/reference/gain.md). medium = "Yb:YAG" | "Ti:sapphire" | "Nd:YAG" or a gain-medium object ({"base": "Yb:YAG", "dopingDensityM3": ...} or a full definition); inversion = {"fraction": b} or {"smallSignalGain": G} instead of / on top of a pump; transverse for spatial gain.

thermal_lens(*, rod_radius_m: Optional[float] = None, heat_fraction: Optional[float] = None, apply: Optional[bool] = None, track: Optional[bool] = None, focal_length_m: Optional[float] = None, pass_gap_m: Optional[float] = None, stress: Optional[bool] = None) -> dict

The thermal lens of a gain element (gain(thermal_lens=...); docs/reference/gain.md#thermal-lens): heat = heat_fraction (default the quantum defect) x absorbed pump, conducted to a rod of radius rod_radius_m. track (default True) also puts it on the tracked Gaussian beam (thin lenses per slice, fitted over the beam; a multipass amplifier only when track or pass_gap_m, the free path between passes, is given); focal_length_m is a measured focal length used instead of the heat model; stress adds thermal birefringence (cubic hosts): the depolarised fraction moves to y, and the two thermal lenses f_r, f_phi are reported.

multipass_amplifier(id: str, medium: Any, length_m: float, passes: int, pump: Optional[Mapping[str, Any]] = None, between_passes: Optional[Mapping[str, Any]] = None, mode_radius_m: Optional[float] = None, beam: Optional[Mapping[str, Any]] = None, inversion: Optional[Mapping[str, Any]] = None, **extra) -> dict

A multipass amplifier (1-D): between_passes = {"loss": 0.02, "gddFs2": .., "materials": [{"name", "lengthM"}]}.

regenerative_amplifier(id: str, medium: Any, length_m: float, round_trips: Any = 'auto', pump: Optional[Mapping[str, Any]] = None, cavity: Optional[Mapping[str, Any]] = None, mode_radius_m: Optional[float] = None, beam: Optional[Mapping[str, Any]] = None, inversion: Optional[Mapping[str, Any]] = None, passes_per_round_trip: Optional[int] = None, **extra) -> dict

A regenerative amplifier (1-D): round_trips = N or "auto" (eject at the energy maximum); cavity = {"lossPerRoundTrip": .., "gddFs2": .., "todFs3": .., "materials": [...]}.

saturable_absorber(id: str, kind: str = 'slow', modulation_depth: float = 0.02, nonsaturable_loss: float = 0.0, recovery_time_s: Optional[float] = None, saturation_fluence_j_per_m2: Optional[float] = None, spot_radius_m: Optional[float] = None, saturation_energy_j: Optional[float] = None, saturation_power_w: Optional[float] = None, kappa_per_w: Optional[float] = None) -> 'T.SaturableAbsorberElement'

A saturable absorber element: kind "slow" (SESAM), "fast" or "kerrLens".

soft_aperture(id: str, radius_m: float, order: int = 1) -> dict

A soft (Gaussian, or super-Gaussian of order) aperture acting on a carried transverse profile.

gaussian_beam(w0_m: float, z_waist_m: float = 0.0, m2: float = 1.0, wavelength_m: Optional[float] = None) -> dict

constant_beam(radius_m: Optional[float] = None, area_m2: Optional[float] = None) -> dict

sampled_beam(z_m: Sequence[float], radius_m: Sequence[float]) -> dict

material(index: Any = None, n2: Optional[float] = None, base: Optional[str] = None, raman: Any = None, attenuation: Any = None, gas: Optional[Mapping[str, Any]] = None, index_reference: Optional[str] = None, **extra) -> dict

sellmeier(B: Sequence[float], C: Sequence[float]) -> dict

gas(species: str, pressure_bar: float = 1.0, temperature_k: float = 293.15) -> dict

coating_gdd(R: float, gdd_s2: float, tod_s3: float = 0.0) -> dict

coating_quarter_wave(design: str, design_wavelength_m: float, H: str = 'Ta2O5', L: str = 'SiO2_film') -> dict

cw(wavelength_m: float, power_w: float) -> dict

A cw source: one spectral bin at wavelength_m (docs/reference/run-spec.md#cw-sources). Fluences are intensity x the window (1 ns unless grid.windowS is set); beamProfile also reports peakIntensityWPerM2.

pulse(center_wavelength_m: float, duration_fwhm_s: Optional[float] = None, energy: Optional[float] = None, shape: str = 'gaussian', rep_rate_hz: Optional[float] = None, average_power_w: Optional[float] = None, peak_power_w: Optional[float] = None, gdd_s2: float = 0.0, tod_s3: float = 0.0, polarization = 'x', **extra) -> 'T.Pulse'

measured_spectrum(wavelengths_m: Sequence[float], intensity: Sequence[float], energy: Optional[float] = None, phase_rad: Optional[Sequence[float]] = None, *, background: Any = None, threshold: Optional[float] = None, resolution_m: Optional[float] = None, deconvolve: Optional[bool] = None, extrapolate: Optional[str] = None, center_wavelength_m: Optional[float] = None, **extra) -> 'T.Pulse'

An input pulse from a measured spectrum (intensity per unit wavelength, optional phase), docs/reference/measured-data.md.

measured_spectrum_csv(csv: str, energy: Optional[float] = None, *, wavelength_unit: Optional[str] = None, background: Any = None, threshold: Optional[float] = None, resolution_m: Optional[float] = None, deconvolve: Optional[bool] = None, extrapolate: Optional[str] = None, center_wavelength_m: Optional[float] = None, **extra) -> 'T.Pulse'

An input pulse from a spectrum file (CSV: wavelength, intensity, optional phase in rad; wavelength_unit "nm" (default), "um" or "m"). Relative paths are resolved against the run file's folder. Same cleaning and options as :func:measured_spectrum.

measured(file: Optional[str] = None, *, values: Optional[Mapping[str, Any]] = None, sigma: Optional[float] = None, normalize: Optional[str] = None, background: Any = None, columns: Optional[Mapping[str, str]] = None, range_x: Optional[Sequence[float]] = None, x_unit: Optional[str] = None, y_unit: Optional[str] = None, value_sigma: Optional[float] = None, weight: Optional[float] = None, resolution_m: Optional[float] = None, resolution_s: Optional[float] = None, match_resolution: Optional[bool] = None, scale: Optional[str] = None, sigma_db: Optional[float] = None, floor_db: Optional[float] = None, simulated: Optional[Mapping[str, str]] = None, **extra) -> 'T.Measured'

Recorded data for an instrument (its measured key; docs/reference/measured-data.md): a CSV / NPZ / JSON file and/or scalar values ({name: value | [value, sigma]}, e.g. {"energyJ": [1.2e-6, 2e-8]}).

instrument(kind: str, at: str = 'end', name: Optional[str] = None, **params) -> dict

An instrument (docs/reference/instruments.md). Keyword arguments are its parameters in the engine's names (resolutionM=..., axis=axis(...), detector={...}, measured=measured(...) to compare with a recording).

axis(values: Optional[Sequence[float]] = None, *, start: Optional[float] = None, stop: Optional[float] = None, step: Optional[float] = None, points: Optional[int] = None, bin_width: Any = None, resolution: Optional[float] = None) -> dict

Where a curve instrument takes its readings (docs/reference/instruments.md#axis-where-readings-are-taken): explicit values (e.g. your spectrometer's pixel wavelengths) or start/stop with step or points, each reading integrating over bin_width (a number or "pixel") and blurred by a Gaussian resolution (FWHM). SI units of the axis (m for wavelengths, s for delays). Use as instrument("spectrometer", axis=axis(...)).

override(target: str, prop: str, model: Any = None, value: Any = None, mode: str = 'replace') -> dict

physics(*, beam_tracking: Any = None, spatio_temporal: Any = None, transverse: Optional[Mapping[str, Any]] = None, **extra) -> 'T.Physics'

Physics switches of a run (run_spec(physics=...)). beam_tracking: "auto" | "on" | "off" (Gaussian q tracking from the input_beam); spatio_temporal: "auto" | "on" | "track" | "profile" | "off" -- angular / spatial dispersion and pulse-front tilt carried with the tracked beam, their dispersion applied to the pulse ("track": reported only; "profile": gratings and tilted surfaces tilt each frequency of a carried cartesian profile instead); transverse: the default spatial model. Other keys (nonlinear, raman, ...) go through extra.

run_spec(pulse: Mapping[str, Any], name: str = 'run', grid: Optional[Mapping[str, Any]] = None, physics: Optional[Mapping[str, Any]] = None, stepper: Optional[Mapping[str, Any]] = None, probes: Any = 'all', instruments: Optional[list] = None, overrides: Optional[list] = None, outputs: Optional[Mapping[str, Any]] = None, input_beam: Optional[Mapping[str, Any]] = None, compute: Optional[Mapping[str, Any]] = None, detectors: Optional[Mapping[str, Any]] = None, **extra) -> 'T.RunSpec'

A run spec. compute selects the compute back-end (:func:compute; GPU: compute(backend="auto")). extra adds top-level keys provided by plugins, e.g. fit= (fitting plugin: from ultrafast_fitting import fit).

compute(backend: Optional[str] = None, *, threads: Optional[int] = None, fft: Optional[str] = None, device: Optional[int] = None, gpu_min_points: Optional[int] = None) -> 'T.Compute'

Where the run computes (docs/reference/speed.md).

sampling(plane: str = 'near', aperture: str = 'pinhole', radius_m: Optional[float] = None, width_m: Optional[float] = None, focal_length_m: Optional[float] = None, center_x_m: Optional[float] = None, center_y_m: Optional[float] = None, na: Optional[float] = None, propagate_m: Optional[float] = None) -> dict

Where an instrument looks (docs/reference/instruments.md): plane "near" | "far" (focal plane of a lens of focal_length_m), aperture "integrated" | "pinhole" | "iris" | "fibre" | "slit" | "point". Use as instrument("spectrometer", sampling=sampling("far", "fibre", radius_m=25e-6, focal_length_m=0.1)).

save(obj: Mapping[str, Any], path: str) -> str

ultrafast.measured

Measured data: typed comparisons of instruments with recordings (res.comparisons), compared arrays.

Measured data: recordings compared with the simulated instruments, and typed access to the comparisons.

class ComparedValue(TypedDict)

One scalar reading compared with its recorded value.

class Comparison(TypedDict)

An instrument compared with recorded data (one entry of summary["comparisons"]).

class MeasuredCurve(TypedDict)

A compared curve on the measured axis (SI units), normalised as in the comparison.

class MeasuredTrace(TypedDict)

A compared 2-D trace on the measured axes, [rows, cols].

comparisons(result: Any) -> List[Comparison]

Every instrument compared with recorded data (a :class:ultrafast.Result or a results folder), or [].

comparison(result: Any, instrument: str) -> Comparison

The comparison of one instrument (by name). KeyError if it has none.

total_chi2(result: Any) -> float

Sum of the chi^2 of all comparisons (summary["measuredChi2"]), 0 if none.

curve(result: Any, instrument: str) -> MeasuredCurve

The measured curve and the simulated reading on the same (measured) axis, as compared.

trace(result: Any, instrument: str) -> MeasuredTrace

The measured 2-D trace and the simulated trace on the same axes, as compared ([rows, cols]).

ultrafast.materials

The material library: list, show, import refractiveindex.info pages.

The material library: built-in materials, gases (with rotational Raman), birefringent crystals and the refractiveindex.info pages bundled with the engine or imported into the user library (docs/reference/materials.md).

available() -> Dict[str, Any]

Names of everything the engine knows: built-in materials, gases, birefringent crystals, refractiveindex.info pages.

show(name: str) -> Dict[str, Any]

Index model, n2, rotational Raman and a table of n, group index and GVD (fs^2/mm) of a material or page.

import_page(path: 'os.PathLike[str] | str', name: Optional[str] = None) -> Dict[str, Any]

Copy a refractiveindex.info YAML page into the user library and return the material definition to use.

refractiveindex(page: str, pressure_bar: Optional[float] = None, temperature_k: Optional[float] = None) -> Dict[str, Any]

An index model dict for a refractiveindex.info page (bundled, imported, a file, or from ULTRAFAST_RII_PATH).

ultrafast.laser

Laser and amplifier helpers.

Building mode-locked oscillators (docs/reference/oscillators.md).

class Oscillator

Fluent builder for an oscillator element (models "haus", "cavity", "parametric").

  • __init__(id: str = 'laser', model: str = 'haus', rep_rate_hz: Optional[float] = None, cavity_length_m: Optional[float] = None, ring: bool = False, output_coupler: float = 0.05)
  • simple_gain(small_signal_gain: float, saturation_energy_j: Optional[float] = None, saturation_power_w: Optional[float] = None, bandwidth_m: Optional[float] = None, center_wavelength_m: Optional[float] = None, shape: str = 'lorentzian', fluence_saturation_energy_j: Optional[float] = None) -> 'Oscillator' -- Lumped gain: power gain per round trip small_signal_gain, saturated by the intracavity pulse energy (or average power), spectral shape of FWHM bandwidth_m.
  • gain_medium(medium: Any, length_m: float, pump: dict, mode_radius_m: float, passes: int = 2, slices: int = 8, relaxation: float = 0.2, **extra) -> 'Oscillator' -- A real gain medium (cavity model): cw pump, inversion from the average powers, spectral gain, host dispersion and SPM on every pass.
  • loss(fraction: float) -> 'Oscillator'
  • dispersion(gdd_fs2: float = 0.0, tod_fs3: float = 0.0) -> 'Oscillator'
  • spm(rad_per_w: float) -> 'Oscillator' -- Self-phase modulation per round trip: phase = rad_per_w x power.
  • absorber(kind: str = 'slow', **params) -> 'Oscillator' -- Saturable absorber: haus model -> the lumped absorber; cavity model -> a saturableAbsorber element appended to the cavity. Parameters as in docs: modulation_depth, nonsaturable_loss, recovery_time_s, saturation_fluence_j_per_m2 + spot_radius_m (or saturation_energy_j), saturation_power_w, kappa_per_w.
  • add(*elements) -> 'Oscillator' -- Append engine elements (as built with ultrafast.build) to the cavity round trip, in order.
  • start(mode: str = 'noise', seed_energy_j: Optional[float] = None, seed: Optional[int] = None) -> 'Oscillator'
  • round_trips(max: int = 5000, tolerance: float = 1e-05, check_every: int = 25, snapshots: int = 120) -> 'Oscillator'
  • element() -> dict
  • system(name: Optional[str] = None, after: Optional[List[dict]] = None) -> dict -- A system file: the oscillator, then optionally after (e.g. a compressor, an amplifier).
  • soliton_fwhm_s(gdd_s2: float, spm_rad_per_w: float, energy_j: float) -> float -- Soliton area theorem: FWHM = 3.53 |GDD| / (delta E) (sech^2 pulse, lumped cavity).
  • kerr_spm_coefficient(n2: float, length_m: float, mode_radius_m: float, wavelength_m: float, passes: int = 2) -> float -- delta (rad/W) of a Kerr medium: k0 n2 L passes / (pi w^2 / 2).

ultrafast.crystal

χ(2) crystal helpers.

Phase-matching calculator (the engine's PhaseMatchCalculator, also ultrafast crystal on the CLI).

crystals() -> list

Names of the built-in chi(2) crystals.

phase_match(crystal: Union[str, dict], process: str = 'shg', type: Optional[str] = None, *, fundamental: Optional[float] = None, pump: Optional[float] = None, signal: Optional[float] = None, idler: Optional[float] = None, a: Optional[float] = None, b: Optional[float] = None, plane: Optional[str] = None, theta_deg: Optional[float] = None, phi_deg: Optional[float] = None, noncollinear: Union[None, float, str] = None, qpm: Union[None, bool, float] = None, length: float = 0.001, temperature_c: Optional[float] = None, pump_intensity: Optional[float] = None, polarizations: Optional[Dict[str, str]] = None, **extra) -> dict

Solve phase matching. Wavelengths in metres; noncollinear in degrees or "magic"; qpm=True (period found) or a period in metres. type defaults to "I" (birefringent) or "0" (QPM). Returns the calculator's JSON as a dict with phaseMatched, best (angles, deffPmPerV, waves, acceptance, gvm, gainSpectrum...) and solutions.

ultrafast.plugins

Plugin discovery and loading.

Plugins from Python: which are installed, and loading their Python parts.

class PluginInfo

An installed plugin folder (from its plugin.json).

search_paths() -> List[Path]

Folders searched for plugins, in order.

installed() -> List[PluginInfo]

Every plugin folder found in :func:search_paths (first occurrence of each id).

load_python_plugins() -> Dict[str, ModuleType]

Import the Python module of every installed plugin (once) and call its register(host), where host offers register_figure. Returns {plugin id: module}. Errors are warnings, never fatal.

module(plugin_id: str) -> Optional[ModuleType]

The Python module of an installed plugin (loading plugins if needed), or None.

loaded() -> List[str]

Ids of plugins whose Python module is loaded.

ultrafast.plot

Quick plots of results (matplotlib).

Plot results written by the ultrafast CLI.

main(argv = None) -> int

ultrafast.plotting

Plotting package: report, plot, register_figure, the figures (re-exported from the modules below).

Publication-style plots of UltrafastEngine results (needs matplotlib: pip install ultrafast-engine[plot]).

register_figure(name: str, maker: Callable, after: Optional[str] = None) -> None

Add a figure to :func:report and ultrafast-plot (used by plugins, e.g. the fitting plugin's measurements and fit). maker(res) returns a matplotlib figure, or None when the result has no data for it. after places it after an existing figure in the default order.

report(res, out_dir: Union[str, Path, None] = None, formats: Iterable[str] = ('png',), pdf: bool = True, only: Optional[Iterable[str]] = None, db: bool = False, dpi: int = 160, close: bool = True) -> Dict[str, object]

Draw every figure that has data, save them as <out_dir>/<name>.<fmt> and (optionally) all of them in one report.pdf. out_dir defaults to <results folder>/plots. Returns {name: figure or path}.

plot(result, what = 'overview', ax = None)

uf.plot(result, what): "overview" or "measurements" (figures), or a single panel "temporal" / "spectrum" / "phase" / "losses" / "elements" on ax.

ultrafast.plotting.style

Themes, matplotlib style, SI-prefix formatting.

Colour themes, matplotlib style, SI-prefix formatting and small axis helpers shared by every figure.

set_theme(dark: bool = False) -> None

Switch the colour theme for figures created afterwards.

fmt(x, unit: str = '', digits: int = 3) -> str

Engineering formatting: fmt(2.2e-13, 's') -> '220 fs'.

ultrafast.plotting.data

Reading a saved results folder.

Reading a results folder (summary.json + result.npz) written by the CLI: :class:SavedResult, :func:load.

class SavedResult

A results folder written by the CLI / Result.write: same interface as a live Result (summary, provenance, names(), result[name], instrument(name), comparisons, comparison(name)).

  • __init__(directory: Union[str, Path])
  • name() -> str
  • names() -> List[str]
  • instrument(name: str) -> dict
  • comparisons() -- Instruments compared with recorded data (:mod:ultrafast.measured).
  • comparison(instrument: str) -- The comparison of one instrument with its recorded data (KeyError if it has none).

load(source) -> 'SavedResult'

A results folder (str/Path) -> :class:SavedResult; a live Result / SavedResult is returned as is.

ultrafast.plotting.time_domain

Temporal panels.

Temporal panels: the pulse in time, input and output.

temporal(res, ax = None, compressed: bool = True, normalize: bool = False)

Input and output power vs time (plus the ideally compressed output, if an ideal compressor ran).

ultrafast.plotting.spectral

Spectral panels.

Spectral panels: spectrum (linear or dB) and spectral phase.

spectrum(res, ax = None, db: bool = False, floor_db: Optional[float] = None)

Input and output spectral density vs wavelength (linear, normalised; or dB). With db, the floor follows the data (down to -120 dB) unless floor_db is given, and the wavelength range covers everything above it.

spectral_phase(res, ax = None, xlim = None)

Output (and input) spectral phase with offset and group delay removed, where the spectrum is > 1 %.

ultrafast.plotting.run_figures

Whole-run figures: overview, losses, gain, oscillator, comparison.

Whole-run figures: overview, element-by-element evolution, losses, gain, oscillator, by-products, run comparison.

evolution(res, axs = None)

Energy, FWHM and cumulative B-integral after each element (three stacked panels, shared x).

losses(res, ax = None)

Energy budget by mechanism. Losses are positive; energy brought in by auxiliary beams (crystals, amplifiers) is negative ("from pump (aux)"). Shown as % of all energy that entered (input + auxiliary beams).

key_numbers(res, ax = None)

Text panel with the headline numbers, warnings and notes.

overview(res, db: bool = False)

Six-panel summary: pulse, spectrum, spectral phase, evolution, losses, key numbers.

elements(res)

Per-element quantities as small multiples (shared x = element).

compare(results: Sequence, labels: Optional[Sequence[str]] = None, db: bool = False)

Overlay the output pulse and spectrum of several runs (max. 8; colours follow the run order).

byproducts(res)

Fields that left an active element alongside the main beam (crystal idler / unconverted pump, ...): one row per element, spectrum and power of the main output and of every recorded by-product. Returns None if the run has none.

gain(res)

Gain and amplifier elements: one row per element with the single-pass small-signal gain spectrum (and the output spectrum), the inversion along the crystal before / after the pulse (or across the beam for spatial models), the build-up per pass / round trip and the pulse-train convergence. Returns None if the run has none.

oscillator(res)

Oscillator elements: build-up of the output energy over the round trips, the evolution of the output pulse (time) and spectrum (wavelength) from start-up to steady state, and the final pulse with the key numbers. Returns None if the run has no iterated oscillator.

ultrafast.plotting.spatial

Image panels.

Spatial (image) panels shared by the instrument and probe figures.

(No public functions; see the exported names above.)

ultrafast.plotting.instrument_panels

Instrument panels, probes, measured versus simulated.

One panel per instrument, probes and the measured-versus-simulated figure.

instruments(res)

One panel per instrument (d-scan / FROG traces as images). Returns None if no instrument has data.

probes(res, db: bool = True, floor_db: Optional[float] = None)

Spectral and temporal evolution through the probes (heat maps, one row per probe, input at the bottom). The dB floor follows the data (down to -60 dB) unless floor_db is given. Returns None if the run recorded fewer than two probes.

measurements(res)

Recorded data against the simulation (instruments with measured data, docs/reference/measured-data.md): one row per instrument with "measured" data -- the measured curve (points), the simulated reading on the same axis (line, with its 1-sigma band after a fit) and the residual; for 2-D traces (FROG, d-scan, cameras) the measured and simulated traces and their difference; for scalar readings a table. Returns None if the run compared nothing.

ultrafast.plotting.diagrams

Layout diagrams of a system (the old ultrafast.diagram).

Schematic of a simulated system for the plots: elements in order, the beam line coloured by its carrier wavelength, auxiliary beams coming in, by-products leaving, probes, and numbered instrument locations.

circled(n: int) -> str

instrument_locations(summary: dict) -> List[dict]

Instruments in system order (input first, then by element, end last), numbered from 1. Each entry: number, tag (①), name, kind, at, index (-1 input, element index, len for end), where, virtual.

location_text(summary: dict, at: str) -> str

wavelength_color(lam: float) -> str

Approximate perceived colour of a wavelength; IR fades from deep red to grey-brown, UV to violet-grey.

group_elements(els: List[dict], max_items: int = 22) -> List[dict]

Collapse repeated units (e.g. 20 x [pass, mirror] in a multipass cell) into one item with a repeat count. Returns items {"start": i, "unit": L, "repeat": R}; plain elements have unit 1, repeat 1.

draw_system(res, ax, theme: dict, compact: bool = False)

Draw the schematic of res (live Result or results folder) on ax.

draw_graph(res, ax, theme: dict, compact: bool = False)

Draw a Branched system as a graph on ax: elements as boxes by layer, arms as lanes, links coloured by the carrier after their source element, virtual inputs and outputs as small open markers, the energy at the end, loops as arcs.

system_diagram(res, ax = None, compact: bool = False)

Schematic of the system on ax: elements, beam line coloured by carrier wavelength, aux beams in, by-products out, probes and numbered instrument locations (the numbers used in every instrument title).

system(res)

Stand-alone system schematic with a numbered list of the instruments and where they sit.

ultrafast.plotting.zernike

Zernike decomposition figure.

Zernike decomposition figure: the wavefront, its Zernike reconstruction, the residual and a bar chart of the Noll coefficients (rms, in waves) coloured by radial order, with the rms and the Marechal Strehl estimate in the title.

wavefront_from(source: Any, x = None, y = None, wavelength: Optional[float] = None, radius: Optional[float] = None) -> Tuple[np.ndarray, np.ndarray, np.ndarray, float]

Normalise the accepted inputs to (map_in_waves[x][y], x, y, radius).

decomposition(sources: Union[Any, Sequence[Any]], labels: Optional[Sequence[str]] = None, *, x = None, y = None, wavelength: Optional[float] = None, radius: Optional[float] = None, max_noll: int = 15, remove_tilt: bool = False, vlim_waves: Optional[float] = None, coeff_lim_waves: Optional[float] = None)

The Zernike decomposition figure for one wavefront (see the module docstring for the accepted inputs) or a list of them, one row each.

animate_decomposition(wavefronts: Sequence[Any], path, labels: Optional[Sequence[str]] = None, *, fps: float = 6, dpi: int = 70, pause_last_s: float = 1.5, **kw) -> Dict[str, Any]

Step through a list of wavefronts (e.g. the iterations of a deformable-mirror correction) and write an animated GIF with one decomposition per frame, on one fixed colour and coefficient scale. kw goes to :func:decomposition.

ultrafast.plotting.animate

Animated GIF (and optional MP4) writer; the figure size budget.

Animations: one function draws a figure per frame, :func:animate writes an animated GIF (Pillow; no ffmpeg needed) and, when ffmpeg is on the path and mp4=True, an MP4 as well.

render_frame(fig, dpi: int = 80) -> np.ndarray

Draw a figure to an RGB uint8 array (Agg; no display needed).

animate(frame: Callable[[Any], Any], frames: Iterable[Any], path: Union[str, Path], fps: float = 15, dpi: int = 80, loop: int = 0, pause_last_s: float = 1.0, progress_bar: bool = False, colors: int = 128, mp4: bool = False, close: bool = True) -> Dict[str, Any]

Draw frame(f) for every f in frames (it returns a matplotlib Figure) and write path (.gif).

check_budget(root: Union[str, Path]) -> list

Files under root over the size budget: PNG over 300 kB, GIF over 2.5 MB. Returns [(path, bytes, limit), ...].

ultrafast.diagram

Deprecated alias of ultrafast.plotting.diagrams.

Moved to :mod:ultrafast.plotting.diagrams. This module keeps the old import path working and warns when it is imported.

(No public functions; see the exported names above.)

ultrafast.system

Sequential and Branched systems, load and save.

Building and loading systems: :class:Sequential and :class:Branched element lists, :func:link, :func:loop, :func:virtual_input, the :func:system builder and :class:System. The classes live in :mod:ultrafast.build (the low-level builders); this package is where to look for them by what they are.

load(source: Any) -> System

Open a system from a .ufs path, JSON text or a dict (same as :meth:System.load).

save(system_dict: Mapping[str, Any], path: Union[str, Path], indent: int = 2) -> Path

Write a system dict (from :func:system) as a .ufs file and return the path.

ultrafast.components

Optical components by kind (CapWords aliases of the builders).

Optical components by kind. components.BeamSplitter is :func:ultrafast.build.beam_splitter: same function, same typed return value, a CapWords name (the snake_case names work here too).

(No public functions; see the exported names above.)

ultrafast.sources

Pulses, beams, measured spectra (CapWords aliases).

Pulses, beams and measured spectra: everything that describes the light entering a system.

(No public functions; see the exported names above.)

ultrafast.instruments

One factory per instrument kind.

Instruments, one factory per kind, plus :func:axis and :func:detector.

EnergyMeter(at: str = 'end', name: Optional[str] = None, **params) -> dict

Pulse energy (or power) through a range. Kind energyMeter; parameters: docs/reference/instruments.md.

Spectrometer(at: str = 'end', name: Optional[str] = None, **params) -> dict

Spectrum on a wavelength axis, with resolution. Kind spectrometer; parameters: docs/reference/instruments.md.

Scope(at: str = 'end', name: Optional[str] = None, **params) -> dict

Photodiode / oscilloscope trace with a finite rise time. Kind scope; parameters: docs/reference/instruments.md.

Autocorrelator(at: str = 'end', name: Optional[str] = None, **params) -> dict

Intensity or interferometric autocorrelation. Kind autocorrelator; parameters: docs/reference/instruments.md.

Frog(at: str = 'end', name: Optional[str] = None, **params) -> dict

Second-harmonic, polarisation-gate or self-diffraction FROG trace. Kind frog; parameters: docs/reference/instruments.md.

XFrog(at: str = 'end', name: Optional[str] = None, **params) -> dict

Cross-correlation FROG with a known reference pulse. Kind xfrog; parameters: docs/reference/instruments.md.

DScan(at: str = 'end', name: Optional[str] = None, **params) -> dict

Dispersion scan: SHG spectrum versus inserted material or GDD. Kind dscan; parameters: docs/reference/instruments.md.

Contrast(at: str = 'end', name: Optional[str] = None, **params) -> dict

Intensity in dB versus time: pre- and post-pulses. Kind contrast; parameters: docs/reference/instruments.md.

Polarimeter(at: str = 'end', name: Optional[str] = None, **params) -> dict

Stokes parameters. Kind polarimeter; parameters: docs/reference/instruments.md.

PulseSummary(at: str = 'end', name: Optional[str] = None, **params) -> dict

Every scalar pulse metric. Kind pulseSummary; parameters: docs/reference/instruments.md.

Compressor(at: str = 'end', name: Optional[str] = None, **params) -> dict

Ideal compressor: the GDD / TOD that compresses best. Kind compressor; parameters: docs/reference/instruments.md.

Conversion(at: str = 'end', name: Optional[str] = None, **params) -> dict

Energy and photon number conversion in an active element. Kind conversion; parameters: docs/reference/instruments.md.

PhaseMatchingCurve(at: str = 'end', name: Optional[str] = None, **params) -> dict

Phase-matching efficiency versus angle, wavelength or temperature. Kind phaseMatchingCurve; parameters: docs/reference/instruments.md.

DelayScan(at: str = 'end', name: Optional[str] = None, **params) -> dict

Conversion versus delay between pump and signal. Kind delayScan; parameters: docs/reference/instruments.md.

BeamProfile(at: str = 'end', name: Optional[str] = None, **params) -> dict

Fluence versus position after an element with a transverse model. Kind beamProfile; parameters: docs/reference/instruments.md.

CrossCorrelator(at: str = 'end', name: Optional[str] = None, **params) -> dict

Third-order cross-correlator (contrast). Kind crossCorrelator; parameters: docs/reference/instruments.md.

Camera(at: str = 'end', name: Optional[str] = None, **params) -> dict

Near-field or far-field camera with a described sensor. Kind camera; parameters: docs/reference/instruments.md.

WavefrontSensor(at: str = 'end', name: Optional[str] = None, **params) -> dict

Shack-Hartmann-like wavefront map and Zernike coefficients (Noll, rms waves). Kind wavefrontSensor; parameters: docs/reference/instruments.md.

ultrafast.algorithms.zernike

Zernike polynomials (Noll), fit and evaluate, in NumPy.

Zernike polynomials in Noll ordering and normalisation, in plain NumPy (no engine needed).

noll_to_nm(j: int) -> Tuple[int, int]

Noll index (1-based) -> radial order n and azimuthal order m (m < 0: sine term).

name(j: int) -> str

A name for the first 11 terms (piston ... spherical); Z<j> for the others.

radial_order_of(j: int) -> int

radial(n: int, m: int, rho: np.ndarray) -> np.ndarray

Radial polynomial R_n^|m|(rho).

value(j: int, rho: np.ndarray, theta: np.ndarray) -> np.ndarray

Noll-normalised Z_j at polar coordinates (rho in units of the pupil radius).

basis(js: Iterable[int], x, y, radius: float, centre: Tuple[float, float] = (0.0, 0.0)) -> np.ndarray

Z_j on a grid, shape (len(js), nx, ny); x, y are the axes (the map is indexed [x][y]).

evaluate_map(coefficients: Sequence[float], x, y, radius: float, centre: Tuple[float, float] = (0.0, 0.0), first: int = 1, outside: float = np.nan) -> np.ndarray

sum_j c_j Z_j on a grid; coefficients[0] belongs to Noll index first. Points outside the pupil get outside.

fit(wavefront: np.ndarray, x, y, radius: float, max_noll: int = 15, centre: Tuple[float, float] = (0.0, 0.0), mask: Optional[np.ndarray] = None, first: int = 1, return_residual: bool = False)

Least-squares Zernike coefficients c[0 .. max_noll - first] of wavefront[x][y] over the disc of radius (points with a non-finite value or mask == False are skipped). Same unit as wavefront. With return_residual=True also returns wavefront - fit on the pupil (NaN outside).

rms(coefficients: Sequence[float], first: int = 1, skip: Sequence[int] = (1,)) -> float

rms of the wavefront from its coefficients (orthonormal basis): sqrt(sum c_j^2), leaving out the Noll indices in skip (piston by default).

strehl_marechal(rms_waves: float) -> float

Marechal estimate exp(-(2 pi sigma)^2) of the Strehl ratio for an rms wavefront error in waves (valid for sigma < ~0.1).

ultrafast.results

Results and curve metrics.

Results and simple metrics: the live :class:Result, a saved results folder (:class:SavedResult, :func:load) and a few curve metrics that need only NumPy.

fwhm(x: Sequence[float], y: Sequence[float]) -> float

Full width at half maximum of a single-peaked curve, with linear interpolation at the two half-maximum crossings.

rms_width(x: Sequence[float], y: Sequence[float]) -> float

sqrt of the second central moment of the weights y along x.

strehl_marechal(rms_waves: float) -> float

Marechal estimate of the Strehl ratio from the rms wavefront error in waves.