quicknxs.interfaces package

Python interface for the Qt UI files.

class quicknxs.interfaces.Q

Generic type for QMainWindow, QDialog, or QWidget.

alias of TypeVar(‘Q’, ~PyQt5.QtWidgets.QMainWindow, ~PyQt5.QtWidgets.QDialog, ~PyQt5.QtWidgets.QWidget)

quicknxs.interfaces.load_ui(ui_filename: str, base_instance: Q) Q[source]

Subpackages

Submodules

quicknxs.interfaces.configuration. module

Application configuration, including reduction options.

class quicknxs.interfaces.configuration.BinningType(value)[source]

Bases: IntEnum

Enum for binning types.

CONST_Q = 2
NONE = 0
NORMAL = 1
class quicknxs.interfaces.configuration.Configuration[source]

Bases: object

Hold reduction options.

Class Attributes

TBD

Instance Attributes

metadata_roi_peak: List[float]

Peak range of interest, obtained from data set’s metadata

metadata_roi_bck: List[float]

Background range of interest, obtained from data set’s metadata

DELTA_KZ_VS_QZ = 3
KZI_VS_KZF = 1
QX_VS_QZ = 0
apply_deadtime = False
bck_offset = 5
property bck_roi
binning_q_step_global = -0.02
binning_type_global = 0
deadtime_tof_step = 100
deadtime_value = 4.2
global_stitching = False
lock_direct_beam_y = False
property low_res_roi
nbr_events_min = 100
normalize_to_unity = True
paralyzable_deadtime = True
property peak_roi
polynomial_stitching = False
polynomial_stitching_degree = 3
polynomial_stitching_points = 3
sample_size = 10
classmethod setup_default_values()[source]

Initialize class variables - only used for testing purposes.

total_reflectivity_q_cutoff = 0.01
update_peak_range = False
use_low_res_finder = False
use_metadata_bck_roi = True
use_peak_finder = False
use_roi = True
use_tight_bck = False
wl_bandwidth = 3.2
quicknxs.interfaces.configuration.get_direct_beam_low_res_roi(data_conf: Configuration, direct_beam_conf: Configuration) List[int][source]

Get the direct beam low res ROI.

Either from the data run or from the direct beam depending on the configuration data_conf.lock_direct_beam_y

Returns:

The pixel range of the direct beam ROI in the low res direction (y)

Return type:

List[int]

quicknxs.interfaces.data_manager module

Data manager. Holds information about the current data location and manages the data cache.

class quicknxs.interfaces.data_manager.DataManager(current_directory: str)[source]

Bases: object

Holds information about the current data location and manages the data cache.

current_directory

Current directory

current_file_name

Current file name, used for file list table to set the current item

_nexus_data

Current data set

active_cross_section

Currently active CrossSectionData

_cache

Cache of loaded data

active_reduction_list_index

Index of current data (ROI) tab

peak_reduction_lists

Dictionary of reduction lists key: reduction list index, corresponds to the reduction table tab in the UI

direct_beam_list

List of direct beam data sets

reduction_states

List of cross-sections common to all reduced data sets

final_merged_reflectivity

Merged reflectivity data

cached_offspec

Cached off-specular data

cached_gisans

Cached GISANS data

MAIN_REDUCTION_LIST_INDEX = 1
MAX_CACHE = 50
add_active_to_direct_beam_list()[source]

Add active data set to the direct beam list.

This method allows adding any run to the direct beam list, even if it wasn’t originally acquired as a direct beam (i.e., when the PV data_type != 1). This is useful for calibration and other runs started with “Start RUN” command in EPICS, which don’t add the “Direct Beam” PV-tag.

Returns:

2 if the run was added and is a true direct beam (data_type == 1) 1 if the run was added but is NOT a true direct beam (data_type != 1) 0 if the run was not added (already in the list)

Return type:

int

add_active_to_reduction(peak_index=1) bool[source]

Add active data set to reduction list.

New data sets are always added to the main reduction list. Data sets are added to secondary reduction lists by initializing from the main reduction list (button to add new data tab) or by propagating individual data sets to other tabs (right-click menu).

