Skip to content

Pulse envelopes, grids and trains

Wave/Envelope construction, temporal grids, pulse trains and hygiene helpers. Docstrings are the source of truth, rendered with mkdocstrings (numpydoc style).

photonics_helper.pulse

Pulse envelopes, temporal grids, and pulse trains.

Amplitude conventions

The propagation engines (:class:~photonics_helper.gnlse.SplitStepEngine, :class:~photonics_helper.multimode_gnlse.MultimodeSplitStepEngine) use the power-normalised envelope convention |A|² in watts (γ in W⁻¹m⁻¹). Build such an envelope with :meth:Envelope.from_energy; it sets :attr:Envelope.amplitude_convention to "power".

:meth:Envelope.from_peak_power / :meth:Envelope.from_fwhm_peak_power are the field-unit factories: they invert P = ½·n·c·ε₀·A_eff·|E0|² and mark the envelope "field" (V/m). They must be converted with :meth:Wave.to_engine_units / :meth:Envelope.to_engine_units before an engine sees them; both engines now raise a clear ValueError instead of silently propagating a 13-order-of- magnitude-wrong amplitude.

For a plain :class:Envelope/Wave (raw peak_amplitude), the metrics Wave.envelope_intensity/peak_power/pulse_energy stay in normalized envelope units unless :meth:Wave.with_effective_area attaches an area; in that case they use P = ½·n·c·ε₀·A_eff·|A|² and emit no warning.

FWHM semantics

:meth:Envelope.from_fwhm always takes the intensity FWHM. The library's Gaussian field is family B, A0·exp(−t²/(2T0²)), so T0 = FWHM/1.6654 and E = P0·T0·√π; sech is A0·sech(t/T0), T0 = FWHM/1.7627, E = 2P0·T0. For the Airy shape the API width is the main-lobe FWHM; the oscillating tail is not in L², so from_energy rejects Airy and a whole-field energy has no finite value.

logger module-attribute

logger = logging.getLogger(__name__)

HEADLESS_BACKENDS module-attribute

HEADLESS_BACKENDS: frozenset[str] = frozenset({'agg', 'pdf', 'ps', 'svg', 'pgf', 'template'})

INTERACTIVE_BACKEND_CANDIDATES module-attribute

INTERACTIVE_BACKEND_CANDIDATES: tuple[str, ...] = ('qtagg', 'TkAgg', 'gtk4agg', 'gtk3agg', 'wxagg', 'macosx')

SHAPE_FACTORS module-attribute

SHAPE_FACTORS: dict[str, float] = {'gaussian': 2 * sqrt(log(2)), 'sech': 2 * acosh(sqrt(2)), 'lorentzian': 2 * sqrt(sqrt(2) - 1), 'rectangular': 2.0, 'parabolic': 2 * sqrt(1 - 2 ** -0.5)}

SHAPE_ENERGY_FACTORS module-attribute

SHAPE_ENERGY_FACTORS: dict[str, float] = {'gaussian': sqrt(pi), 'sech': 2.0, 'lorentzian': pi / 2.0, 'rectangular': 2.0, 'triangular': 2.0 / 3.0, 'parabolic': 16.0 / 15.0, 'cosine': 1.0, 'exponential': 1.0}

Envelope

shape instance-attribute

shape: Literal['gaussian', 'sech', 'lorentzian', 'rectangular', 'super-gaussian', 'triangular', 'parabolic', 'cosine', 'exponential', 'gauss-hermite', 'airy', 'custom']

peak_amplitude instance-attribute

peak_amplitude: float

pulse_width instance-attribute

pulse_width: Time

chirp class-attribute instance-attribute

chirp: float = 0.0

amplitude_convention class-attribute instance-attribute

amplitude_convention: Literal['power', 'field'] = 'power'

super_gaussian_order class-attribute instance-attribute

super_gaussian_order: int = 2

beam_waist class-attribute instance-attribute

beam_waist: Time | None = None

hg_mode class-attribute instance-attribute

hg_mode: int = 0

func class-attribute instance-attribute

func: Callable | None = None

phase_func class-attribute instance-attribute

phase_func: Callable | None = None

fwhm property

