Analysis Modules¶
Specialized modules for XPCS analysis, plotting, and data processing.
Note
These modules depend on PyQtGraph for interactive plotting. Some functions accept PyQtGraph plot items as arguments; those parameters will appear as mock types in the rendered documentation.
G2 Correlation Analysis¶
Multi-tau correlation analysis with single and double exponential fitting.
G2 correlation analysis module.
Provides multi-tau correlation analysis with single and double exponential fitting for XPCS time correlation functions.
- Functions:
get_data: Extract G2 correlation data from XpcsFile objects fit_g2: Fit G2 data with exponential models
- xpcsviewer.module.g2mod.get_data(xf_list, q_range=None, t_range=None)[source]
Extract G2 correlation data from a list of XpcsFile objects.
Reads G2 correlation values, errors, delay times, and Q-values from each file, optionally filtered by Q-range and time-range.
- Parameters:
xf_list – List of XpcsFile objects with correlation analysis data.
q_range – Optional (min, max) Q-value filter in inverse Angstroms.
t_range – Optional (min, max) delay time filter in seconds.
- Returns:
(q, tel, g2, g2_err, labels)where each element is a list of per-file arrays. Returns(False, None, None, None, None)if any file lacks Multitau or Twotime analysis.- Return type:
If all files contain correlation data, returns a 5-tuple
Example
>>> q, tel, g2, g2_err, labels = get_data(xf_list, q_range=(0.01, 0.1)) >>> if q is not False: ... print(f"Loaded {len(q)} files, {g2[0].shape[1]} Q-bins")
- xpcsviewer.module.g2mod.get_g2_stability_data(xf_obj, q_range=None, t_range=None)[source]
Extract G2 stability data from a single XpcsFile object.
- xpcsviewer.module.g2mod.pg_plot_stability(hdl, xf_obj, q_range, t_range, y_range, y_auto=False, q_auto=False, t_auto=False, num_col=4, offset=0, show_label=False, plot_type='multiple', marker_size=5, **kwargs)[source]
Plot G2 stability data showing frame-by-frame correlation analysis.
- Parameters:
hdl (GraphicsLayoutWidget) – PyQtGraph layout widget for plotting
xf_obj (XpcsFile) – XpcsFile object with g2_partial data
q_range (tuple) – Q-range for filtering
t_range (tuple) – Time range for filtering
y_range (tuple) – Y-axis range
y_auto (bool) – Auto-range flags
q_auto (bool) – Auto-range flags
t_auto (bool) – Auto-range flags
num_col (int) – Number of columns in layout
offset (float) – Y-offset between curves
show_label (bool) – Show legend labels
plot_type (str) – Plot type: ‘multiple’, ‘single’, ‘single-combined’
marker_size (int) – Symbol size
**kwargs (dict) – Additional plotting parameters
- xpcsviewer.module.g2mod.compute_geometry(g2, plot_type)[source]
Compute subplot grid dimensions for G2 plots.
Determines how many figures (subplots) and how many overlay lines per figure are needed based on the layout mode.
- Parameters:
g2 – List of 2-D G2 arrays, each shaped
(n_delay, n_q).plot_type – Layout mode.
"multiple"creates one subplot per Q-bin,"single"one per file, and"single-combined"puts everything on one axes.
- Returns:
(num_figs, num_lines)where num_figs is the number of subplot panels and num_lines is the number of curves per panel.- Return type:
- Raises:
ValueError – If plot_type is not a recognised layout mode.
- xpcsviewer.module.g2mod.pg_plot(hdl, xf_list, q_range, t_range, y_range, y_auto=False, q_auto=False, t_auto=False, num_col=4, rows=None, offset=0, show_fit=False, show_label=False, bounds=None, fit_flag=None, plot_type='multiple', subtract_baseline=True, marker_size=5, label_size=4, fit_func='single', robust_fitting=False, enable_diagnostics=False, **kwargs)[source]
Plot G2 correlation data using PyQtGraph with optional curve fitting.
Renders multi-panel G2 plots with configurable layout, fitting overlays, and baseline subtraction. Supports single, double, and stretched exponential fitting models.
- Parameters:
hdl – PyQtGraph plot handler (GraphicsLayoutWidget).
xf_list – List of XpcsFile objects containing G2 data.
q_range – (min, max) Q-value range in inverse Angstroms, or None.
t_range – (min, max) delay time range in seconds, or None.
y_range – (min, max) y-axis range for G2 values, or None.
y_auto – If True, auto-scale y-axis.
q_auto – If True, ignore q_range and use all Q-bins.
t_auto – If True, ignore t_range and use all delay times.
num_col – Number of plot columns in the grid layout.
rows – List of file indices to plot, or None for all.
offset – Vertical offset between datasets for visibility.
show_fit – If True, overlay fitted curves on the data.
show_label – If True, display legend labels.
bounds – Fitting bounds array, shape
(2, n_params).fit_flag – Boolean array indicating which parameters to fit.
plot_type – Layout mode:
'multiple'(one panel per Q-bin),'single'(one panel per file), or'single-combined'.subtract_baseline – If True, subtract fitted baseline from data.
marker_size – Size of data point markers in pixels.
label_size – Font size for legend labels in points.
fit_func – Fitting model:
'single'or'double'exponential.robust_fitting – If True, use NLSQ multistart robust fitting.
enable_diagnostics – If True, compute model health diagnostics.
**kwargs – Additional keyword arguments passed to fitting routines. Includes
force_refit(bool) to force re-fitting.
Example
>>> pg_plot(hdl, xf_list, q_range=(0.01, 0.1), ... t_range=(1e-4, 10), y_range=(0.9, 1.5), ... show_fit=True, fit_func='single')
- xpcsviewer.module.g2mod.pg_plot_from_data(hdl, *, q, tel, g2, g2_err, labels, num_figs, fit_results=None, y_auto=False, q_auto=False, t_auto=False, num_col=4, rows=None, offset=0, show_fit=False, show_label=False, y_range=None, t_range=None, plot_type='multiple', subtract_baseline=True, marker_size=5, fit_func='single', **_ignored_kwargs)[source]
Render pre-fetched G2 data without re-fetching from XpcsFile objects.
This is the rendering-only counterpart of
pg_plot. It accepts the data structures already extracted by the async worker (q,tel,g2,g2_err,labels) and renders them directly, avoiding the redundantget_data()andget_xf_list()calls thatvk.plot_g2would otherwise trigger on the main thread (BUG-014).Parameters mirror the
pg_plotsignature where applicable.
- xpcsviewer.module.g2mod.pg_plot_one_g2(ax, x, y, dy, color, label, symbol, symbol_size=5)[source]
Plot a single G2 correlation curve with error bars on a log-x axis.
Filters NaN/inf values, applies log-scale x-axis, and downsamples dense data for rendering performance.
- Parameters:
ax – PyQtGraph PlotItem to draw on.
x – Delay times array (must be positive for log scale).
y – G2 correlation values.
dy – G2 error bars (standard deviation).
color – RGB tuple for plot color, e.g.
(255, 0, 0).label – Legend label string, or None.
symbol – PyQtGraph symbol character (e.g.
'o','s').symbol_size – Marker size in pixels (default 5).
- xpcsviewer.module.g2mod.vectorized_g2_baseline_correction(g2_data, baseline_values)[source]
Vectorized baseline correction for G2 data.
- Parameters:
g2_data – G2 data array [time, q_values]
baseline_values – Baseline values [q_values]
- Returns:
Baseline-corrected G2 data
- xpcsviewer.module.g2mod.batch_g2_normalization(g2_data_list, method='max')[source]
Batch normalization of multiple G2 datasets using vectorized operations.
- Parameters:
g2_data_list – List of G2 data arrays
method – Normalization method (‘max’, ‘mean’, ‘std’)
- Returns:
List of normalized G2 data arrays
- xpcsviewer.module.g2mod.compute_g2_ensemble_statistics(g2_data_list, include_median=False)[source]
Compute ensemble statistics for multiple G2 datasets using vectorized operations.
- Parameters:
g2_data_list – List of G2 data arrays [time, q_values]
include_median (bool) – If True, compute and include ensemble_median in the result. This adds an O(B·T·Q·log B) partial-sort cost on top of the O(B·T·Q) mean/std computation. Defaults to False for performance. Set True only when the caller genuinely needs the median statistic.
- Returns:
- ensemble_mean, ensemble_std, ensemble_min, ensemble_max,
ensemble_var, q_mean_values, temporal_correlation.
- Optionally contains:
ensemble_median (when include_median=True).
- Return type:
Dictionary with ensemble statistics. Always contains
- xpcsviewer.module.g2mod.optimize_g2_error_propagation(g2_data, g2_errors, operations)[source]
Vectorized error propagation for G2 data operations.
- Parameters:
g2_data – G2 data array [time, q_values]
g2_errors – G2 error array [time, q_values]
operations – List of operations applied to data
- Returns:
Propagated errors
- xpcsviewer.module.g2mod.vectorized_g2_interpolation(tel, g2_data, target_tel)[source]
Vectorized interpolation of G2 data to new time points.
Uses JAX vmap + interpax for batch interpolation when available, falling back to a single scipy interp1d call with 2D y otherwise.
- Parameters:
tel – Original time points
g2_data – G2 data [time, q_values]
target_tel – Target time points for interpolation
- Returns:
Interpolated G2 data
SAXS 1D Analysis¶
Radial averaging, intensity profiles, and line plotting.
SAXS 1D analysis module.
Provides radial averaging and intensity profile analysis for small-angle X-ray scattering data.
- Functions:
get_data: Extract 1D SAXS intensity profiles plot_saxs1d: Generate SAXS 1D plots
- xpcsviewer.module.saxs1d.get_pyqtgraph_anchor_params(loc, padding=10)[source]
Converts a Matplotlib loc string or code to pyqtgraph anchor parameters.
Calculates the ‘itemPos’, ‘parentPos’, and ‘offset’ needed to position a pyqtgraph LegendItem similarly to how Matplotlib places legends using the ‘loc’ parameter.
- Parameters:
- Returns:
- A dictionary with keys ‘itemPos’, ‘parentPos’, and ‘offset’
suitable for unpacking into LegendItem.anchor(**params), or None if loc=’best’ (code 0) as it is not directly supported by pyqtgraph deterministic anchoring.
- Return type:
dict or None
- Raises:
ValueError – If the loc code or type is invalid.
Example Usage:
plot_item = pg.PlotItem() legend = plot_item.addLegend() # ... plot data ... try: anchor_params = get_pyqtgraph_anchor_params('lower left', padding=15) if anchor_params: legend.anchor(\*\*anchor_params) else: logger.info("Using default legend position for best location") except ValueError as e: logger.warning(f"Error setting legend position: {e}")
- xpcsviewer.module.saxs1d.offset_intensity(Iq, n, plot_offset=None, yscale=None)[source]
Apply a vertical offset to intensity curves for visual separation.
For linear y-scale, subtracts a fraction of the peak intensity per file index. For log y-scale, divides by a power-of-ten factor.
- Parameters:
Iq – Intensity array. Can be 1-D
(n_q,)or 2-D(n_phi, n_q).n – File index (0-based) used to scale the offset.
plot_offset – Offset magnitude.
Noneor 0 means no offset.yscale –
"linear"or"log"determines the offset strategy.
- Returns:
Offset-adjusted intensity array (same shape as Iq).
- Return type:
- xpcsviewer.module.saxs1d.switch_line_builder(hdl, lb_type=None)[source]
- xpcsviewer.module.saxs1d.plot_line_with_marker(plot_item, x, y, index, label, alpha_val, marker_size=6, log_x=False, log_y=False)[source]
Vectorized plotting function with advanced data filtering and memory optimization.
- xpcsviewer.module.saxs1d.pg_plot(xf_list, pg_hdl, plot_type=2, plot_norm=0, plot_offset=0, title=None, rows=None, qmax=10.0, qmin=0, loc='best', marker_size=3, sampling=1, all_phi=False, absolute_crosssection=False, subtract_background=False, bkg_file=None, weight=1.0, roi_list=None, show_roi=True, show_phi_roi=True)[source]
Plot one-dimensional SAXS intensity profiles using PyQtGraph.
Renders I(q) curves for one or more XPCS files with support for log/linear axis scaling, intensity normalization, background subtraction, and multi-phi overlays.
- Parameters:
xf_list – List of XpcsFile objects containing SAXS 1-D data.
pg_hdl – PyQtGraph PlotWidget handle for rendering.
plot_type – Axis scale encoding. 0 = lin-lin, 1 = log-lin, 2 = lin-log, 3 = log-log. Default is 2 (lin-log).
plot_norm – Normalization mode index. 0 = none, 1 = q^2, 2 = q^4, 3 = I(0).
plot_offset – Vertical offset exponent applied per file for visual separation. 0 means no offset.
title – Plot title string, or None for no title.
rows – List of file indices to highlight at full opacity. Remaining files are drawn at alpha 0.35.
qmax – Upper bound of the q-range to display (1/A).
qmin – Lower bound of the q-range to display (1/A).
loc – Legend anchor position string (e.g.
"best","upper right").marker_size – Scatter marker diameter in pixels.
sampling – Down-sampling factor for the q-points. 1 = no down-sampling.
all_phi – If True, plot all phi-sector curves. Otherwise plot only the first (azimuthally averaged) curve.
absolute_crosssection – If True, convert intensity to absolute cross-section units (1/cm).
subtract_background – Enable background subtraction using bkg_file.
bkg_file – XpcsFile used as the background reference when subtract_background is True.
weight – Multiplicative weight applied to the background before subtraction.
roi_list – Optional list of ROI descriptors to overlay.
show_roi – Show q-ROI indicators on the plot.
show_phi_roi – Show phi-ROI indicators on the plot.
Example
>>> pg_plot( ... xf_list=[xf], ... pg_hdl=widget, ... plot_type=3, ... qmin=0.001, ... qmax=1.0, ... )
- xpcsviewer.module.saxs1d.vectorized_q_binning(q_values, intensities, q_min, q_max, num_bins)[source]
Vectorized q-space binning for SAXS data with optimized memory usage.
Uses single-pass bincount accumulation instead of per-bin masking loops.
- Parameters:
q_values – Q-values array
intensities – Intensity array [q_points] or [phi_slices, q_points]
q_min – Q-range for binning
q_max – Q-range for binning
num_bins – Number of bins
- Returns:
Tuple of (binned_q, binned_intensity, bin_counts)
- xpcsviewer.module.saxs1d.vectorized_background_subtraction(foreground_data, background_data, weight=1.0)[source]
Vectorized background subtraction with error propagation.
- Parameters:
foreground_data – Tuple of (q, I_fg, I_err_fg)
background_data – Tuple of (q_bg, I_bg, I_err_bg)
weight – Background scaling weight
- Returns:
Tuple of (q, I_subtracted, I_err_propagated)
- xpcsviewer.module.saxs1d.vectorized_intensity_normalization(q_values, intensities, method='none', q_ref=None)[source]
Vectorized intensity normalization using various methods.
- Parameters:
q_values – Q-values array
intensities – Intensity array
method – Normalization method (‘none’, ‘q2’, ‘q4’, ‘max’, ‘area’)
q_ref – Reference q-value for certain normalizations
- Returns:
Normalized intensity array
- xpcsviewer.module.saxs1d.batch_saxs_analysis(data_list, operations)[source]
Batch processing of multiple SAXS datasets with vectorized operations.
- Parameters:
data_list – List of (q, I) tuples
operations – List of operations to apply
- Returns:
List of processed (q, I) tuples
- xpcsviewer.module.saxs1d.optimize_roi_extraction(image_stack, roi_definitions)[source]
Vectorized ROI extraction from image stacks.
- Parameters:
image_stack – Image array [frames, height, width] or [height, width]
roi_definitions – List of ROI definitions with coordinates
- Returns:
Dictionary with extracted ROI data
SAXS 2D Visualization¶
2D scattering pattern visualization.
2D SAXS scattering pattern visualization.
Provides visualization of integrated 2D small-angle X-ray scattering patterns with support for log/linear scaling, colormap selection, and image rotation.
- Functions:
plot: Display 2D SAXS pattern with beam center overlay.
- xpcsviewer.module.saxs2d.plot(xfile, pg_hdl=None, plot_type='log', cmap='jet', rotate=False, autolevel=False, autorange=False, vmin=None, vmax=None)[source]
Display a 2-D SAXS detector image in a PyQtGraph ImageView.
Renders the detector image from xfile with optional log scaling, custom colour mapping, and intensity clamping. A beam-centre ROI marker is drawn automatically.
- Parameters:
xfile – XpcsFile containing
saxs_2dandsaxs_2d_logimage arrays plus beam centre coordinates (bcx,bcy).pg_hdl – PyQtGraph ImageView handle for rendering.
plot_type – Image intensity scaling.
"log"uses the pre-computed log-scaled image; any other value uses the linear image.cmap – Colour-map name passed to
pg_hdl.set_colormap.Nonekeeps the current colour map.rotate – If True, transpose the image (unused in current implementation but returned for caller state tracking).
autolevel – Automatically scale intensity levels to the data range.
autorange – Force the view to fit the full image. When False the previous view range is preserved unless the image shape changed.
vmin – Manual lower intensity clamp. Applied only when autolevel is False.
vmax – Manual upper intensity clamp. Applied only when autolevel is False.
- Returns:
The rotate flag, echoed back for caller convenience.
- Return type:
Example
>>> rotate = plot(xfile, pg_hdl=viewer, plot_type="log", ... cmap="viridis", vmin=0, vmax=100)
Two-Time Correlation¶
Two-time correlation map visualization and analysis for studying temporal dynamics beyond traditional multi-tau analysis.
Two-time correlation analysis module.
Provides two-time correlation map visualization and analysis for studying temporal dynamics beyond traditional multi-tau analysis.
- Functions:
get_twotime_data: Extract two-time correlation matrices plot_twotime: Generate two-time correlation maps
- xpcsviewer.module.twotime.clean_c2_for_visualization(c2, method='nan_to_num')[source]
Clean C2 data to remove NaN/inf values that cause white lines in visualization.
- Parameters:
c2 – C2 correlation matrix
method – Cleaning method (‘nan_to_num’, ‘interpolate’, ‘median’)
- Returns:
Cleaned C2 matrix with NaN/inf values replaced
- xpcsviewer.module.twotime.calculate_safe_levels(c2)[source]
Calculate vmin/vmax levels while safely handling NaN/inf values.
- Parameters:
c2 – C2 correlation matrix
- Returns:
Tuple of (vmin, vmax) computed from finite values only
- xpcsviewer.module.twotime.plot_twotime(xfile, hdl, scale='log', auto_crop=True, highlight_xy=None, cmap='jet', vmin=None, vmax=None, autolevel=True, correct_diag=False, selection=0)[source]
Render a two-time correlation map with associated SAXS and G2 panels.
Displays the C2 two-time correlation matrix alongside the dynamic Q-map, SAXS pattern, and extracted G2 correlation curves (full and partial).
- Parameters:
xfile – XpcsFile object with Twotime analysis data.
hdl – Dictionary of PyQtGraph ImageView/PlotItem handles with keys
'saxs','dqmap','tt','c2g2'.scale – Intensity scale for the SAXS/dqmap display:
'log'or'linear'.auto_crop – If True, automatically crop the Q-map display.
highlight_xy – Optional (x, y) pixel coordinate to highlight on maps.
cmap – Matplotlib colormap name for the C2 matrix (default
'jet').vmin – Minimum color level for C2 display. Ignored when autolevel=True.
vmax – Maximum color level for C2 display. Ignored when autolevel=True.
autolevel – If True, auto-compute color levels from the data.
correct_diag – If True, apply diagonal correction to C2 matrix.
selection – Q-bin index to display (default 0).
- Raises:
AssertionError – If
xfiledoes not contain Twotime analysis.
Example
>>> plot_twotime(xfile, hdl, cmap='viridis', autolevel=True)
- xpcsviewer.module.twotime.plot_twotime_g2(hdl, c2_result)[source]
Plot G2 correlation curves extracted from the two-time correlation matrix.
Displays both the full G2 (averaged over all time sections) and partial G2 curves (individual time sections) on a log-x axis.
- Parameters:
hdl – Dictionary of PyQtGraph handles; uses
hdl['c2g2']PlotItem.c2_result – Dictionary from
XpcsFile.get_twotime_c2()with keys'g2_full','g2_partial', and'acquire_period'.
Two-Time Utilities¶
C2 matrix I/O and processing utilities.
- xpcsviewer.module.twotime_utils.get_optimal_worker_count()[source]
Get optimal number of worker processes based on system resources.
- Return type:
- xpcsviewer.module.twotime_utils.get_process_pool(num_workers=None)[source]
Get or create a reusable process pool.
- Parameters:
num_workers (int | None) – Number of worker processes. If None, uses optimal count.
- Returns:
ProcessPoolExecutor instance
- Return type:
ProcessPoolExecutor
- xpcsviewer.module.twotime_utils.shutdown_process_pool()[source]
Shutdown the global process pool.
- xpcsviewer.module.twotime_utils.create_shared_array(name, shape, dtype=<class 'numpy.float32'>)[source]
Create a shared memory array for multiprocessing.
- xpcsviewer.module.twotime_utils.get_shared_array(name)[source]
Get a previously created shared array by name.
- xpcsviewer.module.twotime_utils.cleanup_shared_arrays()[source]
Clean up all shared memory arrays.
- xpcsviewer.module.twotime_utils.read_single_c2_enhanced(args)[source]
Vectorized version of read_single_c2 with optimized matrix operations.
- xpcsviewer.module.twotime_utils.process_c2_batch(batch_args, progress_callback=None)[source]
Optimized batch processing of C2 matrices with vectorized operations.
- xpcsviewer.module.twotime_utils.correct_diagonal_c2_vectorized(c2_mat)[source]
Vectorized diagonal correction for C2 matrices. Optimized to eliminate loops and use advanced NumPy operations.
- xpcsviewer.module.twotime_utils.read_single_c2(args)[source]
Optimized single C2 reading with vectorized matrix operations.
- xpcsviewer.module.twotime_utils.get_all_c2_from_hdf(full_path, dq_selection=None, max_c2_num=32, max_size=512, num_workers=12, correct_diag=True)[source]
- xpcsviewer.module.twotime_utils.get_all_c2_from_hdf_enhanced(full_path, dq_selection=None, max_c2_num=32, max_size=512, num_workers=None, correct_diag=True, progress_callback=None)[source]
Enhanced version of get_all_c2_from_hdf with better multiprocessing and progress reporting.
- Parameters:
full_path – Path to HDF5 file
dq_selection – List of q-indices to load
max_c2_num – Maximum number of C2 matrices to load
max_size – Maximum size for C2 matrices (for downsampling)
num_workers – Number of worker processes (auto-determined if None)
correct_diag – Whether to apply diagonal correction
progress_callback – Optional callback for progress updates
- Returns:
Dictionary containing C2 data and metadata
- xpcsviewer.module.twotime_utils.get_single_c2_from_hdf(full_path, selection=0, max_size=512, t0=1, correct_diag=True)[source]
- xpcsviewer.module.twotime_utils.get_c2_g2partials_from_hdf(full_path)[source]
- xpcsviewer.module.twotime_utils.get_c2_stream(full_path, max_size=-1)[source]
Returns (idxlist, generator) where the generator yields C2 streams.
- xpcsviewer.module.twotime_utils.batch_c2_matrix_operations(c2_matrices, operations=None)[source]
Vectorized batch operations on multiple C2 matrices.
- Parameters:
c2_matrices – List or array of C2 matrices
operations – List of operations to apply (‘normalize’, ‘symmetrize’, ‘diagonal_correct’)
- Returns:
Processed C2 matrices
- xpcsviewer.module.twotime_utils.compute_c2_statistics_vectorized(c2_matrices)[source]
Compute statistical measures for C2 matrices using vectorized operations.
Uses a JAX-accelerated path when the matrix size is >= 1024, where the GPU transfer overhead is amortised by the larger workload (8.8× measured speedup at 2048×2048). Smaller matrices use the NumPy path to avoid the 0.7× slowdown seen at 512×512.
- Parameters:
c2_matrices – Array of C2 matrices [batch, height, width]
- Returns:
Dictionary with statistical measures
- xpcsviewer.module.twotime_utils.optimized_c2_sampling(c2_matrix, target_size, method='bilinear')[source]
Optimized C2 matrix downsampling using vectorized operations.
- Parameters:
c2_matrix – Input C2 matrix
target_size – Target matrix size
method – Sampling method (‘uniform’, ‘bilinear’, ‘adaptive’)
- Returns:
Downsampled C2 matrix
Stability Analysis¶
Sample stability monitoring by comparing SAXS-1D profiles across time sections.
Sample stability monitoring module.
Analyzes temporal stability of XPCS measurements by comparing intensity profiles across time sections. Helps identify beam damage, sample drift, or other instabilities.
- Functions:
plot: Generate stability comparison plots.
- xpcsviewer.module.stability.plot(fc, pg_hdl, plot_type=2, plot_norm=0, legend=None, title=None, loc='upper right', **kwargs)[source]
Generate a stability comparison plot for an XPCS measurement.
Plots partial SAXS-1D profiles from different time sections of the measurement to visualize temporal stability (beam damage, drift, etc.).
- Parameters:
fc – XpcsFile object containing partial SAXS-1D data.
pg_hdl – PyQtGraph PlotWidget to render into.
plot_type – Axis scaling mode. Bit 0 controls log-x, bit 1 controls log-y: 0=linear-linear, 1=log-linear, 2=linear-log, 3=log-log.
plot_norm – Normalization method index: 0=none, 1=q^2, 2=q^4, 3=I(0).
legend – Unused (legend is created internally).
title – Unused (title is set from
fc.label).loc – Legend anchor position string, e.g.
'upper right'.**kwargs – Additional keyword arguments (currently unused).
Example
>>> from xpcsviewer.module import stability >>> stability.plot(xf, pg_widget, plot_type=3, plot_norm=1)
Intensity vs Time¶
Time series analysis of intensity fluctuations with FFT spectrum and interactive zoom panels.
Intensity vs time analysis module.
Provides visualization of intensity fluctuations over time for XPCS data. Supports multiple q-bins, smoothing, and sampling options.
- Functions:
smooth_data: Apply rolling window smoothing to intensity data. plot: Generate intensity vs time plots with PyQtGraph.
- xpcsviewer.module.intt.smooth_data(fc, window=1, sampling=1)[source]
Apply rolling average smoothing and downsampling to intensity data.
- Parameters:
fc – XpcsFile object with
Int_tproperty returning(x, y).window – Rolling average window size. Values <= 1 skip smoothing.
sampling – Downsampling factor. Values < 2 skip downsampling.
- Returns:
Tuple of
(x, y)arrays after smoothing and downsampling.
- xpcsviewer.module.intt.plot(xf_list, pg_hdl, enable_zoom=True, xlabel='Frame Index', **kwargs)[source]
Plot intensity vs time with FFT spectrum and interactive zoom panel.
Renders a three-panel layout: main intensity time series, Fourier spectrum, and interactive zoom view with a draggable region selector.
- Parameters:
xf_list – List of XpcsFile objects to plot.
pg_hdl – PyQtGraph GraphicsLayoutWidget to render into.
enable_zoom – If True, add an interactive zoom panel with a draggable region selector linked to the main plot.
xlabel – X-axis label. Use
'Frame Index'for raw frames or a time-based label (the x-values are then scaled byfc.t0).**kwargs – Smoothing parameters passed to
smooth_data():window(int) for rolling average width,sampling(int) for downsampling factor.
Example
>>> from xpcsviewer.module import intt >>> intt.plot(xf_list, pg_widget, xlabel='Time (s)', window=5)
Tau-Q Analysis¶
Relaxation time vs Q-value analysis for diffusion characterization.
- xpcsviewer.module.tauq.plot(xf_list, hdl, q_range, offset, plot_type=3)[source]
Plot relaxation time tau versus scattering vector q.
Renders tau(q) with error bars for each file, optionally overlaying a power-law fit line when available.
- Parameters:
xf_list – List of XpcsFile objects that contain G2 fitting results (
fit_summary).hdl – Matplotlib figure handle (
MplCanvas) for rendering.q_range – Tuple
(qmin, qmax)limiting the q-axis display range (currently unused inside the function but passed for caller compatibility).offset – Decade offset exponent applied per file for visual separation. File n is divided by
10^(offset * n).plot_type – Axis scale encoding. 0 = lin-lin, 1 = log-lin, 2 = lin-log, 3 = log-log. Default is 3.
Example
>>> plot(xf_list, hdl=canvas, q_range=(0.001, 0.1), ... offset=0, plot_type=3)
- xpcsviewer.module.tauq.plot_pre(xf_list, hdl)[source]
Plot G2 fitting parameters versus q in a 2x2 subplot grid.
Displays contrast, tau, stretch exponent, and baseline as functions of scattering vector q for all files in xf_list. Upper and lower fit bounds are shown as horizontal lines.
When xf_list is empty, an instructional message is displayed directing the user to perform G2 fitting first.
- Parameters:
xf_list – List of XpcsFile objects with G2 fitting results (
fit_summarycontainingq_val,fit_val, andbounds).hdl – Matplotlib figure handle (
MplCanvas) for rendering.
Example
>>> plot_pre(xf_list, hdl=canvas)
File Averaging¶
Parallel processing framework for averaging multiple XPCS datasets.
See xpcsviewer.module.average_toolbox for complete API documentation.
Note
This module contains Qt-dependent classes (AverageToolbox, WorkerSignal)
that cannot be rendered by autodoc. Refer to the source code for API details.