Parameters:

peak_index (int) – The index of the peak in peak_reduction_lists

Returns:

True if the active data set was added to the reduction list, False if it was not added

Return type:

bool

add_additional_reduction_list(tab_index: int)[source]

Add reduction list for an additional ROI/peak.

Parameters:

tab_index (int) – Index of the peak in self.peak_reduction_lists

asymmetry()[source]

Determine which cross-section to use to compute asymmetry, and compute it.

calculate_gisans(nexus_data=None, progress=None)[source]

Compute GISANS for a single data set.

calculate_reflectivity(configuration=None, active_only=False, nexus_data=None, specular=True)[source]

Calculate reflectivity using the current configuration.

clear_cache()[source]
clear_cached_unused_data()[source]

Delete cached files that are not in the reduction list or direct beam list.

clear_direct_beam_list()[source]

Remove all items from the direct beam list.

clear_reduction_lists()[source]

Resets to one empty reduction list.

copy_nexus_data_to_reduction(nexus_data_to_copy: NexusData, peak_index: int)[source]

Add data set to the reduction list specified by peak_index.

Parameters:
  • nexus_data_to_copy – Data set to copy

  • peak_index – reduction list to copy data set to

Returns:

True if the data set was added successfully, otherwise False

Return type:

bool

property current_event_files: List[str]

Sorted list of event files in the current directory.

Return only file names with pattern ‘event.nxs’ or ‘.nxs.h5’

property current_file
property data_sets

Dict of reduced cross sections.

Type:

dict

determine_asymmetry_states()[source]

Determine which cross-section to use to compute asymmetry.

extract_metadata(file_path=None)[source]

Return the current q-value at the center of the wavelength range of the current data set.

If a file path is provided, the mid q-value will be extracted from that data file.

find_active_data_id() int | None[source]

Look for the active data in the reduction list.

Returns:

The index within the reduction list or none.

Return type:

int | None

find_active_direct_beam_id() int | None[source]

Look for the active data in the direct beam list.

Returns:

The index within the direct beam list or none.

Return type:

int | None

find_best_direct_beam()[source]

Find the best direct beam in the direct beam list for the active data.

Returns:

True if we have updated the data with a new normalization run.

Return type:

bool

find_data_in_direct_beam_list(nexus_data: NexusData | None) int | None[source]

Look for the given data in the direct beam list.

Returns:

The index within the direct beam list, or none.

Return type:

int | None

find_data_in_reduction_list(nexus_data)[source]

Look for the given data in the reduction list.

Returns:

The index within the reduction list, or none.

Return type:

int | None

find_direct_beam_by_name(direct_beam_name: str) NexusData | None[source]

Find a direct beam data set by its name.

Parameters:

direct_beam_name (str) – Name of the direct beam run to find.

Returns:

The direct beam data set if found, otherwise None.

Return type:

NexusData or None

find_run_number_in_direct_beam_list(nexus_data: NexusData | None) int | None[source]

Look for data with the same run number in the direct beam list.

This method compares by run number rather than object identity, which is useful for detecting duplicates when deepcopied objects are involved.

Parameters:

nexus_data (NexusData | None) – The data to search for by run number.

Returns:

The index within the direct beam list, or None if not found.

Return type:

int | None

find_run_number_in_reduction_list(run_number: int, reduction_list: list[NexusData])[source]

Look for the given run number in the reduction list.

Returns:

The index in the reduction list or None

Return type:

int | None

get_active_direct_beam()[source]

Return the direct beam data object for the active data.

get_cachesize()[source]
get_trim_values() List[int] | None[source]

Cut the start and end of the active data set to 5% of its maximum intensity.

is_active(data_set: NexusData)[source]

Check if the given data set is the active data set.

is_direct_beam_for_run(nexus_data: NexusData, direct_beam_run: str | int) bool[source]

Check if the direct beam is the configured direct beam for the given run.