fwhm: Time

Full width at half maximum of the envelope (s).

from_fwhm classmethod

from_fwhm(shape: Literal['gaussian', 'sech', 'lorentzian', 'rectangular', 'super-gaussian', 'triangular', 'parabolic', 'cosine', 'exponential', 'airy'], peak_amplitude: float, fwhm: Time) -> Self

Construct an Envelope from a desired full-width at half-maximum.

amplitude_from_peak_power staticmethod

amplitude_from_peak_power(peak_power: Power, A_eff: Area, refractive_index: float = 1.0) -> float

Peak amplitude A0 for a target physical peak power.

Inverts P = ½·n·c·ε₀·A_eff·|A0|² (see :class:~photonics_helper.base.PeakPower). Shape-independent: every built-in shape peaks at |A| = A0 (for gauss-hermite with hg_mode > 0 the true maximum exceeds A0 by the Hermite-polynomial factor, so treat the result as the on-axis scale, not the lobe maximum).

measured_width

measured_width(level: float = 0.5) -> Time

Shape-aware width measured on the envelope's own field.

For canonical built-in shapes at half maximum this returns :attr:fwhm (so metadata and measurement cannot disagree). For the Airy shape that is the main-lobe FWHM; the accelerating tail re-crosses the half-max level far out (585 fs vs 200 fs for from_fwhm("airy", …, 200 fs)), and treating the outermost crossings as “the” width is exactly the metadata-vs-measurement bug this method exists to remove. For non-half-max levels, custom or gauss-hermite fields, it falls back to the numerical crossing width of the actual field.

energy_factor

energy_factor() -> float

E = A0²·T0·F shape factor for the whole-field energy.

to_engine_units

to_engine_units(A_eff: Area, refractive_index: float = 1.0) -> Envelope

Convert a field-unit (V/m) envelope to the engine's √W units.

The GNLSE engines use |A|² in watts, while :meth:from_peak_power / :meth:from_fwhm_peak_power build a physical field amplitude A0 with P = ½·n·c·ε₀·A_eff·|A0|². The conversion is A_engine = A_field·√(½·n·c·ε₀·A_eff). Envelopes already in "power" convention are returned unchanged (a copy).

from_energy classmethod

from_energy(shape: Literal['gaussian', 'sech', 'lorentzian', 'rectangular', 'super-gaussian', 'triangular', 'parabolic', 'cosine', 'exponential'], energy: float, fwhm: Time, **kwargs: Any) -> Self

Construct an envelope from pulse energy in the engine units.

Uses E = ∫|A|²dt = A0²·T0·F_shape with |A|² in watts — the convention of :class:~photonics_helper.gnlse.SplitStepEngine and :class:~photonics_helper.multimode_gnlse.MultimodeSplitStepEngine (γ in W⁻¹m⁻¹). This is not the field-unit convention of :meth:from_fwhm_peak_power; an envelope built here can be handed straight to an engine.

fwhm is the intensity FWHM (same semantics as :meth:from_fwhm). super_gaussian_order may be passed in kwargs.

from_peak_power classmethod

from_peak_power(shape: Literal['gaussian', 'sech', 'lorentzian', 'rectangular', 'super-gaussian', 'triangular', 'parabolic', 'cosine', 'exponential', 'gauss-hermite', 'airy'], peak_power: Power, pulse_width: Time, A_eff: Area, refractive_index: float = 1.0, chirp: float = 0.0, **kwargs: Any) -> Self

Construct an Envelope from a physical peak power.

Preferred over passing raw peak_amplitude (V/m): users think in watts, and the A0 conversion needs A_eff and n anyway.

from_fwhm_peak_power classmethod

from_fwhm_peak_power(shape: Literal['gaussian', 'sech', 'lorentzian', 'rectangular', 'super-gaussian', 'triangular', 'cosine', 'exponential', 'airy'], peak_power: Power, fwhm: Time, A_eff: Area, refractive_index: float = 1.0, chirp: float = 0.0, **kwargs: Any) -> Self

Construct an Envelope from FWHM + physical peak power.

field

field(t: NDArray | None = None) -> NDArray

Returns complex envelope A(t).

Parameters:

Name Type Description Default
t NDArray | None

Time array in seconds. If None (default), auto-generates a grid covering ~10× T0 which captures >99% of the pulse energy for all built-in shapes.

None

intensity

intensity(t: NDArray) -> NDArray

Optical intensity |A|² (W).

calc_width

calc_width(level: float = 0.5) -> Time

Calculate the pulse width using linear interpolation at crossing points.

Finds the width between the widest pair of crossings where the intensity envelope drops to level * peak_intensity.

Parameters:

Name Type Description Default
level float — fraction of peak to calculate width at.

0.5 gives FWHM, 1/e ≈ 0.368, 1/e² ≈ 0.135. Default 0.5.

0.5

Returns:

Name Type Description
width Time — pulse width in seconds (use ``.as_ps`` etc. for display units).

apply_dispersion

apply_dispersion(GDD: float = 0.0, TOD: float = 0.0, FOD: float = 0.0, N: int = 2 ** 12) -> Envelope

Apply group-delay dispersion (GDD), TOD, FOD in the frequency domain.

Multiplies the spectral amplitude by exp(−i·φ(ω)) where φ(ω) = ½·GDD·Ω² + ⅙·TOD·Ω³ + ¹⁄₂₄·FOD·Ω⁴ and Ω is the offset from the central angular frequency. Uses the same sign as :meth:~photonics_helper.gnlse.SplitStepEngine._linear_step.

Parameters:

Name Type Description Default
GDD float — group-delay dispersion (ps²). Default 0.
0.0
TOD float — third-order dispersion (ps³). Default 0.
0.0
FOD float — fourth-order dispersion (ps⁴). Default 0.
0.0
N int — number of points for the internal grid (default 2¹²).
2 ** 12

Returns:

Type Description
Envelope — a new Envelope with the dispersion-applied field.
Notes

The returned envelope has shape="custom" and owns the numerical field computed on an internal grid sized to contain the broadened pulse (estimated from the input bandwidth and the requested GDD, TOD, FOD; N controls the sampling resolution). Requests outside that window are clamped to the edge values. The analytic parameters of the input envelope no longer describe the broadened pulse, so peak_amplitude and pulse_width are re-measured numerically and the chirp is reset to zero (any input chirp is already baked into the dispersed field).

visualize_2d

visualize_2d(backend: Literal['plotly', 'matplotlib'] = 'plotly', N: int = 2 ** 12, show_phase: bool = True, show_fwhm: bool = True, figsize: tuple[float, float] | None = None, title: str | None = None, theme: Literal['light', 'dark'] = 'light')

Plot temporal intensity, spectral intensity, and phase.

Parameters:

Name Type Description Default
backend "plotly" or "matplotlib" (default "plotly")
'plotly'
N number of time points (default 2^12)
2 ** 12
show_phase show instantaneous phase overlay (default True)
True
show_fwhm show FWHM markers (default True)
True
figsize figure size for matplotlib backend (default None)
None
title optional title override (default uses shape name)
None
theme "light" or "dark" (default "light")
'light'

visualize_3d

visualize_3d(N: int = 2 ** 12, title: str | None = None, theme: Literal['light', 'dark'] = 'light')

Plot 3D spectrogram (time vs frequency vs intensity).

Shows how the frequency content evolves over time. Useful for visualizing chirp and time-frequency structure.

Parameters:

Name Type Description Default
N number of time points (default 2^12)
2 ** 12
title optional title override
None
theme "light" or "dark" (default "light")
'light'

from_parabolic_asymptotic classmethod

from_parabolic_asymptotic(peak_amplitude: float, pulse_width: Time, gain: float, length: float, chirp: float = 0.0) -> Self

Construct a parabolic pulse with asymptotic amplifier chirp.

The chirp coefficient follows the asymptotic parabolic solution: α ≈ 0.2726 × z × gain.

Parameters:

Name Type Description Default
peak_amplitude A₀
required
pulse_width T₀
required
gain Small-signal gain coefficient (unitless or per-length as used in the amplifier model)
required
length Propagation length in the amplifier
required
chirp Additional chirp on top of the asymptotic value (default 0)
0.0

ElectricField

