Plotting#
Matplotlib-based plotters with no global pyplot state, so they embed cleanly in
the GUI and in your own figures. Reusable single-axis plotters plus the 12-, 6-
and 4-panel composites. See Post-processing and plotting.
Matplotlib plotting for retrieval results.
Provides custom colormaps (white at the low end; a red band for negatives),
reusable single-axis plotters (so the GUI embeds exactly the same code), and
composite figures: the 12-panel plot_retrieval(), the 6-panel
plot_frog_filter(), and plot_simulated_trace().
The retrieval summary is assembled from twelve independent panels
(draw_<key>(ax, data) over one RetrievalPlotData bundle, registered in
RETRIEVAL_PANELS). plot_retrieval() lays them out as the 3×4
overview; plot_retrieval_page() draws one of the three 2×2 pages
(RETRIEVAL_PAGES: Traces, Pulse, Diagnostics), as the GUI’s Analyse
pages show them.
Figures are built with matplotlib.figure.Figure directly
(no pyplot global state), so they embed cleanly in a Qt canvas and also save
standalone via fig.savefig(...).
Every public name is importable from croak.plotting itself; the submodules
group them by domain:
unitsDisplay units and read-out formatting (
sig3(),si_power()).tracesFROG-trace images: colormaps,
signed_pcolormesh(), the residual and marginal plotters,plot_frog_filter()andplot_simulated_trace().pulseThe retrieved pulse:
plot_temporal(),plot_spectral()andplot_spectrogram().artistsThe artist bundles each panel returns (
TraceArtists, …).panelsRetrievalPlotDataand the twelvedraw_<key>panels.retrievalThe panel registry, pages and overview,
plot_retrieval_page()andplot_retrieval().uncertaintyBootstrap and substrate-thickness uncertainty figures.
figureThe figure set-up the composites share.
screenWhat the GUI’s interactive views show, as plain data (
croak.plotting.screen).exportThose views drawn as publication figures, for the GUI’s “Export … as a figure” (
croak.plotting.export).displayThose views on the spectral axis (wavelength or frequency, with the density Jacobian) and logarithmic range the viewer chose (
croak.plotting.display).
- croak.plotting.cmap_white(base='viridis', *, n=8, white=True, N=512)[source]#
Build a base colormap with (optionally) a white point at the low end.
- Parameters:
base (str)
n (int)
white (bool)
N (int)
- croak.plotting.cmap_negwhite(base='viridis', *, n=8, white=True, negfrac=0.0, N=512)[source]#
Like
cmap_white()but with a red gradient for negative values.- Parameters:
base (str)
n (int)
white (bool)
negfrac (float)
N (int)
- croak.plotting.signed_pcolormesh(ax, x, y, C, *, db, tracedb=30.0, cmap_pos, vmax=None)[source]#
Pcolormesh that splits an image’s sign onto two colormaps.
Positive samples are drawn with
cmap_pos(e.g. viridis); negative samples are drawn by magnitude with a white→red map. Both maps share the same scale ([0, vmax]linear,[-tracedb, 0]dB), so a negative is only as saturated as a positive of equal magnitude — small negatives stay faint instead of dominating — and zero is white in both (paircmap_poswithcmap_white()).Cfollows the usualpcolormesh()convention — shape(len(y), len(x))(a FROG(Nλ, Nτ)array already has this shape for x = delay and y = wavelength).Returns
(mappable_pos, mappable_neg)(the second isNonewhen there are no negative samples).
- croak.plotting.si_power(watts)[source]#
Return
(scale, unit)to displaywattswith an SI power prefix.Picks the largest prefix not exceeding
|watts|(so e.g.1.2e7W →(1e6, "MW")). Non-finite or non-positive inputs fall back to plain watts; values below the smallest prefix use that smallest prefix.- Parameters:
watts (float)
- Return type:
tuple[float, str]
- croak.plotting.sig3(value)[source]#
Format a number to three significant digits, for a read-out.
Three significant digits keeps a read-out equally informative across the ranges croak covers (sub-fs attosecond pulses through hundreds of fs; nanometre-wide through hundred-nanometre-wide spectra), where a fixed number of decimals is too coarse at one end and spuriously precise at the other. Unlike the
gformat this keeps trailing zeros (so7.00, not7) and never switches to exponent notation, both of which read badly beside a sibling entry in a legend or a table column.- Parameters:
value (float) – The number to format, already in its display unit.
- Returns:
str – The formatted number, with no unit attached.
- Return type:
str
Examples
>>> sig3(9.512), sig3(7.0), sig3(0.85), sig3(953.2) ('9.51', '7.00', '0.850', '953')
- croak.plotting.plot_residual(ax, omega, delays, resid, omega0, *, halfwidth=None, flim=None)[source]#
Plot the measured−retrieved residual with a symmetric blue-white-red map.
flimoptionally bounds the frequency axis, as(f_min, f_max)in Hz.
- croak.plotting.plot_temporal(ax, pr, *, halfwidth=None, power_scale=None, truth=None)[source]#
Temporal intensity/power (left) and phase (right twin axis); phase masked.
When
pr.peak_poweris set (a measured pulse energy was supplied toprocess_result()), the intensity is shown as absolute instantaneous power on an SI-prefixed axis; otherwise it stays normalised (“a.u.”).power_scaleis an optional(scale, unit)pair (seesi_power()) so several panels can share one prefix; whenNoneit is derived from the larger of the retrieved/TL peak powers.truth(aTruthPulse: a synthetic generating field, or a simulated scan’s reference intensity) is overlaid as a thin black line under the retrieved/TL curves, labelled with its own FWHM, and — when it carries a temporal phase — as a dotted phase in the same display gauge as the retrieved one (seecroak.processing.normalize_temporal_phase()).Returns the twin phase axes.
draw_temporal()is the same panel for the registry, returning every artist (TemporalArtists).- Parameters:
pr (ProcessedResult)
truth (TruthPulse | None)
- croak.plotting.plot_spectral(ax, pr, *, lam_min=None, lam_max=None, truth=None, axis='frequency')[source]#
Spectral intensity (left) and phase (right twin axis) against
axis.axisis"frequency"(PHz, the default: the space the retrieval works in, where|E(ω)|²of a symmetric pulse is symmetric) or"wavelength"(nm, the spectrometer’s axis, carrying the 1/λ² density Jacobian). Both spectra are drawn as unit-peak densities in the chosen variable;lam_min/lam_max(m) bound the axis on either. The phase curves are the same on both.truth, when it carries a spectrum, is overlaid as a thin black line under the retrieved curve; when it carries a known spectral phase, that phase is overlaid on the phase axis. It is drawn in the SAME gauge as the retrieved phase (unwrapped, de-tilted, zeroed at the spectral peak — seecroak.processing.normalize_spectral_phase()), because spectral phase is defined only up to a constant and a linear term; a truth pinned any other way would show a tilt or offset that is gauge, not error.Returns the twin phase axes.
draw_spectral()is the same panel for the registry, returning every artist (SpectralArtists).- Parameters:
pr (ProcessedResult)
truth (TruthPulse | None)
axis (SpectralAxis)
- croak.plotting.SPECTRAL_AXES: tuple[str, ...] = ('frequency', 'wavelength')#
Abscissae the spectrum panel can be drawn against (see
plot_spectral()).
- croak.plotting.EDGE_ENERGY_WARN = 0.01#
Edge-energy fraction (see
croak.processing.edge_energy_fraction()) above which the spectrum panel flags the retrieval in red. A sound retrieval on a generous band sits two orders of magnitude below this; above it, re-run on a wider grid.
- croak.plotting.plot_convergence(ax, errors, *, boundaries=())[source]#
Plot the FROG error vs iteration on a log y-axis.
boundariesare indices intoerrorswhere a multi-stage solver handed over to its next stage (stage_boundaries); each is drawn as a dashed rule. Marking them matters because the stages need not count the same unit of work —warm-lbfgssplices COPRA iterations onto L-BFGS function evaluations — so an unmarked kink would read as convergence behaviour rather than as the change of algorithm it is.The error curve is created even for an empty
errors(a result restored from file carries no history), so a live view can grow it in place.- Parameters:
errors (ArrayLike)
boundaries (Sequence[int])
- Return type:
- croak.plotting.plot_marginal(ax, x, retrieved, measured=None, *, xlabel='', scale=1.0, halfwidth=None)[source]#
Plot a (retrieved vs measured) trace marginal.
- Return type:
- croak.plotting.plot_spectrogram(ax, t_centers, wavelength, S, *, lam_min=None, lam_max=None, halfwidth=None, cmap=None)[source]#
Plot a Gabor spectrogram (time fs × wavelength nm).
- croak.plotting.plot_retrieval(result, *, measured=None, Iomega_meas=None, lam_min=None, lam_max=None, flim=None, tracedb=30.0, cmap='viridis', truth=None, energy=None, figsize=(17.0, 9.45), fig=None, processed=None, spectral_axis='frequency')[source]#
12-panel retrieval summary: the standard at-a-glance quality check.
The panels are
RETRIEVAL_PANELSin theRETRIEVAL_OVERVIEWlayout — measured/retrieved traces (log and linear) on the left, the pulse, spectrum and marginals on the right, convergence, residual, spectral filter and spectrogram along the bottom.plot_retrieval_page()draws a subset.lam_min/lam_max(m) bound the wavelength axes — the spectrum and spectrogram panels.flimbounds the frequency axis of the trace and residual panels, as(f_min, f_max)in Hz; the default shows the whole retrieval grid. The two are separate because the trace sits at the signal frequency, which for SHG is twice the pulse’s. Reach forflimwhen the retrieval grid is much wider than the signal — typical when retrieving directly on a synthesis grid rather than on one cropped byload_and_clean()— where the trace would otherwise be a thin stripe in a mostly empty axis.energyis an optional measured pulse energy (J); when given, the temporal panel is shown in absolute power (seeprocess_result()).processedis an optional, already-computedProcessedResultfor this same result: pass it when the caller needs the processed quantities too (the GUI shows them in a table beside the figure) so they are not derived twice. It must have been built with the samemeasured/Iomega_meas/energy, which are then used only for the trace panels; a mismatched one raisesValueError.spectral_axisdraws the spectrum panel against"frequency"(PHz, the default) or"wavelength"(nm); seeplot_spectral().- Raises:
ValueError – If
resultcarries no trace, orprocessedbelongs to another result.- Parameters:
result (RetrievalResult)
measured (ArrayLike | None)
Iomega_meas (ArrayLike | None)
lam_min (float | None)
lam_max (float | None)
flim (tuple[float, float] | None)
tracedb (float)
cmap (str)
truth (TruthPulse | None)
energy (float | None)
fig (Figure | None)
processed (ProcessedResult | None)
spectral_axis (SpectralAxis)
- Return type:
Figure
- class croak.plotting.RetrievalPlotData(result, processed, measured, retrieved, omega0_trace, halfwidth, lam_min, lam_max, flim, tracedb, cmap_pos, lin_vmax, truth, power_scale, spectral_axis)[source]#
Bases:
objectEverything the retrieval panels share, computed once from one result.
Build it with
retrieval_plot_data(). The bundle is immutable and carries no figure state, so one instance can feed several figures (the GUI’s pages and their pop-outs) and be redrawn at any size.- Parameters:
result (RetrievalResult)
processed (ProcessedResult)
measured (NDArray[np.float64])
retrieved (NDArray[np.float64])
omega0_trace (float)
halfwidth (float)
lam_min (float)
lam_max (float)
flim (tuple[float, float] | None)
tracedb (float)
cmap_pos (Colormap)
lin_vmax (float)
truth (TruthPulse | None)
power_scale (tuple[float, str] | None)
spectral_axis (str)
- result#
The retrieval;
result.traceis the retrieved trace.- Type:
- processed#
Display-ready quantities of
result(croak.processing.process_result()).- Type:
- measured, retrieved
Measured and retrieved traces, shape
(Nω, Nτ).- Type:
ndarray
- omega0_trace#
Centre angular frequency of the signal (twice
omega0for SHG), so the trace panels’ frequency axis reads at the signal frequency.- Type:
float
- halfwidth#
Half the delay span (s); bounds the delay axes.
- Type:
float
- lam_min, lam_max
Wavelength bounds (m) of the spectrum and spectrogram panels.
- Type:
float
- flim#
Optional
(f_min, f_max)(Hz) bounds of the trace/residual frequency axes.- Type:
tuple of float or None
- tracedb#
Dynamic range (dB) of the logarithmic trace panels.
- Type:
float
- cmap_pos#
White-based positive colormap shared by the trace and spectrogram panels.
- Type:
Colormap
- lin_vmax#
Common scale of the linear trace pair, so their colorbar is meaningful.
- Type:
float
- truth#
Known pulse to overlay (synthetic and simulated data).
- Type:
TruthPulse or None
- power_scale#
SI
(scale, unit)for absolute power when a pulse energy was given.- Type:
tuple of (float, str) or None
- spectral_axis#
"frequency"or"wavelength": the spectrum panel’s abscissa.- Type:
str
- property spectrogram: tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]][source]#
(t_centres, wavelength, S)ofcroak.processing.spectrogram().The Gabor transform is the costliest thing the panels compute (hundreds of FFTs), so it runs only when the spectrogram panel is first drawn and is then cached on the bundle for every later draw of it.
- croak.plotting.retrieval_plot_data(result, *, measured=None, Iomega_meas=None, lam_min=None, lam_max=None, flim=None, tracedb=30.0, cmap='viridis', truth=None, energy=None, processed=None, spectral_axis='frequency')[source]#
Bundle a retrieval’s plot inputs for the panels (see
plot_retrieval()).The arguments are those of
plot_retrieval(), which is this bundle drawn as the overview; see there for their meaning.processedis an already-computedProcessedResultfor this same result (the GUI computes it once for its read-out); it must have been built with the samemeasured/Iomega_meas/energy.- Raises:
ValueError – If
resultcarries no trace,processedbelongs to another result, orspectral_axisis not one ofSPECTRAL_AXES.- Parameters:
result (RetrievalResult)
measured (ArrayLike | None)
Iomega_meas (ArrayLike | None)
lam_min (float | None)
lam_max (float | None)
flim (tuple[float, float] | None)
tracedb (float)
cmap (str)
truth (TruthPulse | None)
energy (float | None)
processed (ProcessedResult | None)
spectral_axis (str)
- Return type:
- class croak.plotting.TraceArtists(mesh_pos, mesh_neg, label=None)[source]#
Bases:
objectArtists of a trace-image panel.
- Parameters:
mesh_pos (QuadMesh)
mesh_neg (QuadMesh | None)
label (Text | None)
- mesh_pos, mesh_neg
The positive-sample image and, when the data hold negatives, the white→red magnitude image of the negative samples (else
None).- Type:
QuadMesh
- label#
The bold error/shape annotation of the retrieved-linear panel.
- Type:
Text or None
- class croak.plotting.ResidualArtists(mesh)[source]#
Bases:
objectArtists of the residual panel: its signed image (
Noneif no residual).- Parameters:
mesh (QuadMesh | None)
- class croak.plotting.TemporalArtists(line_retr, line_tl, line_phase, ax_phase, legend, legend_retr, legend_tl, line_truth=None, line_truth_phase=None)[source]#
Bases:
objectArtists of the temporal panel.
- Parameters:
line_retr (Line2D)
line_tl (Line2D)
line_phase (Line2D)
ax_phase (Axes)
legend (Legend)
legend_retr (Text)
legend_tl (Text)
line_truth (Line2D | None)
line_truth_phase (Line2D | None)
- line_retr, line_tl
Retrieved and transform-limited intensity (or power) curves.
- Type:
Line2D
- line_phase#
Retrieved temporal phase on the twin axis
ax_phase.- Type:
Line2D
- ax_phase#
The right-hand phase axis.
- Type:
Axes
- legend#
The combined intensity + phase legend.
- Type:
Legend
- legend_retr, legend_tl
The legend entries carrying the R and TL durations (they change with the result, so a live update rewrites them in place).
- Type:
Text
- line_truth, line_truth_phase
Ground-truth intensity and phase overlays, when a truth was given.
- Type:
Line2D or None
- class croak.plotting.SpectralArtists(line_retr, line_phase, line_phase_fit, ax_phase, legend, text_dispersion, text_edge, line_meas=None, line_truth=None, line_truth_phase=None)[source]#
Bases:
objectArtists of the spectrum panel.
- Parameters:
line_retr (Line2D)
line_phase (Line2D)
line_phase_fit (Line2D)
ax_phase (Axes)
legend (Legend)
text_dispersion (Text)
text_edge (Text)
line_meas (Line2D | None)
line_truth (Line2D | None)
line_truth_phase (Line2D | None)
- line_retr#
Retrieved spectral intensity.
- Type:
Line2D
- line_phase, line_phase_fit
Retrieved spectral phase and its dashed polynomial fit, on
ax_phase.- Type:
Line2D
- ax_phase#
The right-hand phase axis.
- Type:
Axes
- legend#
The combined intensity + phase legend.
- Type:
Legend
- text_dispersion, text_edge
The GDD/TOD block and the edge-energy warning.
- Type:
Text
- line_meas, line_truth, line_truth_phase
Measured spectrum, truth spectrum and truth phase, when available.
- Type:
Line2D or None
- class croak.plotting.ConvergenceArtists(line, boundaries=(), legend=None)[source]#
Bases:
objectArtists of the convergence panel: the error curve, stage rules, legend.
- Parameters:
line (Line2D)
boundaries (tuple[Line2D, ...])
legend (Legend | None)
- class croak.plotting.LineArtists(line)[source]#
Bases:
objectA single-curve panel (the spectral filter).
- Parameters:
line (Line2D)
- class croak.plotting.MarginalArtists(line_retr, legend, line_meas=None)[source]#
Bases:
objectArtists of a marginal panel: retrieved and (optional) measured curves.
- Parameters:
line_retr (Line2D)
legend (Legend)
line_meas (Line2D | None)
- class croak.plotting.SpectrogramArtists(mesh)[source]#
Bases:
objectArtists of the spectrogram panel: its image.
- Parameters:
mesh (QuadMesh)
- class croak.plotting.PanelSpec(key, title, draw)[source]#
Bases:
objectOne retrieval panel: registry key, axes title and how to draw it.
- Parameters:
key (str)
title (str)
draw (PanelDraw)
- class croak.plotting.PageSpec(key, title, mosaic)[source]#
Bases:
objectA figure’s worth of panels laid out as a grid of registry keys.
- Parameters:
key (str)
title (str)
mosaic (tuple[tuple[str, ...], ...])
- key, title
Identifier and human-readable name (the GUI’s tab label).
- Type:
str
- mosaic#
Rows of panel keys, as
subplot_mosaic()takes them.- Type:
tuple of tuple of str
- property keys: tuple[str, ...]#
The page’s panel keys in reading order.
- class croak.plotting.ColorbarSpec(panels, shrink=0.6, neg_label='neg |·|')[source]#
Bases:
objectA colorbar shared by the listed panels (drawn only when all are present).
A positive colorbar is always drawn; a second,
neg_label-ed one appears when any of the panels holds negative samples (seesigned_pcolormesh()).- Parameters:
panels (tuple[str, ...])
shrink (float)
neg_label (str)
- croak.plotting.RETRIEVAL_PANELS: Mapping[str, PanelSpec] = {'convergence': PanelSpec(key='convergence', title='Convergence', draw=<function draw_convergence>), 'delay_marginal': PanelSpec(key='delay_marginal', title='Delay marginal', draw=<function draw_delay_marginal>), 'freq_marginal': PanelSpec(key='freq_marginal', title='Frequency marginal', draw=<function draw_freq_marginal>), 'measured_lin': PanelSpec(key='measured_lin', title='Measured (lin)', draw=<function draw_measured_lin>), 'measured_log': PanelSpec(key='measured_log', title='Measured (log)', draw=<function draw_measured_log>), 'residual': PanelSpec(key='residual', title='Residuals', draw=<function draw_residual>), 'retrieved_lin': PanelSpec(key='retrieved_lin', title='Retrieved (lin)', draw=<function draw_retrieved_lin>), 'retrieved_log': PanelSpec(key='retrieved_log', title='Retrieved (log)', draw=<function draw_retrieved_log>), 'spectral': PanelSpec(key='spectral', title='Spectrum', draw=<function draw_spectral>), 'spectral_filter': PanelSpec(key='spectral_filter', title='Spectral filter', draw=<function draw_spectral_filter>), 'spectrogram': PanelSpec(key='spectrogram', title='Spectrogram', draw=<function draw_spectrogram>), 'temporal': PanelSpec(key='temporal', title='Retrieved pulse', draw=<function draw_temporal>)}#
The twelve retrieval panels, keyed, in the overview’s reading order.
- croak.plotting.RETRIEVAL_COLORBARS: tuple[ColorbarSpec, ...] = (ColorbarSpec(panels=('measured_log', 'retrieved_log'), shrink=0.6, neg_label='neg |·|'), ColorbarSpec(panels=('measured_lin', 'retrieved_lin'), shrink=0.6, neg_label='neg |·|'), ColorbarSpec(panels=('residual',), shrink=0.6, neg_label='neg |·|'))#
one per trace pair (they share a scale) and one for the residual.
- Type:
Colorbars
- croak.plotting.RETRIEVAL_PAGES: Mapping[str, PageSpec] = {'diagnostics': PageSpec(key='diagnostics', title='Diagnostics', mosaic=(('convergence', 'residual'), ('spectral_filter', 'spectrogram'))), 'pulse': PageSpec(key='pulse', title='Pulse', mosaic=(('temporal', 'spectral'), ('delay_marginal', 'freq_marginal'))), 'traces': PageSpec(key='traces', title='Traces', mosaic=(('measured_log', 'retrieved_log'), ('measured_lin', 'retrieved_lin')))}#
The three 2×2 pages the GUI shows as tabs.
- croak.plotting.RETRIEVAL_OVERVIEW = PageSpec(key='overview', title='Retrieval overview', mosaic=(('measured_log', 'retrieved_log', 'temporal', 'delay_marginal'), ('measured_lin', 'retrieved_lin', 'spectral', 'freq_marginal'), ('convergence', 'residual', 'spectral_filter', 'spectrogram')))#
traces left, pulse right (the delay marginal beside the time-domain pulse, the frequency marginal beside the spectrum), diagnostics along the bottom.
- Type:
The 3×4 overview
plot_retrieval()draws
- croak.plotting.plot_retrieval_page(data, page, *, figsize=(8.5, 6.3), fig=None)[source]#
Draw one page of retrieval panels (a
RETRIEVAL_PAGESentry).The default
figsizegives a 2×2 page the same per-panel size as the overview’s default 17.0×9.45 in.- Parameters:
data (RetrievalPlotData) – From
retrieval_plot_data().page (PageSpec) – Which panels, in which grid;
RETRIEVAL_OVERVIEWdraws all twelve.figsize (tuple of float) – Size (in) of a new figure; ignored when
figis given.fig (Figure, optional) – Existing figure to clear and draw into (a GUI canvas).
- Return type:
Figure
Examples
>>> data = retrieval_plot_data(result, measured=trace) >>> fig = plot_retrieval_page(data, RETRIEVAL_PAGES["pulse"])
- croak.plotting.draw_measured_log(ax, data)[source]#
Draw the measured trace, logarithmic (
tracedbdynamic range).- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_retrieved_log(ax, data)[source]#
Draw the retrieved trace, logarithmic.
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_measured_lin(ax, data)[source]#
Draw the measured trace, linear, on the scale shared with the retrieved.
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_retrieved_lin(ax, data)[source]#
Draw the retrieved trace, linear, annotated with FROG error and shape.
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_temporal(ax, data)[source]#
Draw the retrieved pulse: intensity/power, TL pulse, phase, truth overlay.
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_spectral(ax, data)[source]#
Draw the spectrum: retrieved, measured, phase and fit, GDD/TOD, truth.
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_convergence(ax, data)[source]#
Draw the FROG error against iteration, with the solver’s stage handovers.
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_residual(ax, data)[source]#
Draw the measured − retrieved residual; leave it empty if there is none.
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_spectral_filter(ax, data)[source]#
Draw the per-frequency scale factor (Rω filter) against wavelength.
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_freq_marginal(ax, data)[source]#
Draw the frequency marginal of the retrieved and measured traces.
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_delay_marginal(ax, data)[source]#
Draw the delay marginal of the retrieved and measured traces.
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.draw_spectrogram(ax, data)[source]#
Draw the Gabor spectrogram of the retrieved pulse (computed once, cached).
- Parameters:
data (RetrievalPlotData)
- Return type:
- croak.plotting.plot_frog_filter(td, *, tracedb=30.0, cmap='viridis', figsize=(9.45, 4.72), fig=None)[source]#
6-panel measured/filtered (wavelength-domain) + regridded (frequency-domain).
Positive values use the viridis (white-low) map; negative values — kept through filtering rather than clamped — are drawn by magnitude on a white→red map so they are visible and not mistaken for signal. Each row (the dB row and the linear row) carries one positive + one negative colorbar on the right-hand side.
- Parameters:
tracedb (float)
cmap (str)
fig (Figure | None)
- Return type:
Figure
- croak.plotting.filter_view_vmax(td)[source]#
Return the shared positive colour scale for the six-panel filter view.
Take the largest positive sample across the measured, filtered and regridded traces, restricting the two wavelength-domain arrays to the measurement window
td.lamm_limswhen set.Both restrictions matter on real data. An absolute-calibration curve amplifies the background-subtracted noise far outside the signal band, so scaling by
max|·|lets a large negative excursion set the positive scale: on one of our measured deep-UV traces, whose signal peaks at+1but dips to-5.7at 1097 nm, every linear panel rendered its signal at 18 % of the colour range.The three panels share this one number so the row’s single colourbar means something; each array is peak-normalised upstream, so they are comparable. If no positive sample remains, fall back to the largest absolute value, then 1.0, so the returned scale is always positive.
- Return type:
float
- croak.plotting.plot_simulated_trace(omega, delays, trace, omega0_trace, *, tracedb=40.0, cmap='viridis', figsize=(7.87, 5.51), fig=None)[source]#
4-panel view of a simulated trace: dB, linear, and the two marginals.
- Parameters:
tracedb (float)
cmap (str)
fig (Figure | None)
- Return type:
Figure
- croak.plotting.plot_fwhm_distribution(ax, uresult, *, truth=None)[source]#
Histogram of bootstrap FWHM samples with the point estimate and intervals.
- Parameters:
ax (matplotlib.axes.Axes) – Axis to draw into.
uresult (UncertaintyResult) – The bootstrap result (its
samplesare histogrammed).truth (float, optional) – A known true FWHM (s) to mark with a dashed line (synthetic tests).
- Return type:
None
- croak.plotting.plot_intensity_band(ax, uresult)[source]#
Plot the median temporal intensity and pointwise 68 %/95 % resampling bands.
Requires the bootstrap to have been run with
collect_profiles=True. The profiles are peak-aligned (translation gauge removed byshiftnorm), so the band is the spread of the aligned intensity envelope across replicates. The bands are pointwise, not simultaneous bands for the whole curve.- Parameters:
uresult (UncertaintyResult)
- Return type:
None
- croak.plotting.plot_uncertainty(uresult, *, truth=None, figsize=(11.0, 4.2), fig=None)[source]#
Composite uncertainty figure: FWHM histogram + a confidence band if present.
- Parameters:
uresult (UncertaintyResult) – The bootstrap result.
truth (float, optional) – Known true FWHM (s) for the histogram (synthetic tests).
figsize (tuple, optional) – Figure size.
fig (matplotlib.figure.Figure, optional) – Existing figure to draw into (cleared first), e.g. a Qt canvas figure.
- Returns:
matplotlib.figure.Figure
- Return type:
Figure
Figures of the GUI’s views#
Publication figures of what the GUI shows: screen views drawn by matplotlib.
The window’s plots are pyqtgraph, built from the Qt-free views of
croak.plotting.screen. draw_view() draws one of those views into a
matplotlib axes with the same data, colours and line styles, and
views_figure() lays a page’s views out as one figure, so any plot or page
can be saved as a vector PDF or SVG (or a PNG). Images are rasterized inside a
vector file (rasterized=True): a trace map stays a few hundred kilobytes and
opens quickly, while its axes, labels and curves stay sharp.
Examples
>>> import numpy as np
>>> from croak.plotting.screen import CurveView, LineView
>>> view = LineView(
... curves=(CurveView(np.arange(3.0), np.ones(3), "retrieved", "pulse"),),
... title="Temporal",
... xlabel="Time (fs)",
... ylabel="Intensity",
... )
>>> fig = views_figure([[view]])
>>> fig.axes[0].get_xlabel()
'Time (fs)'
- croak.plotting.export.EXPORT_RC = {'axes.labelsize': 8, 'axes.linewidth': 0.6, 'axes.titlesize': 8, 'font.size': 8, 'legend.fontsize': 7, 'legend.frameon': False, 'lines.linewidth': 1.2, 'pdf.fonttype': 42, 'ps.fonttype': 42, 'svg.fonttype': 'none', 'xtick.direction': 'in', 'xtick.labelsize': 7, 'xtick.top': True, 'ytick.direction': 'in', 'ytick.labelsize': 7, 'ytick.right': True}#
small type, inward ticks.
- Type:
Matplotlib settings for a figure at print size
- croak.plotting.export.PANEL_SIZE = (3.4, 2.6)#
a journal’s single column is about 3.4 in wide.
- Type:
One panel’s size in inches
- croak.plotting.export.draw_line_view(ax, view)[source]#
Draw a line
viewintoax: curves, a right axis, bands and rules.- Parameters:
ax (matplotlib.axes.Axes) – Where to draw.
view (LineView) – The curves and their decorations.
- Return type:
None
- croak.plotting.export.draw_map_view(ax, view, *, colours=None, white=True)[source]#
Draw a map
viewintoaxwith a colour bar, as the screen shows it.- Parameters:
ax (matplotlib.axes.Axes) – Where to draw.
view (MapView) – The image, its levels and labels.
colours (str, optional) – The colour map (default: the view’s own).
white (bool) – Start the colour map at white, so an empty background reads as paper. A signed view’s negative values fade from red to white at zero.
- Return type:
None
- croak.plotting.export.draw_view(ax, view, *, colours=None, white=True)[source]#
Draw
viewintoax(a map or a line view; see the two drawers).- Parameters:
ax (Axes)
view (MapView | LineView)
colours (str | None)
white (bool)
- Return type:
None
- croak.plotting.export.save_figure(fig, path)[source]#
Save
figtopath; the extension picks PDF, SVG or PNG.Saved under
EXPORT_RC, which keeps text as editable text in a vector file, atEXPORT_DPI.- Parameters:
fig (Figure)
path (str)
- Return type:
None
- croak.plotting.export.views_figure(views, *, colours=None, white=None)[source]#
Lay views out as a figure: rows of panels, as they sit on the page.
- Parameters:
views (sequence of sequence of view or None) – The rows;
Noneleaves a cell empty.colours (sequence of sequence, optional) – Per cell, a map’s colour map and white-based scale (see
draw_map_view()); default: the view’s own map, white-based.white (sequence of sequence, optional) – Per cell, a map’s colour map and white-based scale (see
draw_map_view()); default: the view’s own map, white-based.
- Returns:
matplotlib.figure.Figure – At
PANEL_SIZEper panel, drawn withEXPORT_RC.- Raises:
ValueError – If there is nothing to draw.
- Return type:
Figure
The display’s spectral axis and range#
Show a screen view on the spectral axis and logarithmic range the viewer chose.
The views of croak.plotting.screen are built on the axis their data were
computed on: a loaded trace against wavelength, a retrieval against frequency.
displayed() moves any of them to the axis a Display asks for and
sets every logarithmic map’s range, so that one setting holds for every plot.
Moving between wavelength λ (nm) and frequency ν (PHz) uses ν = c/λ, with c = 299.792458 nm·PHz, on positions, ranges, shaded intervals and rules. An intensity is a density per unit of its axis, so it also takes the Jacobian: from \(I_\lambda\,d\lambda = I_\nu\,d\nu\),
Either way the factor is the square of the old coordinate, up to the constant,
so a broad spectrum changes shape, not only position. Every map, and every curve
marked as a density (density), is
converted so; a phase or a filter factor only moves. The views are normalised
displays, so after the Jacobian each map and each density curve is rescaled to
its old peak (in dB: shifted to its old peak), and the colour scale still
reads the same. A map is resampled onto an even grid on the new axis
(uniform_image()); that is for drawing only.
Examples
>>> import numpy as np
>>> from croak.plotting.screen import WAVELENGTH_LABEL, CurveView, LineView
>>> flat = CurveView(np.array([500.0, 1000.0]), np.array([1.0, 1.0]), "measured")
>>> view = LineView(
... curves=(flat,),
... title="Spectrum",
... xlabel=WAVELENGTH_LABEL,
... ylabel="Intensity",
... )
>>> shown = displayed(view, Display(axis="frequency"))
>>> shown.xlabel, shown.curves[0].x.round(4).tolist(), shown.curves[0].y.tolist()
('Frequency (PHz)', [0.2998, 0.5996], [1.0, 0.25])
- croak.plotting.display.DB_RANGE = 30.0#
The default range of a logarithmic map below its peak, dB.
- croak.plotting.display.DB_RANGE_LIMITS = (5.0, 120.0)#
The narrowest and widest logarithmic range, dB (the views keep values down to
DB_DEPTHbelow the peak).
- croak.plotting.display.DISPLAY_AXES: tuple[str, ...] = ('native', 'wavelength', 'frequency')#
The spectral axes a display can ask for;
"native"keeps each view’s own.
- croak.plotting.display.SPEED_OF_LIGHT_NM_PHZ = 299.792458#
The speed of light in nm·PHz, so that ν (PHz) = c / λ (nm).
- class croak.plotting.display.Display(axis='native', db_range=30.0)[source]#
Bases:
objectHow the views are shown: their spectral axis and logarithmic range.
- axis#
The spectral axis of every view;
"native"keeps each on its own.- Type:
{“native”, “wavelength”, “frequency”}
- db_range#
Every logarithmic map spans this many dB below its peak, within
DB_RANGE_LIMITS.- Type:
float
- Raises:
ValueError – For an unknown axis or a range outside the limits.
- Parameters:
axis (str)
db_range (float)
- croak.plotting.display.displayed(view: MapView, display: Display) MapView[source]#
- croak.plotting.display.displayed(view: LineView, display: Display) LineView
Return
viewasdisplayshows it (the view itself if unchanged).- Parameters:
view (MapView or LineView) – A screen view; its spectral axis is the one labelled
WAVELENGTH_LABELorFREQUENCY_LABEL.display (Display) – The axis and the logarithmic range.
- Returns:
MapView or LineView – The view on the display’s axis, with its logarithmic range.
- Return type:
MapView | LineView