Parameters:
  • nexus_data (NexusData) – NexusData run object

  • direct_beam (str | int) – Direct beam run number

is_gisans_available(active_only=True)[source]

Verify that all data sets and all cross-sections have calculated GISANS data available.

is_nexus_data_compatible(nexus_data: NexusData, reduction_list: List[NexusData]) bool[source]

Determine if the data set is compatible with the data sets in the reduction list.

A data set is compatible if the polarization cross-section states matches those of the first run in the reduction list, both the same number of states and the same states.

Parameters:
  • nexus_data (NexusData) – The data set to check if compatible with reduction list

  • reduction_list (list[NexusData]) – The reduction list

Returns:

True if the data set is compatible with the reduction list, False otherwise.

Return type:

bool

is_offspec_available()[source]

Verify that all data sets and all cross-sections have calculated off-specular data available.

is_same_run(run_number_a: str | int, run_number_b: str | int) bool[source]

Returns True if two run numbers are considered the same.

Tries to compare the run numbers as integers if possible; falls back to comparing them as-is (e.g., strings).

Parameters:
  • run_number_a (str or int) – The first run number.

  • run_number_b (str or int) – The second run number.

Returns:

True if the run numbers are equal (after normalization), False otherwise.

Return type:

bool

load(file_path: str, configuration: Configuration, force: bool = False, update_parameters: bool = True, progress: Callable | None = None) bool[source]

Load one or more Nexus data files.

Parameters:
  • file_path – absolute path to one or more files. If more than one, files are concatenated with the merge symbol ‘+’.

  • configuration – Configuration to use to load the data

  • force – if True, existing data in the cache will be replaced by reading from file.

  • update_parameters – if True, we will find peak ranges

  • progress – aggregator to estimate percent of time allotted to this function

Returns:

True if the data is retrieved from the cache of past loading events

Return type:

bool

load_data_from_reduced_file(file_path: str, configuration: Configuration | None = None, progress: ProgressReporter = None)[source]

Load the information from a reduced file, the load the data.

Ask the main event handler to update the UI once we are done.

load_direct_beam_and_data_files(db_files: List[tuple], data_files: List[tuple], additional_peaks: list | None = None, configuration: Configuration | None = None, progress: ProgressReporter | None = None, force: bool = False, t_0: float | None = None)[source]

Load direct beam and data files and add them to the direct beam list and reduction list, respectively.

Parameters:
  • db_files (list) – List of (run_number, run_file, conf, slice_value) for direct beam files

  • data_files (list) – List of (run_number, run_file, conf, slice_value) for data files

  • additional_peaks (list | None) – List of (peak_index, run_number, run_file, conf, slice_value) for data files for additional peaks

  • configuration (Configuration) – Configuration to base the loaded data on

  • progress (ProgressReporter) – Progress reporter

  • force (bool) – If True, ignore cache and force reloading from file

  • t_0 (float) – Start time for logging data loading time

property main_reduction_list: list[NexusData]

Reduction list for the first (mandatory) data tab.

merge_data_sets(asymmetry=True)[source]
rebin_gisans(pol_state, wl_min=0, wl_max=100, qy_npts=50, qz_npts=50, use_pf=False)[source]

Merge all the off-specular reflectivity data and rebin.

reduce_gisans(progress=None)[source]

Calculate GISANS for all datasets in the reduction list.

Since the specular reflectivity is prominently displayed, it is updated as soon as parameters change. This is not the case for GISANS, which is computed on-demand.

reduce_offspec(progress=None)[source]

Calculate off-specular reflectivity for all datasets in all reduction list.

Since the specular reflectivity is prominently displayed, it is updated as soon as parameters change. This is not the case for the off-specular, which is computed on-demand.

reduce_spec(direct_beam: int | str | None = None)[source]

Calculate reflectivity for all runs in all reduction lists.

If a direct beam is given, only calculate reflectivity for the runs using the given direct beam.

Parameters:

direct_beam (Optional[str | int]) – Direct beam run number

property reduction_list: list[NexusData]

Reduction list for the active data tab.

Type:

list[NexusData]

reload_files(configuration: Configuration | None = None, progress=None)[source]

Force reload of files in the reduction lists and direct beam list.

remove_active_from_direct_beam_list()[source]

Remove the active data set from the direct beam list.

Uses run number comparison to find the entry, since the active data may be the original object while the list contains a deepcopy.

remove_additional_reduction_list(tab_index: int)[source]

Remove reduction list for additional ROI/peak.

Parameters:

tab_index (int) – Index of the peak in self.peak_reduction_lists

remove_from_active_reduction_list(index: int)[source]

Remove item from the active reduction list.

Parameters:

index (int) – Index of the item to remove

set_active_cross_section(index: int) bool[source]

Set the current cross section to the specified index, or zero if it doesn’t exist.

set_active_data_from_direct_beam_list(index: int)[source]

Set a data set in the direct beam list as the active data set according to its index.

Parameters:

index – index in the direct beam list

set_active_data_from_reduction_list(index)[source]

Set a data set in the reduction list as the active data set according to its index.

Parameters:

index (int) – index in the reduction list

set_active_reduction_list_index(tab_index: int)[source]

Set the active reduction list index.

Parameters:

tab_index (int) – Index of the peak in self.peak_reduction_lists

stitch_data_sets(normalize_to_unity: bool = True, q_cutoff: float = 0.01, global_stitching: bool = False, poly_degree: int | None = None, poly_points: int = 3)[source]

Determine scaling factors for each data set.

Parameters:
  • normalize_to_unity – If True, the reflectivity plateau will be normalized to 1.

  • q_cutoff – critical q-value below which we expect R=1

  • global_stitching – If True, use data from all cross-sections to calculate scaling factors

  • poly_degree – if not None, find the scaling factor by simultaneously fitting a polynomial and scaling factor to the curves

  • poly_points – number of additional points on each end of the overlap region to include in the fit

strip_overlap()[source]

Remove overlapping points in the reflectivity, cutting always from the lower Qz measurements.

update_active_direct_beam()[source]

Updates the active direct beam when switching to the direct beam tab.

Tries to maintain the previously selected direct beam row index if available, otherwise defaults to the first direct beam.

update_active_reduction_list(tab_index: int)[source]

Updates the active reduction list and run.

Parameters:

tab_index (int) – Index of the peak in self.peak_reduction_lists

update_configuration(configuration, active_only: bool = False, nexus_data: NexusData | None = None)[source]

Update configuration.

update_direct_pixel_from_direct_beam() float | None[source]

Set direct_pixel_overwrite based on the matched direct beam peak position.

quicknxs.interfaces.main_window module

class quicknxs.interfaces.main_window.MainWindow[source]

Bases: QMainWindow

Main application window.

Initialization.

addDataTable()[source]

Add data tab for additional peaks/ROIs.

addRefl()[source]

Signal handling to add a new reflectivity data set.

add_data_tab_by_index(tab_index: int)[source]

Add/update a specific data tab.

add_direct_beam()[source]
apply_offspec_crop()[source]
autoRef()[source]

Signal handling to run automated file selection.

changeRegionValues()[source]

Called when the reflectivity extraction region has been changed.

Sets up a trigger to replot the reflectivity with a delay so a subsequent change can occur without several replots.

change_active_cross_section(is_checked: bool)[source]

Update the run info and overview plots when the active cross section is changed.

The toggled() signal is emitted from both radio buttons whose states were changed, therefore, use the bool value to only perform update actions once.

Parameters:

is_checked (bool) – The state of the radio button that emitted the signal.

change_gisans_colorscale()[source]
change_offspec_colorscale()[source]

Change the intensity limits for the color scale of the off-specular plots.

clearRefList()[source]

Signal handling to clear the reflectivity data set list.

clear_direct_beam_list()[source]

Signal handling.

closeEvent(event)[source]

Close UI event.

current_table_changed(tab_index: int)[source]

Update the state for active data set and the UI.

cutPoints()[source]

Cut the start and end of the active data set to 5% of its maximum intensity.