Physical electric field as a complex analytic signal (V/m).

:attr:field stores the complex analytic samples — the physical field is np.real(field). For an envelope A(t) reconstructed around a carrier ω₀ the intensity follows the standard relation I = ½·n·c·ε₀·|E|² with the background :attr:refractive_index.

The class is deliberately a thin unit-bearing value object over a :class:TemporalGrid: no plotting, no solver state, and no FFT-backend choices live here (axes and transforms come from the grid). The carrier convention is single-sourced in :meth:from_envelope — E(t) = A(t)·e^{−iω₀t} with the analysis kernel of :meth:TemporalGrid.fft — so the library's carrier/sign conventions only need auditing in one place.

Parameters:

Name Type Description Default
field complex 1-D array (V/m analytic samples)
required
grid :class:`TemporalGrid` — time axis + FFT convention
required
central_frequency :class:`~photonics_helper.base.AngularFrequency` —

carrier ω₀ used in :meth:from_envelope / :meth:to_envelope

required
refractive_index background n for the intensity–power conversions
required

field instance-attribute

field: NDArray

grid instance-attribute

grid: TemporalGrid

central_frequency instance-attribute

central_frequency: AngularFrequency

refractive_index class-attribute instance-attribute

refractive_index: float = 1.0

real_field property

real_field: NDArray

Physical field samples Re[E(t)] in V/m.

intensity property

intensity: NDArray

Instantaneous intensity ½·n·c·ε₀·|E|² in W/m² (single-sourced scale).

intensity_scale property

intensity_scale: float

½·n·c·ε₀ — the only place the |E|²→W/m² factor is defined.

spectrum cached property

spectrum: NDArray

Spectral field Ê(Ω) from the grid's FFT convention (Parseval-holding).

spectral_intensity property

spectral_intensity: NDArray

from_array classmethod

from_array(A: NDArray, grid: TemporalGrid, central_wavelength: Wavelength, refractive_index: float = 1.0) -> ElectricField

Reconstruct the field from raw complex envelope samples A(t).

The single authoritative carrier reconstruction of the library: E(t) = A(t)·e^{−iω₀t} where ω₀ = 2πc/λ₀. Note A carries the physical scale directly (V/m when used with intensity ½·n·c·ε₀·|A|²), i.e. it is the analytic envelope, not a normalized shape (see :class:Envelope for the normalized one).

Parameters:

Name Type Description Default
A complex 1-D envelope samples on ``grid.t``
required
grid the temporal grid ``A`` is sampled on
required
central_wavelength carrier wavelength λ₀
required
refractive_index background n (stored for later conversions)
1.0

from_envelope classmethod

from_envelope(envelope: Envelope | NDArray, grid: TemporalGrid, central_wavelength: Wavelength, refractive_index: float = 1.0) -> ElectricField

Reconstruct the field from an :class:Envelope (or raw samples).

Preferred form takes an Envelope and samples it on grid.t::

field = ElectricField.from_envelope(env, grid, Wavelength(1550, "nm"))

Passing a raw NDArray still works (deprecated — use :meth:from_array instead) so existing call sites keep running.

to_envelope

to_envelope() -> NDArray

Analytic-signal extraction back to the envelope A(t).

Inverse of :meth:from_envelope for fields constructed around a carrier: pulls the slow envelope out of E(t) by multiplying with the conjugate carrier and low-pass filtering over one carrier period. For HiREP-style windows whose sampling resolves the carrier, the roundtrip preserves amplitude and phase up to floating-point noise.

power

power(A_eff: Area) -> NDArray

Sampled power P(t) = I(t)·A_eff in watts.

A_eff is required (and positional): power is meaningless without a mode area, and needing it explicitly prevents the silently-scaling footgun the legacy Wave.metrics warned about.

peak_power

peak_power(A_eff: Area) -> float

Peak power in watts (max of :meth:power).

pulse_energy

pulse_energy(A_eff: Area) -> float

Pulse energy ∫P(t)dt in joules (trapezoidal integration).

instantaneous_phase

instantaneous_phase() -> NDArray

Unwrapped phase of the analytic field (rad).

Wave

grid instance-attribute

grid: TemporalGrid

envelope instance-attribute

envelope: Envelope

central_wavelength instance-attribute

central_wavelength: Wavelength

refractive_index class-attribute instance-attribute

refractive_index: float = 1.0

repetition_rate class-attribute instance-attribute

repetition_rate: Frequency | None = None

central_frequency cached property

central_frequency: float

Carrier angular frequency at the central wavelength (rad/s).

amplitude_convention property

amplitude_convention: Literal['power', 'field']

Amplitude scale of :attr:envelope (see :class:Envelope).

wavelength_nm property

wavelength_nm: WavelengthArray

Absolute wavelength grid (nm) for each frequency sample on grid.w.

Built through the base-unit conversions (carrier offset from the central wavelength → :class:AngularFrequencyArray → to_wl) instead of hand-rolled 2π·c/ω arithmetic, so the returned object carries its own unit handling (.as_nm, .as_m, to_freq()).

electric_field property

electric_field

Physical electric field (V/m) reconstructed from the envelope.

envelope_intensity property

envelope_intensity

Intensity of the envelope |A|² (W).

envelope_field property

envelope_field

Complex envelope field (√W).

spectrum cached property

spectrum: NDArray

Frequency-domain envelope obtained via the configured FFT backend.

instantaneous_intensity

instantaneous_intensity()

Instantaneous intensity in physical units (W).

pulse_energy

pulse_energy() -> float

Pulse energy (or normalized integral ∫|A|²dt).

Returns:

Type Description
float

Joules when an effective mode area has been attached with :meth:with_effective_area; otherwise the normalized integral ∫|A|²dt in field-units²·seconds and a one-time :class:UserWarning is emitted.

calc_width

calc_width(level: float = 0.5) -> Time

Calculate the pulse width using linear interpolation at crossing points.

Finds the width between the widest pair of crossings where the intensity envelope drops to level * peak_intensity.

Parameters:

Name Type Description Default
level float — fraction of peak to calculate width at.

0.5 gives FWHM, 1/e ≈ 0.368, 1/e² ≈ 0.135. Default 0.5.

0.5

Returns:

Name Type Description
width Time — pulse width in seconds (use ``.as_ps`` etc. for display units).
For a canonical built-in shape at half maximum this defers to
attr:`Envelope.fwhm` (and therefore to the shape-aware
meth:`Envelope.measured_width`), so metadata and measurement agree —
including the Airy main-lobe definition. An overridden
``_pulse_train_field`` or a custom/gauss-hermite shape still uses the
numerical crossings of the actual field.

to_engine_units

to_engine_units(A_eff: Area | None = None) -> Wave

Convert a field-unit wave (V/m) to the engine's √W convention.

from_peak_power / from_fwhm_peak_power produce field-unit envelopes; the GNLSE engines use |A|² in watts. This converts with A_eff (the attached area or the argument) and refractive_index. A wave already in "power" convention is returned unchanged. The returned wave has no attached effective area (the conversion replaces it).

peak_power

peak_power() -> float

Peak power (or normalized peak intensity max|A|²).

Returns:

Type Description
float

Watts when an effective mode area has been attached with :meth:with_effective_area (using P = ½·n·c·ε₀·A_eff·|A|²); otherwise max|A|² in normalized envelope units and a one-time :class:UserWarning is emitted.

**Unit hazard:** the return value changes by many orders of
magnitude depending on whether ``A_eff`` is attached. For a field
built as ``sqrt(5.0)``, ``peak_power()`` returns ``5.0`` without an
effective area and ``5.3e-13`` with one — the same field, 13 orders
of magnitude apart. ``add_ase_noise`` defaults ``reference_power``
to ``wave.peak_power()``, so passing a wave with an effective area
to one without silently changes the ASE level by 13 orders of
magnitude. Always check which convention you are in before using
the result.

with_effective_area

with_effective_area(A_eff: Area) -> Self

Return a copy of this Wave bound to a physical mode area.

Once an effective area is attached, :meth:peak_power and :meth:pulse_energy return physical watts and joules via the intensity relation P = ½·n·c·ε₀·A_eff·|A|² (with :attr:refractive_index as n). Without one they stay in normalized envelope units.