direct_beam_table_changed(item: QTableWidgetItem)[source]
direct_beam_table_right_click(pos: QPoint)[source]

Handle right-click on the direct beam table.

file_loaded()[source]

Update UI after a file is loaded.

file_loaded_signal

Signal emitted when a file is loaded.

file_open_dialog()[source]

Show a dialog to open a new file.

file_open_from_list()[source]

Called when a new file is selected from the file list. This is an event call.

file_open_sum_dialog()[source]

Read a set of congruent file data sets.

Select a list of event or histogram files, check their metadata is compatible, and read-in.

get_direct_beam()[source]

Retrieve the direct beam data for the active reflectivity data.

This is used to normalize the distributions we are plotting. See plotting.plot_xtof and plotting.plot_overview

global_reflectivity_config_changed()[source]

Perform action upon change in global reflectivity configuration.

handle_roi_checkbox(state)[source]

Handle the ROI checkbox state change.

hide_data_table()[source]
hide_run_data()[source]
hide_sidebar()[source]
hide_unsupported()[source]

Hide what we don’t support.

initialize_instrument()[source]

Initialize instrument according to the instrument and saved parameters.

initiate_projection_plot(bool)

Signal to initiate the projection plot.

initiate_reflectivity_or_intensity_plot

Signal to initiate the reflectivity or intensity plot.

keyPressEvent(event)[source]

UI event.

keyReleaseEvent(event)[source]

UI event.

loadExtraction()[source]
match_direct_beam_clicked()[source]

Find the best direct beam run for the activate data set and compute the reflectivity as needed.

normalizeTotalReflection()[source]

Stitch the reflectivity parts and normalize to 1.

openByNumber()[source]

Signal handling to open a file by run number.

open_advanced_background()[source]
open_deadtime_settings()[source]

Show the dialog for dead-time options.

Update global configuration parameters upon closing the dialog.

open_polarization_window()[source]
open_rawdata_dialog()[source]
plotActiveTab()[source]

Select the appropriate function to plot all visible images.

plot_manager

Setting auto_change_active = True bypasses execution of: - MainWindow.file_open_from_list() - MainWindow.changeRegionValues() - MainHandler.reduction_table_changed() - MainHandler.direct_beam_table_changed()

propagate_binning_options_to_runs()[source]

Apply the binning options in the global reflectivity extraction panel to all runs.

reduceDatasets()[source]

Open a dialog to select reduction options for the current list of reduction items.

reductionTableChanged(item)[source]

Perform action upon change in data reduction list.

reduction_table_right_click(pos: QPoint)[source]

Handle right-click on the reduction table.

refresh_file_list()[source]
refresh_offspec()[source]

Refresh / recalculate the off-specular plots.

reload_all_files()[source]

Reload all previously loaded files upon change in loading configuration.

reload_file()[source]

Reload the file that is currently selected form the list.

removeDataTable()[source]

Remove last data tab for additional peaks/ROI:s

removeRefl()[source]

Signal handling to remove a reflectivity data set.

remove_direct_beam()[source]

Signal handling.

replotProjections()[source]

Signal handling to replot the projections.

reset_data_tabs()[source]

Reset UI to one visible data tab.

set_active_direct_beam(checked: bool, row: int)[source]

Select a data set when the user double-clicks on a run number (col 0) in the direct beam table.

set_active_reduction_data(checked: bool, row: int)[source]

Select a data set (when checking the active box in the normalization/reduction table).

show_results()[source]
stripOverlap()[source]

Remove overlapping points in the reflectivity.

Cutting is done from the lower Qz measurements.

toggleColorbars()[source]

Refresh plots because of a color or scale change.

toggle_smoothing()[source]
update_gisans_viewer

Signal to update the GISANS viewer.

update_off_specular_viewer

Signal to update the off-specular viewer.

update_offspec_qz_bin_width(value=None)[source]
update_specular_viewer

Signal to update the specular viewer.

quicknxs.interfaces.main_window.disabled_widget(widget: QWidget)[source]