Parameters:

Name Type Description Default
A_eff Area — effective mode area (e.g. ``Area(80, "um^2")``).
required

Returns:

Type Description
Wave — a copy sharing this wave's field with the area attached.

average_power

average_power(repetition_rate: Frequency | None = None) -> float

Average power = pulse energy × repetition_rate.

Parameters:

Name Type Description Default
repetition_rate Frequency | None — pulse repetition rate. When

omitted, falls back to the wave's stored repetition_rate (set by :meth:from_pulse_train); single-pulse waves built with :meth:from_envelope must pass one explicitly.

None

from_envelope classmethod

from_envelope(envelope: Envelope, central_wavelength: Wavelength, grid: TemporalGrid | None = None, N: int = 2 ** 12, refractive_index: float = 1.0, repetition_rate: Frequency | None = None) -> Self

Construct a single-pulse Wave from an envelope.

Parameters:

Name Type Description Default
envelope the single-pulse envelope shape
required
central_wavelength carrier wavelength λ₀
required
grid explicit :class:`TemporalGrid`. When ``None`` (default) it is

built automatically via envelope._make_grid(N) (≈10× T0 window), so callers never need to think about sampling.

None
N samples for the auto-built grid (default 2¹²).
2 ** 12
refractive_index background n (default 1.0).
1.0
repetition_rate optional repetition rate for later

:meth:average_power convenience.

None

from_pulse_train classmethod

from_pulse_train(envelope: Envelope, central_wavelength: Wavelength, grid: TemporalGrid | None = None, repetition_rate: Frequency | None = None, n_pulses: int = 10, refractive_index: float = 1.0, N: int = 2 ** 12) -> Self

Construct a pulse train Wave from a single-envelope shape.

grid is optional: when omitted it is built automatically with :meth:TemporalGrid.for_pulse_train (multi-pulse) or envelope._make_grid (single pulse, n_pulses == 1 without a repetition rate). repetition_rate is optional for a single pulse and required for n_pulses > 1.

Parameters:

Name Type Description Default
envelope The single-pulse envelope shape to repeat
required
central_wavelength Central wavelength of the carrier
required
grid TemporalGrid covering the full window (all pulses + padding).

None → auto-built (recommended).

None
repetition_rate Frequency | None — spacing between consecutive

pulses (None allowed only for n_pulses == 1).

None
n_pulses number of pulses (default 10)
10
refractive_index background refractive index (default 1.0)
1.0
N samples for the auto-built grid (default 2¹²).
2 ** 12

with_field

with_field(field: NDArray) -> Self

Return this Wave with an explicit envelope-field override.

Used by :meth:from_pulse_train for precomputed multi-pulse fields. Mutates and returns self (so both w.with_field(f) and w = w.with_field(f) work).

time_bandwidth_product

time_bandwidth_product() -> float

RMS time-bandwidth product. ≈0.707 for transform-limited Gaussian.

visualize

visualize(t_unit: str = 's', w_unit: str = 'rad/s', t_scale: float = 1.0, w_scale: float = 1.0, show_electric_field: bool = False, show_phase: bool = True, show_spectrogram: bool = False, figsize: tuple[float, float] | None = None, save_path: str | None = None)

Plot a comprehensive overview of the pulse.

Parameters:

Name Type Description Default
t_unit label for the time axis (e.g. "ps", "fs")
's'
w_unit label for the frequency axis (e.g. "THz", "rad/ps")
'rad/s'
t_scale multiply grid.t by this before plotting (e.g. 1e12 for ps)
1.0
w_scale multiply grid.w by this before plotting
1.0
show_electric_field add a panel with the real electric field
False
show_phase overlay instantaneous phase on the temporal panel
True
show_spectrogram add a spectrogram (STFT) panel
False
figsize passed to plt.figure()
None
save_path if given, save figure to this path
None

FROGTrace

Represents a FROG trace I(ω, τ).

Attributes:

Name Type Description
trace 2D array of shape (N_omega, N_tau)

The FROG trace (normalized if normalize=True in from_field).

unnormalized_trace 2D array of shape (N_omega, N_tau)

The raw trace before normalization (used for retrieval).

omega :class:`~photonics_helper.base.AngularFrequencyArray`

Angular frequency axis (rad/s), centered at 0.

tau NDArray

Delay axis in seconds, centered at 0 (kept as a raw array; there is no scalar Time-per-element class in :mod:base for arrays).

dt :class:`~photonics_helper.base.Time` — time step.
dw :class:`~photonics_helper.base.AngularFrequency` — angular frequency step.
field 1-D complex NDArray — reconstructed field E(t) (raw array on

purpose: :class:~photonics_helper.structured.StructuredField is a 2-D spatial (x, y) object and does not fit a 1-D time trace).

field reconstructed field E(t) (set after retrieval).

trace instance-attribute

trace: NDArray

unnormalized_trace instance-attribute

unnormalized_trace: NDArray

omega instance-attribute

omega: AngularFrequencyArray

tau instance-attribute

tau: NDArray

dt instance-attribute

dt: Time

dw instance-attribute

dw: AngularFrequency

field class-attribute instance-attribute

field: NDArray | None = None

from_field classmethod

from_field(E_field: NDArray, dt: Time | float, normalize: bool = True) -> FROGTrace

Generate a FROG trace from a complex electric field E(t).

Parameters:

Name Type Description Default
E_field complex 1D array, the electric field on a uniform time grid.
required
dt :class:`~photonics_helper.base.Time` time step. A plain float is

accepted as seconds for backwards compatibility.

required
normalize normalize trace to [0, 1] (default True).
True

Returns:

Type Description
FROGTrace

visualize

visualize(retrieved: FROGTrace | None = None, figsize: tuple[float, float] | None = None, save_path: str | None = None)

Plot the FROG trace and optionally the retrieved pulse.

Parameters:

Name Type Description Default
retrieved optional FROGTrace with .field set (from retrieve()).
None
figsize figure size.
None
save_path if given, save figure to this path.
None

generate_trace

generate_trace(E_field: NDArray, dt: Time | float, normalize: bool = True) -> FROGTrace

Generate a SHG-FROG trace from an electric field.

Parameters:

Name Type Description Default
E_field complex 1D array, electric field on uniform time grid.
required
dt :class:`~photonics_helper.base.Time` time step (plain float = seconds).
required
normalize normalize trace to [0, 1] (default True).
True

Returns:

Type Description
FROGTrace

fidelity

fidelity(trace1: FROGTrace, trace2: FROGTrace) -> float

Compute FROG fidelity between two traces.

fidelity = 1 - ||I1 - I2|| / ||I1||

Returns:

Type Description
float in [0, 1], where 1 = perfect match.

retrieve

retrieve(trace: FROGTrace, max_iter: int = 100, tol: float = 0.0001, verbose: bool = True, *, seed: int | None = 0, n_restarts: int = 5) -> FROGTrace

Retrieve the electric field E(t) from a FROG trace using PCGPA.

Implements the generalized-projections / PCGPA material-constraint step: after replacing the trace magnitude with the measurement (keeping the phase), the new field is the least-squares solution

E_new(t) = Σ_τ G'(t, τ)·E*(t+τ) / Σ_τ |E(t+τ)|²

for the bilinear SHG signal G(t, τ) = E(t)E(t+τ). Retrieval is initialized from the dominant SVD component of the trace plus one or more random complex fields (seeded for reproducibility); the lowest-error result is returned.

Parameters:

Name Type Description Default
trace FROGTrace — the measured (or generated) trace.
required
max_iter maximum iterations per restart (default 100).
100
tol convergence tolerance on the change in the normalized FROG error

(default 1e-4).

0.0001
verbose print iteration progress (default True).
True
seed RNG seed for the random initialization (default 0). ``None`` uses

fresh entropy.

0
n_restarts number of random restarts (default 5). Together with the

SVD initialization these are ranked by FROG error and the lowest-error result is returned.

5

Returns:

Type Description
FROGTrace with ``.field`` set to the retrieved E(t).
Notes

SHG-FROG cannot distinguish E(t) from E*(−t) or a global phase, so compare retrieved and reference fields up to those symmetries (comparing traces is ambiguity-free).