Temporarily disable a widget for the duration of the context.

Restores the enabled state of the widget when the context exits.

quicknxs.interfaces.plotting module

class quicknxs.interfaces.plotting.PlotManager(main_window)[source]

Bases: object

PlotManager is responsible for plotting the data in the main window.

plot_gisans()[source]

Create GISANS plots of the current dataset with Qy-Qz maps.

plot_offspec(recalc=True, crop=False)[source]

Plot off-specular data.

Create an offspecular plot for all cross sections of the datasets in the reduction list. The user can define upper and lower bounds for the plotted intensity and select the coordinates to be either kiz-kfz vs. Qz, Qx vs. Qz or kiz vs. kfz.

plot_overview()[source]

X vs. Y and X vs. Tof for main xs.

plot_projections(preserve_lim=False)[source]

Create projections of the data on the x and y axes.

The x-projection can also be done be means of quantile calculation, which means that the ToF intensities are calculation which are exceeded by a certain number of points. This can be helpful to better separate the specular reflection from bragg-sheets

plot_reflectivity_or_intensity()[source]

Plot reflectivity data or intensity, depending on the type of the active run.

If the active run is a direct beam run (natively labeled as direct beam OR selected from the direct beam table), the intensity vs ToF (or wavelength) in the region-of-interest (ROI) is plotted.

If the active run is selected from the reduction/data table, the reflectivity of all datasets is plotted, even if that same run also exists in the direct beam table.

This allows users to compare different ROIs by adding the same run to both tables, with the plot type determined by which table the user is currently viewing from.

Return type:

True if the plot was successful, False otherwise

plot_xtof()[source]

X vs. ToF plots for all xss.

plot_xy()[source]

X vs. Y plots for all xss.

quicknxs.interfaces.reduction_dialog module

Modal dialog for reduction options.

Dialog to select reduction options to choose which outputs are needed and in which formats to write them.

class quicknxs.interfaces.reduction_dialog.ReductionDialog(parent)[source]

Bases: QDialog

Reduction dialog.

accept()[source]

Save the current options and close dialog.

change_directory()[source]

Change the output directory.

default_template = '{instrument}_{numbers}_{peak}_{item}_{state}.{type}'
get_options()[source]

Return the reduction options as a dict.

reset_filename_template()[source]

Reset the filename template to the default.

save_settings() None[source]

Save reduction options in QSettings.

quicknxs.interfaces.result_viewer module

Dialog to show final reduced data.

class quicknxs.interfaces.result_viewer.ResultViewer(parent, data_manager: DataManager)[source]

Bases: QDialog

Reduction dialog.

apply_gisans_crop()[source]
apply_offspec_crop()[source]
default_template = '{instrument}_{numbers}_{peak}_{item}_{state}.{type}'
reset_gisans_crop()[source]
reset_offspec_crop()[source]
update_active_tab()[source]
update_gisans(crop: bool = False)[source]

Update the results viewer with the latest GISANS calculations.

Parameters:

crop – If True, all the plots will be cropped to the ++ cross-section

update_off_specular(crop: bool = False)[source]

Update the result viewer with the latest off-specular calculations.

Parameters:

crop – If True, all the plots will be cropped to the ++ cross-section

update_specular()[source]
quicknxs.interfaces.result_viewer.clear_layout(layout)[source]

quicknxs.interfaces.smooth_dialog module

Dialog to let the user select smoothing options.

This code was taken as-is from QuickNXS v1

class quicknxs.interfaces.smooth_dialog.SmoothDialog(parent, data_manager: DataManager)[source]

Bases: QDialog

Dialog to define smoothing parameters.

GRID_OFFSET = 0.05
INTENSITY_MAX = 1.0
INTENSITY_MIN = 1e-06
drawPlot()[source]

Plot the unsmoothed data.

drawing = False
plotSelect(event)[source]

Plot for y-projection has been clicked.

updateGrid()[source]
updateSettings()[source]
update_output_options(output_options: dict) dict[source]

Update a dict with smoothing options.