drtsans.mono.biosans package

Submodules

drtsans.mono.biosans.api module

BIOSANS API

drtsans.mono.biosans.api.load_all_files(reduction_input: dict, prefix: str = '', load_params: dict = {}, path: str = None, use_nexus_idf: bool = False, debug_output: bool = False) dict[source]

Load all required files at the beginning, and transform them into histograms.

Parameters:
  • reduction_input (dict) – Dictionary containing the reduction input

  • prefix (str) – Prefix to be used for the workspaces

  • load_params (dict) – Dictionary containing the parameters to be passed to the Load event algorithm

  • path (str) – Additional path to search the for NeXus files

  • use_nexus_idf (bool) – Flag to enforce to use IDF from NeXus file. It must be true for SPICE-converted NeXus

  • debug_output (bool) – Flag to save internal data for debugging

Returns:

Dictionary containing the configuration used to load the workspaces

Return type:

dict

drtsans.mono.biosans.api.plot_reduction_output(reduction_output: list, reduction_input: dict, loglog: bool = True, imshow_kwargs: dict = {})[source]

Generate reduction plot per slice per detector.

Parameters:
  • reduction_output – List of 1D and 2D I(Q) profile objects, for each detector panel

  • reduction_input – Dictionary of all possible options to properly configure the data reduction workflow.

  • loglog – Whether to plot in loglog scale, by default True.

  • imshow_kwargs – Keyword arguments to pass to imshow, by default {}.

drtsans.mono.biosans.api.prepare_data(data, data_dir=None, pixel_calibration=False, mask_detector=None, detector_offset=0, sample_offset=0, center_x=None, center_y=None, center_y_wing=None, center_y_midrange=None, dark_current=None, flux_method=None, monitor_fail_switch=False, mask=None, mask_panel=None, btp={}, solid_angle=True, sensitivity_file_path=None, sensitivity_workspace=None, wave_length=None, wavelength_spread=None, sample_aperture_diameter=None, sample_thickness=None, source_aperture_diameter=None, smearing_pixel_size_x=None, smearing_pixel_size_y=None, output_workspace=None, output_suffix='', **kwargs)[source]

Load a BIOSANS data file and bring the data to a point where it can be used. This includes applying basic corrections that are always applied regardless of whether the data is background or scattering data.

Parameters:
  • data (int, str, IEventWorkspace) – Run number as int or str, file path, IEventWorkspace

  • data_dir (str, list) – Additional data search directories

  • pixel_calibration (bool) – Adjust pixel heights and widths according to barscan and tube-width calibrations.

  • mask_detector (str, list) – Name of one or more instrument components to mask: (e.g detector1,wing_detector)

  • detector_offset (float) – Additional translation of the detector along Z-axis, in mili-meters.

  • sample_offset (float) – Additional translation of the sample along the Z-axis, in mili-meters.

  • center_x (float) – Move the center of the detector to this X-coordinate. If None, the detector will be moved such that the X-coordinate of the intersection point between the neutron beam and the detector array will have x=0.

  • center_y (float) – Move the center of the detector to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • center_y_wing (float) – Move the center of the wing detector to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • center_y_midrange (float) – Move the center of the detector vertically to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • dark_current (int, str, IEventWorkspace) – Run number as int or str, file path, IEventWorkspace

  • flux_method (str) – Method for flux normalization. Either ‘monitor’, or ‘time’.

  • monitor_fail_switch (bool) – Resort to normalization by ‘time’ if ‘monitor’ was selected but no monitor counts are available

  • panel (str) – Either ‘front’ or ‘back’ to mask a whole panel

  • mask_panel (str) – Either ‘front’ or ‘back’ to mask whole front or back panel.

  • mask (mask file path, MaskWorkspace, list) – Additional mask to be applied. If list, it is a list of detector ID’s.

  • btp (dict) – Additional properties to Mantid’s MaskBTP algorithm

  • solid_angle (bool) – Apply the solid angle correction

  • sensitivity_file_path (str) – file containing previously calculated sensitivity correction

  • sensitivity_workspace (str, MatrixWorkspace) – workspace containing previously calculated sensitivity correction. This overrides the sensitivity_filename if both are provided.

  • wave_length (float, None) – wave length in Angstrom

  • wavelength_spread (float, None) – wave length spread in Angstrom

  • sample_aperture_diameter (float, None) – sample aperture diameter in mm

  • sample_thickness (None, float) – sample thickness in unit cm

  • source_aperture_diameter (float, None) – source aperture size radius in unit mm

  • smearing_pixel_size_x (float, None) – pixel size in x direction in unit as meter, only for Q-resolution calculation

  • smearing_pixel_size_y (float, None) – pixel size in Y direction in unit as meter, only for Q-resolution calculation

  • output_workspace (str) – Name of the output workspace. If not supplied, will be determined from the supplied value of data.

  • output_suffix (str) – If the output_workspace is not specified, this is appended to the automatically generated output workspace name.

Returns:

Reference to the events workspace

Return type:

IEventWorkspace

drtsans.mono.biosans.api.prepare_data_workspaces(data, center_x=None, center_y=None, center_y_wing=None, center_y_midrange=None, dark_current=None, flux_method=None, monitor_fail_switch=False, mask_ws=None, mask_detector=None, mask_panel=None, mask_btp=None, solid_angle=True, sensitivity_workspace=None, output_workspace=None)[source]

Given a “ raw”data workspace, this function provides the following:

  • centers the detector

  • subtracts dark current

  • normalize by time or monitor

  • applies masks

  • corrects for solid angle

  • corrects for sensitivity

All steps are optional. data, mask_ws, dark_current are either None or histogram workspaces. This function does not load any file.

Parameters:
  • data (Workspace2D) – raw workspace (histogram)

  • center_x (float) – Move the center of the detector to this X-coordinate. If None, the detector will be moved such that the X-coordinate of the intersection point between the neutron beam and the detector array will have x=0.

  • center_y (float) – Move the center of the detector to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • center_y_wing (float) – Move the center r of the detector to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • center_y_midrange (float) – Move the center of the detector vertically to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • dark_current (Workspace2D) – histogram workspace containing the dark current measurement

  • flux_method (str) – Method for flux normalization. Either ‘monitor’, or ‘time’.

  • monitor_fail_switch (bool) – Resort to normalization by ‘time’ if ‘monitor’ was selected but no monitor counts are available

  • mask_ws (Workspace2D) – Mask workspace

  • mask_detector (str, list) – Name of one or more instrument components to mask: (e.g detector1,wing_detector)

  • mask_panel (str) – Either ‘front’ or ‘back’ to mask whole front or back panel.

  • mask_btp (dict) – Additional properties to Mantid’s MaskBTP algorithm

  • solid_angle (bool) – Apply the solid angle correction

  • sensitivity_workspace (str, MatrixWorkspace) – workspace containing previously calculated sensitivity correction. This overrides the sensitivity_filename if both are provided.

  • output_workspace (str) – The output workspace name. If None will create data.name()+output_suffix

Returns:

Reference to the processed workspace

Return type:

Workspace2D

drtsans.mono.biosans.api.process_single_configuration(sample_ws_raw: str | Workspace2D, sample_trans_ws: Workspace2D | None = None, sample_trans_value: float | None = None, bkg_ws_raw: Workspace2D | None = None, bkg_trans_ws: Workspace2D | None = None, bkg_trans_value: float | None = None, blocked_ws_raw: Workspace2D | None = None, theta_dependent_transmission: bool = True, center_x: float | None = None, center_y: float | None = None, center_y_wing: float | None = None, center_y_midrange: float | None = None, dark_current: Workspace2D | None = None, flux_method: str | None = None, monitor_fail_switch: bool = False, mask_ws: Workspace2D | None = None, mask_detector: str | List | None = None, mask_panel: str | None = None, mask_btp: dict | None = None, solid_angle: bool = True, sensitivity_workspace: Workspace2D | None = None, thickness: float = 1.0, absolute_scale_method: str = 'standard', absolute_scale: float = 1.0, keep_processed_workspaces: bool = True, output_workspace: str | None = None, output_prefix: str = '')[source]

This function provides full data processing for a single experimental configuration, starting from workspaces (no data loading is happening inside this function)

Steps applied to the sample and background workspaces: 1. centering the detector 2. dark current subtraction 3. normalization by time or monitor 4. masking 5. solid angle correction 6. sensitivity correction 7. transmission correction

Additional steps applied to the sample workspace: 1. background subtraction 2. thickness correction 3. absolute scaling

Parameters:
  • sample_ws_raw – raw data histogram workspace, or a string with the workspace name

  • sample_trans_ws – optional histogram workspace for sample transmission

  • sample_trans_value – optional value for sample transmission

  • bkg_ws_raw – optional raw histogram workspace for background

  • bkg_trans_ws – optional histogram workspace for background transmission

  • bkg_trans_value – optional value for background transmission

  • blocked_ws_raw – optional histogram workspace for blocked beam

  • theta_dependent_transmission (bool) – flag to apply angle dependent transmission

  • center_x – x center for the beam

  • center_y – y center for the beam

  • center_y_wing – y center for the wing detector

  • center_y_midrange – y center for the midrange detector

  • dark_current – dark current workspace

  • flux_method – normalization by ‘time’ or ‘monitor’

  • monitor_fail_switch – resort to normalization by ‘time’ if ‘monitor’ was selected but no monitor counts are available

  • mask_ws – user-defined mask

  • mask_detector – Name of one or more instrument components to mask: (e.g wing_detector,midrange_detector)

  • mask_panel – mask front or back panel of tubes

  • mask_btp – optional bank, tube, pixel to mask. These are options passed as optional arguments to Mantid algorithm MaskBTP

  • solid_angle – flag to apply solid angle

  • sensitivity_workspace – workspace containing sensitivity

  • thickness – sample thickness (cm)

  • absolute_scale_method – method to do absolute scaling. One of [“standard”, “direct_beam”]

  • absolute_scale – absolute scaling value for standard method

  • keep_processed_workspaces – flag to keep the processed blocked beam and background workspaces

  • output_workspace – output workspace name for the sample. If None, the name will be output_suffix + "_sample"

  • output_prefix – prefix for output workspaces (output_suffix + "_sample", output_suffix + "_blocked", and output_suffix + "_background")

Returns:

Reference to the processed workspace

Return type:

Workspace2D

drtsans.mono.biosans.api.reduce_single_configuration(loaded_ws: dict, reduction_input: dict, prefix: str = '', skip_nan: bool = True, debug_output: bool = False) list[source]

Do data reduction for the loaded workspaces according to the given reduction configuration

Saves to file the resulting I(Q) profiles in ASCII format as well as a reduction log.

Parameters:
  • loaded_ws – Dictionary with loaded workspaces (e.g. background, sensitivity, etc.) to use in the reduction

  • reduction_input – Reduction configuration parameters

  • prefix – String to prepend to output file names

  • skip_nan – If True, data points with value NaN will be ignored when writing I(Q) profiles to file.

  • debug_output – If True, saves 2D plots representative of the workspace at different stages of the reduction

Returns:

List of tuple of I(Q):s, one tuple per sample in the workspace. Each tuple holds I(Q):s with 1D and 2D binning for the individual detector panels, as well as a stitched 1D I(Q) profile.

Return type:

list

drtsans.mono.biosans.beam_finder module

drtsans.mono.biosans.beam_finder.center_detector(input_workspace, center_x, center_y, center_y_wing, center_y_midrange=None)[source]

Center the detector and adjusts the height for the main wing and midrange detectors This uses drtsans.center_detector()

Mantid algorithms used: MoveInstrumentComponent

Parameters:
  • input_workspace (MatrixWorkspace, str) – The workspace to be centered

  • center_x (float) – The x-coordinate of the beam center in meters

  • center_y (float) – The y-coordinate of the beam center on the main detector in meters

  • center_y_wing (float) – The y-coordinate of the beam center on the wing detector in meters

  • center_y_midrange (float) – The y-coordinate of the beam center on the midrange detector in meters

Returns:

reference to the corrected input_workspace

Return type:

MatrixWorkspace

drtsans.mono.biosans.beam_finder.fbc_options_json(reduction_input)[source]
drtsans.mono.biosans.beam_finder.find_beam_center(input_workspace, method='center_of_mass', mask=None, mask_options={}, centering_options={}, sample_det_cent_main_detector=None, sample_det_cent_wing_detector=None, sample_det_cent_midrange_detector=None, solid_angle_method='VerticalTube') Tuple[float, float, float, float, dict][source]

Finds the beam center in a 2D SANS data set.

This is based on (and uses) drtsans.find_beam_center()

Parameters:
  • input_workspace (str, MatrixWorkspace, IEventWorkspace)

  • method (str) – Method to calculate the beam center. Available methods are: - ‘center_of_mass’, invokes FindCenterOfMassPosition.

  • mask (mask file path, MaskWorkspace`, list.) – Mask to be passed on to ~drtsans.mask_utils.mask_apply.

  • mask_options (dict) – Additional arguments to be passed on to ~drtsans.mask_utils.mask_apply.

  • centering_options (dict) – Arguments to be passed on to the centering method.

  • sample_det_cent_wing_detector (float) – sample to detector center distance, in meters, of the wing detector.

  • solid_angle_method (bool, str specify which solid angle correction is needed)

Returns:

  • (center_x, center_y, center_y_wing, center_y_midrange, fit_results) where

    • center_y_wing is used to correct BIOSANS wing detector Y position.

    • center_y_midrange is used to correct BIOSANS midrange detector Y position. – if sample_det_cent_midrange_detector is specified then a float number is returned, else None.

    • fit_results produced by fitting the beam center intensities to a 2D Gaussian model of the lmfit package

drtsans.mono.biosans.cg3_spice_to_nexus module

class drtsans.mono.biosans.cg3_spice_to_nexus.CG3EventNexusConvert[source]

Bases: EventNexusConverter

Converting legacy SPICE file for BIOSANS to Event NeXus

get_pid_range(bank_id)[source]

Set GPSANS bank and pixel ID relation

Parameters:

bank_id (int) – bank ID from 1 to 88

Returns:

start PID, end PID (assuming PID are consecutive in a bank and end PID is inclusive)

Return type:

tuple

property num_banks

88

Type:

For BioSANS (CG3), the total number of banks is a fixed value

drtsans.mono.biosans.cg3_spice_to_nexus.convert_spice_to_nexus(ipts_number: int, exp_number: int, scan_number: int, pt_number: int, template_nexus: str, masked_detector_pixels: List[int] = [], output_dir: str | None = None, spice_dir: str | None = None, spice_data: str = typing.Optional[str])[source]

Convert legacy SPICE file for bioSANS/cg3 to Event NeXus

Parameters:
  • ipts_number (int) – IPTS

  • exp_number (int) – experiment number

  • scan_number (int) – scan

  • pt_number (int) – pt

  • masked_detector_pixels (~list) – List of pixels (mantid workspace indexes) to mask

  • template_nexus (str) – path to a GPSANS nED event Nexus file especially for IDF

  • output_dir (None or str) – output directory of the converted data

  • spice_dir (None or str) – data file directory for SPICE file. None using default

  • spice_data (None or str) – full data file. It is specified, there is no need to construct SPICE file name anymore

Returns:

generated event Nexus file

Return type:

str

drtsans.mono.biosans.cg3_spice_to_nexus.generate_event_nexus(source_nexus, target_nexus, das_log_list=None)[source]

Generate event NeXus properly from a source Nexus file

This method will be migrated to drtsans.mono.biaosans

Parameters:
  • source_nexus (str) – source nexus file

  • target_nexus (str) – target nexus file

  • das_log_list (~list) – list of DAS logs

drtsans.mono.biosans.prepare_sensitivities_correction module

class drtsans.mono.biosans.prepare_sensitivities_correction.PrepareSensitivityCorrection(component='detector1')[source]

Bases: PrepareSensitivityCorrection

property curved_detectors: List[str]

List of curved detectors by inspecting the first of the flood files.

Returns:

  • Either ["wing_detector"] or ["wing_detector", "midrange_detector"]

  • depending on whether the data files contain the midrange detector.

set_masks(default_mask, pixels, main_det_mask_angle=None, **kwargs) None[source]

Set masks

Parameters:
  • default_mask (str or ~mantid.api.MaskWorkspace or list or None) – Mask to be applied. If list, it is a list of detector ID’s. mask file name

  • pixels (str or None) – pixels to mask. Example: ‘1-8,249-256’

  • main_det_mask_angle (float or None) – angle to mask (MaskAngle) to main detector

  • kwargs (dict) – additional keyword arguments to accept deprecated argument “wing_det_mask_angle”. Unused.

set_theta_dependent_correction_flag(flag)[source]

Set the flag to do theta dep with transmission correction

Parameters:

flag (bool) – True to do the correction

set_transmission_correction(transmission_flood_runs, transmission_reference_runs, beam_trap_factor=2)[source]

Set transmission beam run and transmission flood runs

Parameters:
  • transmission_flood_runs (int or tuple or list) – transmission flood runs

  • transmission_reference_runs (int or tuple or list) – transmission reference runs

  • beam_trap_factor (float, int) – factor to beam trap size for masking angle

drtsans.mono.biosans.prepare_sensitivities_correction.prepare_spice_sensitivities_correction(component: str, flood_run: SpiceRun, direct_beam_run: SpiceRun, dark_current_run: SpiceRun, apply_solid_angle_correction: bool, transmission_flood_run: SpiceRun, transmission_reference_run: SpiceRun, beam_trap_size_factor: float, apply_theta_dependent_correction: bool, universal_mask_file: str | None, pixels_to_mask: str, beam_center_mask_radius: float, main_detector_mask_angle: float, wing_detector_mask_angle: float, min_count_threshold: float, max_count_threshold: float, sensitivity_file_name: str, nexus_dir: str | None = None)[source]

Prepare sensitivities from SPICE files

Parameters:
  • component (str) – Detector panel to use. One of “detector1” or “wing_detector”

  • flood_run (SpiceRun) – flood run

  • direct_beam_run (SpiceRun or None) – direct beam run

  • dark_current_run (SpiceRun) – dark current run

  • apply_solid_angle_correction (bool) – Flag to apply solid angle correction to flood run

  • transmission_flood_run (SpiceRun) – transmission flood run

  • transmission_reference_run (SpiceRun) – transmission reference run

  • beam_trap_size_factor (float) – size factor of beam trap given by user

  • apply_theta_dependent_correction (bool) – Flag to apply theta dependent correction to transmission run

  • universal_mask_file (str) – path to mask file applied to all the runs

  • pixels_to_mask (str) – lists of pixels (IDs) to mask

  • beam_center_mask_radius (float) – radius of mask for beam center in mm

  • main_detector_mask_angle (float) – angle for main detector mask

  • wing_detector_mask_angle (float) – deprecated

  • min_count_threshold (float) – minimum normalized count threshold as a good pixel

  • max_count_threshold (float) – maximum normalized count threshold as a good pixel

  • sensitivity_file_name (str) – output file name with full path

  • nexus_dir (str or None) – directory for nexus file. None for default.

drtsans.mono.biosans.reduce_spice module

drtsans.mono.biosans.reduce_spice.clear_buffer()[source]

Clear memory buffer: clear mantid workspaces

drtsans.mono.biosans.reduce_spice.generate_output_base_name(sample_run_i: str | int, sample_name_i: str) str[source]

Generate base name for output files according to sample run (Nexus file or run number) and sample name

drtsans.mono.biosans.reduce_spice.generate_output_log_file(output_directory: str, file_base_name: str, file_suffix: str) str[source]

Generate output log file name as the standard drtsans/biosans convention

drtsans.mono.biosans.reduce_spice.reduce_biosans_nexus(ipts_number: int, experiment_number: int, sample_names: List[str], sample_runs: List[Tuple[int, int]], background_runs: List[Tuple[int, int] | None], sample_transmission_runs: List[Tuple[int, int]], background_transmission_runs: List[Tuple[int, int] | None], empty_transmission_run: Tuple[int, int], beam_center_runs: Tuple[int, int], sample_thickness_list: List[str | float], sample_identifier: str, overwrite_reduced_data: bool, main_detector_dark_run: Tuple[int, int], wing_detector_dark_run: Tuple[int, int], base_output_directory: str, main_detector_sensitivities_file: str, wing_detector_sensitivities_file: str, scale_factor: float | str | None, scaling_beam_radius: float | str | None, number_linear_q1d_bins_main_detector: int | str, number_linear_q1d_bins_wing_detector: int | str, number_linear_q2d_bins_main_detector: int | str, number_linear_q2d_bins_wing_detector: int | str, plot_type: str, plot_binning: str, number_log_bins_per_decade_main_detector: int, number_log_bins_per_decade_wing_detector: int, q_range_main: List[float] | Tuple[float, float], q_range_wing: List[float] | Tuple[float, float], overlap_stitch_range: List[float] | Tuple[float, float], flexible_pixel_sizes: bool, wedge_min_angles: List[float] | None, wedge_max_angles: List[float] | None, auto_wedge_qmin: float, auto_wedge_qmax: float, auto_wedge_delta_q: float, auto_wedge_peak_width: float, auto_wedge_delta_azimuthal_angle: float, auto_wedge_background_width: float, auto_wedge_minimum_signal_to_noise_ratio: float, q_range_main_wedge0: Tuple[float, float] | List[float], q_range_wing_wedge0: Tuple[float, float] | List[float], OL_range_wedge0: Tuple[float, float] | List[float], q_range_main_wedge1: Tuple[float, float] | List[float], q_range_wing_wedge1: Tuple[float, float] | List[float], OL_range_wedge1: Tuple[float, float] | List[float], refresh_cycle: int, nexus_dir: str | None)[source]

Module contents

class drtsans.mono.biosans.BinningMethod(value)[source]

Bases: Enum

Binning method

NOWEIGHT = 1
WEIGHTED = 2
class drtsans.mono.biosans.BinningParams(min, max, bins)

Bases: tuple

bins

Alias for field number 2

max

Alias for field number 1

min

Alias for field number 0

drtsans.mono.biosans.abspath(path: str, instrument='', ipts='', directory=None, search_archive=True)[source]

Returns an absolute path

In addition to fully supporting what os.path.abspath does, this also supports path strings in such as EQSANS_106026 and EQSANS106026. It will search your data search path and the data archive using ONCat.

This looks in /instrument/proposal/nexus/instrument_runnumber.nxs.h5 then falls back to use mantid.api.FileFinder.

Parameters:
  • path – Either a run number, a file name (e.g. CG2_1235), or an absolute file path,

  • directory (str, list) – One or more directory paths where to look for the data file

drtsans.mono.biosans.abspaths(runnumbers, instrument='', ipts='', directory=None, search_archive=True)[source]
Parameters:
  • runnumbers (str) – Comma separated list of run numbers

  • instrument (str) – Name of the instrument

  • ipts (str) – Proposal number the run is expected to be in

  • directory (str, list) – One or more directory paths where to look for the data file

Returns:

Comma separated list of all of the full paths

Return type:

str

drtsans.mono.biosans.allow_overwrite(folder)[source]

Changes permissions for all the files and folders in the path to allow write by anyone. It is not recursive. It will do that only for the files/folders the user has permissions to do that

Parameters:

path (str) – string to the folder in which the file permissions are to be changed

Return type:

None

drtsans.mono.biosans.apply_calibrations(input_workspace, database=None, calibrations=['BARSCAN', 'TUBEWIDTH'], output_workspace=None)[source]

Load and apply pixel calibrations to an input workspace.

devs - Jose Borreguero <borreguerojm@ornl.gov>

Parameters:
  • input_workspace (str, MatrixWorkspace, IEventWorkspace) – Input workspace whose pixels are to be calibrated.

  • database (str, None) – Path to JSON file containing metadata for different past calibrations. If None, the default database is used. Currently, these are the default files: - BIOSANS, ‘/HFIR/CG3/shared/calibration/pixel_calibration.json’, - EQSANS, ‘/SNS/EQSANS/shared/calibration/pixel_calibration.json’, - GPSANS, ‘/HFIR/CG2/shared/calibration/pixel_calibration.json’

  • calibrations (str, list) – One or more of ‘BARSCAN’ and/or ‘TUBEWIDTH’.

  • output_workspace (str) – Name of the output workspace with calibrated pixels. If None, the pixels of the input workspace will be calibrated.

Return type:

MatrixWorkspace, IEventsWorkspace

drtsans.mono.biosans.apply_mask(input_workspace, mask=None, panel=None, **btp)[source]

Apply a mask to a workspace.

The function accepts a path to a mask file, a MaskWorkspace, or options to algorithm MaskBTP.

Parameters:
  • input_workspace (str, IEventWorkspace, MatrixWorkspace) – Workspace to be masked

  • mask (mask file path, ~mantid.api.MaskWorkspace, list) – Additional mask to be applied. If list, it is a list of detector ID’s. If None, it is expected that maskbtp is not empty.

  • panel (str) – Either ‘front’ or ‘back’ to mask a whole panel

  • btp (dict) – Options to Mantid algorithm MaskBTP or MaskAngle. Will be used if mask=None

drtsans.mono.biosans.apply_transmission_correction(input_workspace, trans_workspace=None, trans_value=None, trans_error=0.0, theta_dependent=True, output_workspace=None)[source]

Correct the intensities with transmission coefficient(s).

Mantid algorithms used: ApplyTransmissionCorrection ReplaceSpecialValues

Parameters:
  • input_workspace (str, MatrixWorkspace) – Input workspace to correct its intensities

  • trans_workspace (str, MatrixWorkspace) – Workspace containing the transmission coefficient(s). The result of applying calculate_transmission to the input workspace. If None, trans_value will be used.

  • trans_value (float) – A single transmission coefficient to correct the intensities. If None, trans_workspace will be used.

  • trans_error (float) – Error associated to trans_value.

  • theta_dependent (bool) – Flag to do theta dependent correction

  • output_workspace (str) – Name of the workspace containing the corrected intensities. If None, the input_workspace will be overwritten.

Return type:

MatrixWorkspace

drtsans.mono.biosans.as_intensities(input_workspace, component='detector1', views=['positions', 'heights', 'widths'])[source]

Returns one workspace for each pixel property that is calibrated (e.g., pixel height), and the calibration datum is stored as the intensity value for that pixel. Intended to visualize the calibration in MantidPlot’s instrument viewer. Not required for calibration generation or for data reduction.

Generated workspaces are `input_name_positions`, `input_name_heights`, and `input_name_widths`, where `input_name` is the name of the input workspace.

Note: Positions for visualization in Mantid’s instrument view are shifted so that the

lowest position (usually a negative number) becomes zero. The reason being that showing the instrument in Mantid will mask negative intensities, and we want to avoid this.

Mantid algorithms used: CreateWorkspace, <https://docs.mantidproject.org/algorithms/CreateWorkspace-v1.html> LoadEmptyInstrument, <https://docs.mantidproject.org/algorithms/LoadEmptyInstrument-v1.html> LoadInstrument, <https://docs.mantidproject.org/algorithms/LoadInstrument-v1.html>

Parameters:
  • input_workspace (str, MatrixWorkspace, IEventsWorkspace) – Workspace from which pixel properties are retrieved.

  • component (str, list) – Name or list of names for the double detector array panels. For BIOSANS we have ‘detector1’, ‘wing_detector’ or ‘midrange_detector’.

  • views (list) – Generate views for the pixel properties provided.

Returns:

A namedtuple containing the ~mantid.api.MatrixWorkspace workspaces with fields ‘positions’, ‘positions_mantid’, ‘heights’, and ‘widths’

Return type:

namedtuple

drtsans.mono.biosans.bin_all(i_qxqy, i_modq, nxbins, nybins, n1dbins=None, n1dbins_per_decade=None, bin1d_type='scalar', log_scale=False, decade_on_center=False, qmin=None, qmax=None, wedge1_qmin=None, wedge1_qmax=None, wedge2_qmin=None, wedge2_qmax=None, qxrange=None, qyrange=None, annular_angle_bin=1.0, wedges: List[Any] | None = None, symmetric_wedges: bool = True, error_weighted=False, n_wavelength_bin=1) Tuple[IQazimuthal, List[IQmod]][source]

Do all 1D and 2D binning for a configuration or detector

Parameters:
  • i_qxqy (IQazimuthal) – Object containing 2D unbinned data I(Qx, Qy). It will be used for 2D binned data, and 1D wedge or annular binned data

  • i_modq (IQmod) – Object containing 1D unbinned data I(|Q|). It will be used for scalar binned data

  • nxbins (int) – number of bins in the x direction for 2D binning

  • nybins (int) – number of bins in the y direction for 2D binning

  • n1dbins (int) – number of bins for the 1d binning.

  • n1dbins_per_decade (int) – Total number of bins will be this value multiplied by number of decades from X min to X max

  • bin1d_type (str) – type of binning for 1D data. Possible choices are ‘scalar’, ‘annular’, or ‘wedge’

  • log_scale (bool) – if True, 1D scalar or wedge binning will be logarithmic. Ignored for anything else

  • decade_on_center (bool) – Flag to have the min X and max X on bin center; Otherwise, they will be on bin boundary

  • qmin (float) – Minimum value of the momentum transfer modulus Q

  • qmax (float) – Maximum value of the momentum transfer modulus Q

  • wedge1_qmin (float) – Minimum value of the momentum transfer modulus Q for the first wedge when bin1d_type = 'wedge'

  • wedge1_qmax (float) – Maximum value of the momentum transfer modulus Q for the first wedge when bin1d_type = 'wedge'

  • wedge2_qmin (float) – Minimum value of the momentum transfer modulus Q for the second wedge when bin1d_type = 'wedge'

  • wedge2_qmax (float) – Maximum value of the momentum transfer modulus Q for the second wedge when bin1d_type = 'wedge'

  • qxrange (~tuple) – qx min and qx max

  • qyrange (~tuple) – qy min and qy max

  • annular_angle_bin (float) – width of annular bin in degrrees. Annular binning is linear

  • wedges (list) – list of tuples (angle_min, angle_max) for the wedges. Both numbers have to be in the [-90,270) range. It will add the wedge offset by 180 degrees dependent on symmetric_wedges

  • symmetric_wedges (bool) – It will add the wedge offset by 180 degrees if True

  • error_weighted (bool) – if True, the binning is done using the Weighted method

  • n_wavelength_bin (None, int) – None: keep original wavelength vector. int: number of wavelength bins. 1 to sum all

Returns:

binned IQazimuthal list of binned ~drtsans.dataobjects.IQmod objects. The list has length 1, unless the ‘wedge’ mode is selected, when the length is the number of original wedges

Return type:

(IQazimuthal, ~list)

drtsans.mono.biosans.bin_annular_into_q1d(i_of_q, theta_bin_params, q_min=0.001, q_max=0.4, method=BinningMethod.NOWEIGHT)[source]

Annular 1D binning

Calculates: I(azimuthal), sigma I and dazmuthal by assigning pixels to proper azimuthal angle bins Given I(Qx, Qy) and will convert to IQmod in the code. The independent axis is actually the azimuthal angle around the ring.

Parameters:
  • i_of_q (IQazimuthal) – I(Qx, Qy), sigma I(Qx, Qy), Qx, Qy, dQx and dQy

  • theta_bin_params (BinningParams) –

    binning parameters on annular angle ‘theta’

    theta_minfloat

    minimum value of theta/azimuthal angle

    theta_maxfloat

    maximum value of theta/azimuthal angle

    binsint or sequence of scalars, optional

    See scipy.stats.binned_statistic. If bins is an int, it defines the number of equal-width bins in the given range (10 by default). If bins is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths. Values in x that are smaller than lowest bin edge areassigned to bin number 0, values beyond the highest bin are assigned to bins[-1]. If the bin edges are specified, the number of bins will be, (nx = len(bins)-1).

  • q_min (float, optional) – , by default

  • q_max (float, optional) – , by default

  • method (BinningMethod) – binning method, no-weight or weighed

Returns:

Annular-binned I(azimuthal) in 1D

Return type:

drtsans.dataobjects.IQmod

drtsans.mono.biosans.bin_intensity_into_q1d(i_of_q, q_bins, bin_method=BinningMethod.NOWEIGHT, wavelength_bins=1) IQmod[source]

Binning I(Q) from scalar Q (1D) with linear binning on Q

Replace intensity, intensity_error, scalar_q, scalar_dq by IQmod Replace bins, q_min=None, q_max=None by BinningParams bins: number of bins for linear binning; step per decade for logarithm binning q_min : Default to min(scalar_q) q_max : Default to max(scalar_q)

Parameters:
  • i_of_q (IQmod) – Scalar I(Q) including intensity, intensity_error, scalar_q, scalar_dq in 1d nparray including: intensity error mod_q delta_mod_q

  • q_bins (Bins) – namedtuple for arbitrary bin edges and bin centers

  • bin_method (BinningMethod) – weighted binning or no-weight binning method

  • wavelength_bins (None, int) – number of binned wavelength. If None, do not bin. If equal to 1, bin all wavelength together

Returns:

the one dimensional data as a named tuple

Return type:

drtsans.dataobjects.IQmod

drtsans.mono.biosans.bin_intensity_into_q2d(i_of_q, qx_bins, qy_bins, method=BinningMethod.NOWEIGHT, wavelength_bins=1)[source]

Bin I(Qx, Qy) into to new (Qx, Qy) bins

Note 1: for binning parameters: - ‘min’: float or None. If None, set to default as min(Qx) (or Qy) - ‘max’: float or None. If None, set to default as max(Qx) (or Qy) - ‘bins’: integer as number of bins

Note 2: output Intensity, error, dqx an dqy are in following order - qx = [[qx0, qx1, …], [qx0, qx1, …], …] - qy = [[qy0, qy0, …], [qy1, qy1, …], …]

Parameters:
  • i_of_q (IQazimuthal) – class IQazimuthal(namedtuple(‘IQazimuthal’, ‘intensity error qx qy delta_qx delta_qy wavelength’))

  • qx_bins (Bins) – namedtuple for arbitrary bin edges and bin centers for Qx

  • qy_bins (Bins) – namedtuple for arbitrary bin edges and bin centers for Qy

  • method (BinningMethod) – Weighted binning or no weight binning

  • wavelength_bins (None, int) – number of binned wavelength. If None, do not bin. If equal to 1, bin all wavelength together

Returns:

binned IQazimuthal (important: must read Note 2)

Return type:

IQazimuthal

drtsans.mono.biosans.calculate_apparent_tube_width(flood_input, component='detector1', load_barscan_calibration=True, db_file=None)[source]

Determine the tube width most efficient for detecting neutrons. An effective tube (or pixel) diameter is determined for tubes in the front panel, and likewise for the tubes in the back panel.

devs - Jose Borreguero <borreguerojm@ornl.gov>

Mantid algorithms used: DeleteWorkspaces, Integration, MaskDetectors, MaskDetectorsIf, ReplaceSpecialValues,

Parameters:
  • flood_input (str, IEventWorkspace, MatrixWorkspace) – Path to flood run, flood workspace name, or flood workspace object.

  • component (str) – Name of the instrument component containing the detector array consisting of two parallel panels of tubes.

  • load_barscan_calibration (bool) – Load pixel positions and heights from the pixel-calibrations database appropriate to `input_workspace`. If False, then the pixel positions and heigths will be those of `input_workspace`.

  • db_file (str, None) – database file (json format). None will load the default database for the selected instrument. Otherwise the combination load_barscan_calibration=True, db_file=None may come across as some data contradictory

Returns:

Dictionary containing the following keys: - instrument, str, Standard name of the instrument. - component, str, name of the double detector array, usually “detector1”. - run, int, run number of input_workspace. - unit: str, the units for the tube widths. Set to ‘mm’ for mili-meters. - widths, list, A two-item list containing the apparent widths for the front and back tubes.

Return type:

dict

drtsans.mono.biosans.calculate_barscan_calibration(barscan_dataset, component='detector1', bar_position_log='dcal_Readback', formula=None, order=5, mask=None, inspect_data=False, permissive_fit=False)[source]

Calculate pixel positions (only Y-coordinae) as well as pixel heights from a barscan calibration session.

Mantid Algorithms used: Load,

devs - Andrei Savici <saviciat@ornl.gov>,

Jose Borreguero <borreguerojm@ornl.gov>

Parameters:
  • barscan_dataset (str, list) – Path(s) to barscan run file(s), or list of workspaces. If only one file, it should contain multiple positions of the bar. If a list of files, then each file contains the pixel_intensities recorded with a constant position for the bar. If a list of workspaces, each workspace must contain the same information as when passing a list of files.

  • component (str) – Name of the detector panel scanned with the bar. Usually, ‘detector1`.

  • bar_position_log (str) – Name of the log entry in the barscan run file containing the position of the bar (Y-coordinate, in ‘mm’) with respect to some particular frame of reference, not necessarily the one located at the sample.

  • formula (str) – Formula to obtain the position of the bar (Y-coordinate) in the frame of reference located at the sample.

  • order (int) – Highest degree for the polynomial that will fit the observed positions of the bar.

  • mask (mask file path, ~mantid.api.MaskWorkspace, list) – A mask to be applied. If list, it is a list of detector ID’s.

  • inspect_data (Bool) – Additional pieces of data returned by this function in order to assess the correctness of the barscan calculation. These data are returned as a dictionary with the current entries: - bar_positions: list of Y-coordinates of the bar for each scan holding the bar at a particular position. - bar workspaces: list of ~mantid.api.MatrixWorkspace objects, each containing the bar at a particular position. - bottom_shadow_pixels: ~numpy.ndarray of shape (number of scans, number of tubes) listing the indexes for the pixels shadowed by the lower portion of the bar.

  • permissive_fit (bool) – If True, then fitted positions and heights are allowed to be non-physical. Only for debugging.

Returns:

If `inspect_data` is False, only a table object is returned. Otherwise a tube is returned where the first component is the table, and the second item is a dictionary with the additional pieces of data.

Return type:

Table, dict

drtsans.mono.biosans.calculate_solid_angle(input_workspace, detector_type='VerticalTube', output_workspace=None, **kwargs)[source]

Calculate the solid angle from the input_workspace.

Mantid algorithms used: SolidAngle

Parameters:
  • input_workspace (str, IEventWorkspace, MatrixWorkspace) – Input workspace to be normalized by the solid angle.

  • detector_type (str) – Select the method to calculate the Solid Angle. Allowed values: [‘GenericShape’, ‘Rectangle’, ‘VerticalTube’, ‘HorizontalTube’, ‘VerticalWing’, ‘HorizontalWing’]

  • output_workspace (str) – Optional name of the output workspace. if None, the name created is <instrument>_solid_angle

  • kwargs (dict) – Additional arguments to Mantid algorithm SolidAngle

Return type:

IEventWorkspace, MatrixWorkspace

drtsans.mono.biosans.calculate_transmission(input_sample, input_reference, radius=None, radius_unit='mm', output_workspace=None)[source]
drtsans.mono.biosans.center_detector(input_workspace, center_x, center_y, center_y_wing, center_y_midrange=None)[source]

Center the detector and adjusts the height for the main wing and midrange detectors This uses drtsans.center_detector()

Mantid algorithms used: MoveInstrumentComponent

Parameters:
  • input_workspace (MatrixWorkspace, str) – The workspace to be centered

  • center_x (float) – The x-coordinate of the beam center in meters

  • center_y (float) – The y-coordinate of the beam center on the main detector in meters

  • center_y_wing (float) – The y-coordinate of the beam center on the wing detector in meters

  • center_y_midrange (float) – The y-coordinate of the beam center on the midrange detector in meters

Returns:

reference to the corrected input_workspace

Return type:

MatrixWorkspace

drtsans.mono.biosans.check_iq_for_binning(i_of_q)[source]

Check I(Q) for binning.

Binning I(Q) assumes that 1. there is no NaN or Infinity in intensities 2. there is no NaN, Infinity or Zero in intensity errors

:exceptionRuntimeError

raise exception if input I(Q) does not meet assumption

Parameters:

i_of_q – ~drtsans.dataobjects.IQmod or IQazimuthal I(Q)

drtsans.mono.biosans.circular_mask_from_beam_center(input_workspace, radius, unit='mm')[source]

Find the detectors ID’s within a certain radius from the beam center

Parameters:
  • input_workspace (MatrixWorkspace) – Workspace containing the detector already beam-centered

  • radius (float) – Radius of the circle encompassing the detectors of interest.

  • unit (str) – Either ‘mm’ or ‘m’, unit of the radius option.

Returns:

List of detector ID’s

Return type:

numpy.ndarray

drtsans.mono.biosans.convert_to_q(ws, mode, resolution_function=<function mono_resolution>, **kwargs)[source]

Convert a workspace with units of wavelength into a series of arrays: intensity, error, q (or q components), delta q (or delta q components), and wavelength

Using the scattering angle as \(2\theta\) and azimuthan angle as \(\phi\),the calculaion of momentum transfer is:

  • ‘scalar’ mode:

\[|Q| = \frac{4\pi}{\lambda}\sin\theta\]
  • ‘azimuthal’ mode:

\[ \begin{align}\begin{aligned}Q_x=\frac{4\pi}{\lambda}\sin\theta\cos\phi\\Q_y=\frac{4\pi}{\lambda}\sin\theta\sin\phi\end{aligned}\end{align} \]
  • ‘crystallographic’ mode:

\[ \begin{align}\begin{aligned}Q_x=\frac{2\pi}{\lambda}\sin(2\theta)\cos\phi\\Q_y=\frac{2\pi}{\lambda}\sin(2\theta)\sin\phi\\Qz_=\frac{2\pi}{\lambda}(\cos(2\theta)-1)\end{aligned}\end{align} \]

It calls drtsans.momentum_transfer.convert_to_q

Parameters:
  • ws (str, IEventWorkspace, MatrixWorkspace) – Workspace in units of wavelength

  • mode (str) – Available options are ‘scalar’, ‘azimuthal’, and ‘crystallographic’

  • resolution_function – Function to calculate resolution

  • kwargs – Parameters to be passed to the resolution function

Returns:

A namedtuple with fields for

  • intensity

  • error

  • mod_q (\(|Q|\)) or qx, qy (\(Q_x, Q_y\)) or qx, qy, qz (\(Q_x, Q_y, Q_z\)) (depending on the mode)

  • delta_q or delta_qx, delta_qy or delta_qx, delta_qy, delta_qz - the resolution along the q components

  • wavelength

Return type:

namedtuple

drtsans.mono.biosans.day_stamp(input_workspace)[source]

Find the day stamp (e.g 20200311 for March 11, 2020) using the “start_time” metadata from the Nexus events file as input.

devs - Jose Borreguero <borreguerojm@ornl.gov>

Parameters:

input_workspace (str, MatrixWorkspace, IEventsWorkspace) – Workspace from which the day stamp is to be retrieved.

Return type:

int

drtsans.mono.biosans.determine_1d_linear_bins(x_min, x_max, bins)[source]

Determine linear bin edges and centers

Parameters:
  • x_min (float) – Q min of bin edge

  • x_max (float or None) – Q max of bin edge

  • bins (integer) – number of bins

Returns:

Bins including bin centers and bin edges

Return type:

Bins

drtsans.mono.biosans.determine_1d_log_bins(x_min, x_max, decade_on_center, n_bins_per_decade=None, n_bins=None)[source]
Parameters:
  • x_min (float) – minimum value of X in the bins

  • x_max (float) – maximum value of X in the bins

  • decade_on_center (bool) – flag that data must be centered on decades

  • n_bins_per_decade (int, None) – density of points (number of data points per decade)

  • n_bins (int, None) – total number of points in the output

drtsans.mono.biosans.empty_beam_scaling(input_workspace, empty_beam_workspace, beam_radius=None, unit='mm', attenuator_coefficient=1.0, attenuator_error=0.0, output_workspace=None)[source]

Normalize input workspace by the intensity impinging on the detector for an empty beam run, taking into account attenuation.

Mantid Algorithms used: Divide, DeleteWorkspace,

Parameters:
  • input_workspace (str, MatrixWorkspace, IEventsWorkspace) – Workspace to be normalized

  • empty_beam_workspace (str, MatrixWorkspace, IEventsWorkspace) – Attenuated intensities collected at the detector with and empty beam.

  • beam_radius (float) – Radius of the beam at the detector. If None, it will be estimated with the sample and source apertures.

  • unit (str) – Units for the beam radius, either meters (‘m’) or mili-miters (‘mm’).

  • attenuator_coefficient (float) – Fraction of the neutrons allowed to pass through the attenuator. Assumed wavelength independent.

  • attenuator_error (float) – Estimated error for the attenuator coefficient.

  • output_workspace (str) – Name of the normalized workspace. If None, then the name of input_workspace will be used, thus overwriting input_workspace.

Return type:

MatrixWorkspace, IEventsWorkspace

drtsans.mono.biosans.exists(path)[source]

Test whether a path exists. Returns False for broken symbolic links

In addition to fully supporting what os.path.exists does, this also supports path strings in such as EQSANS_106026 and EQSANS106026. It will search your data search path and the data archive using ONCat.

This uses mantid.api.FileFinder.

drtsans.mono.biosans.fbc_options_json(reduction_input)[source]
drtsans.mono.biosans.find_beam_center(input_workspace, method='center_of_mass', mask=None, mask_options={}, centering_options={}, sample_det_cent_main_detector=None, sample_det_cent_wing_detector=None, sample_det_cent_midrange_detector=None, solid_angle_method='VerticalTube') Tuple[float, float, float, float, dict][source]

Finds the beam center in a 2D SANS data set.

This is based on (and uses) drtsans.find_beam_center()

Parameters:
  • input_workspace (str, MatrixWorkspace, IEventWorkspace)

  • method (str) – Method to calculate the beam center. Available methods are: - ‘center_of_mass’, invokes FindCenterOfMassPosition.

  • mask (mask file path, MaskWorkspace`, list.) – Mask to be passed on to ~drtsans.mask_utils.mask_apply.

  • mask_options (dict) – Additional arguments to be passed on to ~drtsans.mask_utils.mask_apply.

  • centering_options (dict) – Arguments to be passed on to the centering method.

  • sample_det_cent_wing_detector (float) – sample to detector center distance, in meters, of the wing detector.

  • solid_angle_method (bool, str specify which solid angle correction is needed)

Returns:

  • (center_x, center_y, center_y_wing, center_y_midrange, fit_results) where

    • center_y_wing is used to correct BIOSANS wing detector Y position.

    • center_y_midrange is used to correct BIOSANS midrange detector Y position. – if sample_det_cent_midrange_detector is specified then a float number is returned, else None.

    • fit_results produced by fitting the beam center intensities to a 2D Gaussian model of the lmfit package

drtsans.mono.biosans.load_all_files(reduction_input: dict, prefix: str = '', load_params: dict = {}, path: str = None, use_nexus_idf: bool = False, debug_output: bool = False) dict[source]

Load all required files at the beginning, and transform them into histograms.

Parameters:
  • reduction_input (dict) – Dictionary containing the reduction input

  • prefix (str) – Prefix to be used for the workspaces

  • load_params (dict) – Dictionary containing the parameters to be passed to the Load event algorithm

  • path (str) – Additional path to search the for NeXus files

  • use_nexus_idf (bool) – Flag to enforce to use IDF from NeXus file. It must be true for SPICE-converted NeXus

  • debug_output (bool) – Flag to save internal data for debugging

Returns:

Dictionary containing the configuration used to load the workspaces

Return type:

dict

drtsans.mono.biosans.load_and_split(run, sample_to_si_name, si_nominal_distance, data_dir=None, output_workspace=None, output_suffix='', overwrite_instrument=True, pixel_calibration=False, time_interval: float | List[float] | None = None, time_offset: float = 0.0, time_period: float | None = None, log_name=None, log_value_interval=None, sample_to_si_value=None, sample_detector_distance_value=None, reuse_workspace=False, monitors=False, **kwargs)[source]

Load an event NeXus file and filter into a WorkspaceGroup depending on the provided filter options. Either a time_interval must be provided or a log_name and log_value_interval.

Metadata added to output workspace includes the slice number, number_of_slices, slice_parameter, slice_interval, slice_start and slice_end.

For EQSANS two WorkspaceGroup’s are return, one for the filtered data and one for filtered monitors

Parameters:
  • run (str, IEventWorkspace) – Examples: CG3_55555, CG355555 or file path.

  • sample_to_si_name (str) – Meta data name for sample to Silicon window distance

  • si_nominal_distance (float) – distance between nominal position to silicon window. unit = meter

  • data_dir (str, list) – Additional data search directories

  • output_workspace (str) – If not specified it will be BIOSANS_55555 determined from the supplied value of run.

  • output_suffix (str) – If the output_workspace is not specified, this is appended to the automatically generated output workspace name.

  • overwrite_instrument (bool, str) – If not False, ignore the instrument embedeed in the Nexus file. If True, use the latest instrument definition file (IDF) available in Mantid. If str, then it should be the filepath to the desired IDF.

  • pixel_calibration (bool) – Adjust pixel heights and widths according to bar-scan and tube-width calibrations.

  • time_interval – Array for lengths of time intervals for splitters. If the array has one value, then all splitters will have same time intervals. If the size of the array is larger than one, then the splitters can have various time interval values.

  • time_offset – Offset to be added to the start time of the first splitter, in seconds.

  • time_period – A multiple integer of the time interval. If specified, it indicates that the time slicing is periodic so that events in time intervals separated by one (or more) period should be reduced together.

  • sample_to_si_value (float or None) – Sample to silicon window distance to overwrite the EPICS value. None for no operation. unit = meter

  • sample_detector_distance_value (float or None) – Sample to detector distance to overwrite the EPICS value. None for no operation. unit = meter

  • log_name (string) – Name of the sample log to use to filter. For example, the pulse charge is recorded in ‘ProtonCharge’.

  • log_value_interval (float) – Delta of log value to be sliced into from min log value and max log value.

  • reuse_workspace (bool) – When true, return the output_workspace if it already exists

  • monitors (bool) – flag to load monitors

  • kwargs (dict) – Additional positional arguments for LoadEventNexus.

Returns:

Reference to the workspace groups containing all the split workspaces

Return type:

WorkspaceGroup

drtsans.mono.biosans.load_calibration(input_workspace, caltype, component='detector1', database=None, output_workspace=None)[source]

Load a calibration into a ~drtsans.pixel_calibration.Table object.

devs - Jose Borreguero <borreguerojm@ornl.gov>

Parameters:
  • input_workspace (str, MatrixWorkspace, IEventsWorkspace) – Workspace from which calibration session is to be retrieved.

  • caltype (str) – Either ‘BARSCAN’ or ‘TUBEWIDTH’. A saved calibration can only contain one of these, but not both.

  • component (str) – Name of one of the double detector array panels. For BIOSANS we have ‘detector1’, ‘wing-detector’ or ‘midrange_detector’

  • database (str) – Path to database file containing the metadata for the calibrations. If None, the default database is used. Currently, these are the default files: - BIOSANS, ‘/HFIR/CG3/shared/calibration/pixel_calibration.json’, - EQSANS, ‘/SNS/EQSANS/shared/calibration/pixel_calibration.json’, - GPSANS, ‘/HFIR/CG2/shared/calibration/pixel_calibration.json’

  • output_workspace (str) – Name of the table workspace containing the calibration session values. If None, then a composite name is created using the calibration type, instrument, component, and daystamp. (e.g. “barscan_gpsans_detector1_20200311”)

Return type:

Table

drtsans.mono.biosans.load_dark_current_workspace(dark_current_filename, output_workspace)[source]

Loads dark current workspace. Useful to avoid multiple loads from disk.

Mantid algorithms used: LoadEventNexus,

Parameters:
  • dark_current_filename (str) – file containing previously calculated sensitivity correction

  • output_workspace (int, str) – run number or file path for dark current

drtsans.mono.biosans.load_events(run, data_dir=None, output_workspace=None, overwrite_instrument=True, output_suffix='', pixel_calibration=False, detector_offset=0.0, sample_offset=0.0, reuse_workspace=False, **kwargs)[source]

Load an event Nexus file produced by the instruments at ORNL.

Parameters:
  • run (str, IEventWorkspace) – Examples: CG3_55555, CG355555 or file path.

  • output_workspace (str) – If not specified it will be BIOSANS_55555 determined from the supplied value of run.

  • data_dir (str, list) – Additional data search directories

  • overwrite_instrument (bool, str) – If not False, ignore the instrument embedeed in the Nexus file. If True, use the latest instrument definition file (IDF) available in Mantid. If str, then it should be the filepath to the desired IDF.

  • output_suffix (str) – If the output_workspace is not specified, this is appended to the automatically generated output workspace name.

  • pixel_calibration (bool, str) – Adjust pixel heights and widths according to bar-scan and tube-width calibrations. Options are (1) No calibration (2) Using default calibration file (True) and (3) User specified calibration file (str)

  • detector_offset (float) – Additional translation of the detector along the Z-axis, in mm. Positive moves the detector downstream.

  • sample_offset (float) – Additional translation of the sample, in mm. The sample flange remains at the origin of coordinates. Positive moves the sample downstream.

  • reuse_workspace (bool) – When true, return the output_workspace if it already exists

  • kwargs (dict) – Additional positional arguments for LoadEventNexus.

Returns:

Reference to the events workspace

Return type:

IEventWorkspace

drtsans.mono.biosans.load_events_and_histogram(run, data_dir=None, output_workspace=None, output_suffix='', overwrite_instrument=True, pixel_calibration=False, reuse_workspace=False, sample_to_si_name=None, si_nominal_distance=None, sample_to_si_value=None, sample_detector_distance_value=None, **kwargs)[source]

Load one or more event Nexus file produced by the instruments at HFIR. Convert to wavelength and sums the data.

Parameters:
  • run (str, list of runs to load) – Examples: CG3_55555, CG355555, file path, CG3_55555,CG3_55556

  • data_dir (str, list) – Additional data search directories

  • output_workspace (str) – If not specified it will be BIOSANS_55555 determined from the supplied value of run.

  • output_suffix (str) – If the output_workspace is not specified, this is appended to the automatically generated output workspace name.

  • overwrite_instrument (bool, str) – If not False, ignore the instrument embedeed in the Nexus file. If True, use the latest instrument definition file (IDF) available in Mantid. If str, then it should be the filepath to the desired IDF.

  • pixel_calibration (bool) – Adjust pixel heights and widths according to bar-scan and tube-width calibrations.

  • sample_to_si_name (str) – Meta data name for sample to Silicon window distance

  • si_nominal_distance (float) – distance between nominal position to silicon window. unit = meter

  • sample_to_si_value (float or None) – Sample to silicon window distance to overwrite the EPICS value. None for no operation. unit = meter

  • sample_detector_distance_value (float or None) – Sample to detector distance to overwrite the EPICS value. None for no operation. unit = meter

  • reuse_workspace (bool) – When true, return the output_workspace if it already exists

  • kwargs (dict) – Additional positional arguments for LoadEventNexus.

Return type:

MatrixWorkspace

drtsans.mono.biosans.load_histogram(filename, output_workspace=None, wavelength=None, wavelength_spread=None, sample_det_cent=None)[source]

Loads a SANS data file produce by the HFIR instruments at ORNL. The instrument geometry is also loaded. The center of the detector is placed at (0, 0, sample_det_cent )

Parameters:
  • filename (str) – The name of the input xml file to load

  • output_workspace (str, optional) – The optional name of the output workspace. If None is the filename stripped of the extension.

  • wavelength (float) – The wavelength value to use when loading the data file (Angstrom). This value will be used instead of the value found in the data file.

  • wavelength_spread (float) – wavelength spread value to use when loading the data file (Angstrom). This value will be used instead of the value found in the data file.

  • sample_det_cent (float) – Sample to detector distance to use (overrides meta data) in mm

Returns:

A reference for the workspace created.

Return type:

MatrixWorkspace

drtsans.mono.biosans.load_iqmod(file, sep=' ', header_type='Pandas')[source]

Load an intensity profile into a ~drtsans.dataobjects.IQmod object.

Required file format: The first row must include the names for the file columns. The order of the columns is irrelevant and the names of the columns must be: - ‘intensity’ for profile intensities. This column is required. - ‘error’ for uncertainties in the profile intensities. This column is required. - ‘mod_q’ for values of Q. This column is required. - ‘delta_mod_q’ for uncertainties in the Q values. This column is optional. - ‘wavelength’ This column is optional.

Example of file contents:

intensity error mod_q 1000.0 89.0 0.001 90.0 8.0 0.01 4.7 0.9 0.1

Usage example: ` from drtsans.mono.gpsans import load_iqmod iq = load_iqmod(file_name) `

Parameters:
  • file (str) – Path to input file

  • sep (str) – String of length 1. Field delimiter in the input file.

Return type:

IQmod

drtsans.mono.biosans.load_mono(filename, **kwargs)[source]

Loads a SANS data file produce by the HFIR instruments at ORNL.

Parameters:
  • filename (int, str) – Examples: 55555 or CG3_55555 or file path.

  • kwargs – keyword arguments for load_events or load_histogram.

Return type:

MatrixWorkspace

drtsans.mono.biosans.normalize_by_flux(ws, method)[source]

Normalize to time or monitor

Parameters:
  • input_workspace (MatrixWorkspace)

  • method (str) – Normalization method: ‘time’ or ‘monitor’

drtsans.mono.biosans.normalize_by_monitor(input_workspace, output_workspace=None)[source]

Normalize by the monitor value

Mantid algorithms used: :ref: CreateSingleValuedWorkspace <algm-CreateSingleValuedWorkspace-v1> :ref:`Divide <algm-Divide-v1>,

Parameters:
  • input_workspace (MatrixWorkspace)

  • output_workspace (str) – Optional name of the output workspace. Default is to replace the input workspace

Returns:

the normalized input workspace

Return type:

MatrixWorkspace

Raises:

RuntimeError – No monitor metadata found in the sample logs of the input workspace

drtsans.mono.biosans.normalize_by_thickness(input_workspace, thickness)[source]

Normalize input workspace by thickness

Parameters:
Return type:

MatrixWorkspace

drtsans.mono.biosans.normalize_by_time(input_workspace, output_workspace=None)[source]

Normalize by time Used to normalize dark current

Mantid algorithms used: Divide,

Parameters:
  • input_workspace (MatrixWorkspace)

  • output_workspace (str) – Optional name of the output workspace. Default is to replace the input workspace

drtsans.mono.biosans.normalize_dark_current(dark_workspace, output_workspace=None)[source]

Divide a dark current workspace by its duration.

Entry ‘normalizing_duration’ is added to the logs of the normalized dark current to annotate what log entry was used to find the duration

Mantid algorithms used: Scale, DeleteWorkspace,

Parameters:
  • dark_workspace (str, MatrixWorkspace) – Dark current workspace

  • output_workspace (str) – Name of the normalized dark workspace. If None, the name of the input workspace dark_workspace is chosen (and the input workspace is overwritten).

Returns:

Output workspace

Return type:

MatrixWorkspace

drtsans.mono.biosans.plot_IQazimuthal(workspace, filename, backend: str = 'd3', qmin: float | None = None, qmax: float | None = None, wedges: List[Any] | None = None, symmetric_wedges: bool = True, mask_alpha=0.6, imshow_kwargs: Dict = {}, **kwargs)[source]

Save a plot of I(Qx, Qy). If qmin is specified, all I(Q) with Q less than qmin will be masked in output plot. If qmax is specified, all I(Q) with Q greater than qmax will be masked in output plot. If wedges are specified, all I(Q) out side of wedges will be masked in output plot.

Parameters:
  • workspace (IQazimuthal) – The workspace (i.e., I(Qx, Qy)) to plot. This assumes the data is binned on a constant grid.

  • filename (str) – The name of the file to save to. For the MATPLOTLIB backend, the type of file is determined from the file extension

  • qmin (float) – minimum 1D Q for plotting selection area

  • qmax (float) – maximum 1D Q for plotting selection area

  • wedges (~list or None) – list of tuples (angle_min, angle_max) for the wedges. Select wedges to plot. Both numbers have to be in the [-90,270) range. It will add the wedge offset by 180 degrees dependent on symmetric_wedges

  • symmetric_wedges (bool) – Add the wedge offset by 180 degrees if True

  • mask_alpha (float) – Opacity for for selection area

  • backend – Which backend to save the file using

  • imshow_kwargs (~dict) – Optional arguments to matplotlib.axes.Axes.imshow e.g. {"norm": LogNorm()}

  • kwargs (~dict) – Additional key word arguments for matplotlib.axes.Axes

drtsans.mono.biosans.plot_IQmod(workspaces, filename, loglog=True, backend: str = 'd3', errorbar_kwargs={}, **kwargs)[source]

Save a plot representative of the supplied workspaces

Parameters:
  • workspaces (list, tuple) – A collection of IQmod workspaces to plot. If only one is desired, it must still be supplied in a list or tuple.

  • filename (str) – The name of the file to save to. For the MATPLOTLIB backend, the type of file is determined from the file extension

  • loglog (bool) – If true will set both axis to logarithmic, otherwise leave them as linear

  • backend – Which backend to save the file using

  • errorbar_kwargs (dict) – Optional arguments to matplotlib.axes.Axes.errorbar Can be a comma separated list for each workspace e.g. {'label':'main,wing,both', 'color':'r,b,g', 'marker':'o,v,.'}

  • kwargs (dict) – Additional key word arguments for matplotlib.axes.Axes

drtsans.mono.biosans.plot_detector(input_workspace, filename=None, backend: str = 'd3', axes_mode='tube-pixel', panel_name=None, figure_kwargs={'figsize': (8, 6)}, imshow_kwargs={'norm': <matplotlib.colors.LogNorm object>})[source]

Save a 2D plot representative of the supplied workspace

Parameters:
  • input_workspace (str, MatrixWorkspace) – The workspace to plot

  • filename (str) – The name of the file to save to. For the MATPLOTLIB backend, the type of file is determined from the file extension

  • backend – Which backend to save the file using

  • axes_mode (str) – Plot intensities versus different axes. Options are: ‘xy’ for plotting versus pixel coordinates; ‘tube-pixel’ for plotting versus tube and pixel index.

  • panel_name (str) – Name of the double panel detector array. If None, plots will be generated for all arrays.

  • figure_kwargs (str) – Optional arguments to matplotlib.pyplot.figure

  • imshow_kwargs (dict) – Optional arguments to matplotlib.axes.Axes.imshow

drtsans.mono.biosans.plot_reduction_output(reduction_output: list, reduction_input: dict, loglog: bool = True, imshow_kwargs: dict = {})[source]

Generate reduction plot per slice per detector.

Parameters:
  • reduction_output – List of 1D and 2D I(Q) profile objects, for each detector panel

  • reduction_input – Dictionary of all possible options to properly configure the data reduction workflow.

  • loglog – Whether to plot in loglog scale, by default True.

  • imshow_kwargs – Keyword arguments to pass to imshow, by default {}.

drtsans.mono.biosans.prepare_data(data, data_dir=None, pixel_calibration=False, mask_detector=None, detector_offset=0, sample_offset=0, center_x=None, center_y=None, center_y_wing=None, center_y_midrange=None, dark_current=None, flux_method=None, monitor_fail_switch=False, mask=None, mask_panel=None, btp={}, solid_angle=True, sensitivity_file_path=None, sensitivity_workspace=None, wave_length=None, wavelength_spread=None, sample_aperture_diameter=None, sample_thickness=None, source_aperture_diameter=None, smearing_pixel_size_x=None, smearing_pixel_size_y=None, output_workspace=None, output_suffix='', **kwargs)[source]

Load a BIOSANS data file and bring the data to a point where it can be used. This includes applying basic corrections that are always applied regardless of whether the data is background or scattering data.

Parameters:
  • data (int, str, IEventWorkspace) – Run number as int or str, file path, IEventWorkspace

  • data_dir (str, list) – Additional data search directories

  • pixel_calibration (bool) – Adjust pixel heights and widths according to barscan and tube-width calibrations.

  • mask_detector (str, list) – Name of one or more instrument components to mask: (e.g detector1,wing_detector)

  • detector_offset (float) – Additional translation of the detector along Z-axis, in mili-meters.

  • sample_offset (float) – Additional translation of the sample along the Z-axis, in mili-meters.

  • center_x (float) – Move the center of the detector to this X-coordinate. If None, the detector will be moved such that the X-coordinate of the intersection point between the neutron beam and the detector array will have x=0.

  • center_y (float) – Move the center of the detector to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • center_y_wing (float) – Move the center of the wing detector to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • center_y_midrange (float) – Move the center of the detector vertically to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • dark_current (int, str, IEventWorkspace) – Run number as int or str, file path, IEventWorkspace

  • flux_method (str) – Method for flux normalization. Either ‘monitor’, or ‘time’.

  • monitor_fail_switch (bool) – Resort to normalization by ‘time’ if ‘monitor’ was selected but no monitor counts are available

  • panel (str) – Either ‘front’ or ‘back’ to mask a whole panel

  • mask_panel (str) – Either ‘front’ or ‘back’ to mask whole front or back panel.

  • mask (mask file path, MaskWorkspace, list) – Additional mask to be applied. If list, it is a list of detector ID’s.

  • btp (dict) – Additional properties to Mantid’s MaskBTP algorithm

  • solid_angle (bool) – Apply the solid angle correction

  • sensitivity_file_path (str) – file containing previously calculated sensitivity correction

  • sensitivity_workspace (str, MatrixWorkspace) – workspace containing previously calculated sensitivity correction. This overrides the sensitivity_filename if both are provided.

  • wave_length (float, None) – wave length in Angstrom

  • wavelength_spread (float, None) – wave length spread in Angstrom

  • sample_aperture_diameter (float, None) – sample aperture diameter in mm

  • sample_thickness (None, float) – sample thickness in unit cm

  • source_aperture_diameter (float, None) – source aperture size radius in unit mm

  • smearing_pixel_size_x (float, None) – pixel size in x direction in unit as meter, only for Q-resolution calculation

  • smearing_pixel_size_y (float, None) – pixel size in Y direction in unit as meter, only for Q-resolution calculation

  • output_workspace (str) – Name of the output workspace. If not supplied, will be determined from the supplied value of data.

  • output_suffix (str) – If the output_workspace is not specified, this is appended to the automatically generated output workspace name.

Returns:

Reference to the events workspace

Return type:

IEventWorkspace

drtsans.mono.biosans.prepare_data_workspaces(data, center_x=None, center_y=None, center_y_wing=None, center_y_midrange=None, dark_current=None, flux_method=None, monitor_fail_switch=False, mask_ws=None, mask_detector=None, mask_panel=None, mask_btp=None, solid_angle=True, sensitivity_workspace=None, output_workspace=None)[source]

Given a “ raw”data workspace, this function provides the following:

  • centers the detector

  • subtracts dark current

  • normalize by time or monitor

  • applies masks

  • corrects for solid angle

  • corrects for sensitivity

All steps are optional. data, mask_ws, dark_current are either None or histogram workspaces. This function does not load any file.

Parameters:
  • data (Workspace2D) – raw workspace (histogram)

  • center_x (float) – Move the center of the detector to this X-coordinate. If None, the detector will be moved such that the X-coordinate of the intersection point between the neutron beam and the detector array will have x=0.

  • center_y (float) – Move the center of the detector to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • center_y_wing (float) – Move the center r of the detector to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • center_y_midrange (float) – Move the center of the detector vertically to this Y-coordinate. If None, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will have y=0.

  • dark_current (Workspace2D) – histogram workspace containing the dark current measurement

  • flux_method (str) – Method for flux normalization. Either ‘monitor’, or ‘time’.

  • monitor_fail_switch (bool) – Resort to normalization by ‘time’ if ‘monitor’ was selected but no monitor counts are available

  • mask_ws (Workspace2D) – Mask workspace

  • mask_detector (str, list) – Name of one or more instrument components to mask: (e.g detector1,wing_detector)

  • mask_panel (str) – Either ‘front’ or ‘back’ to mask whole front or back panel.

  • mask_btp (dict) – Additional properties to Mantid’s MaskBTP algorithm

  • solid_angle (bool) – Apply the solid angle correction

  • sensitivity_workspace (str, MatrixWorkspace) – workspace containing previously calculated sensitivity correction. This overrides the sensitivity_filename if both are provided.

  • output_workspace (str) – The output workspace name. If None will create data.name()+output_suffix

Returns:

Reference to the processed workspace

Return type:

Workspace2D

drtsans.mono.biosans.process_single_configuration(sample_ws_raw: str | Workspace2D, sample_trans_ws: Workspace2D | None = None, sample_trans_value: float | None = None, bkg_ws_raw: Workspace2D | None = None, bkg_trans_ws: Workspace2D | None = None, bkg_trans_value: float | None = None, blocked_ws_raw: Workspace2D | None = None, theta_dependent_transmission: bool = True, center_x: float | None = None, center_y: float | None = None, center_y_wing: float | None = None, center_y_midrange: float | None = None, dark_current: Workspace2D | None = None, flux_method: str | None = None, monitor_fail_switch: bool = False, mask_ws: Workspace2D | None = None, mask_detector: str | List | None = None, mask_panel: str | None = None, mask_btp: dict | None = None, solid_angle: bool = True, sensitivity_workspace: Workspace2D | None = None, thickness: float = 1.0, absolute_scale_method: str = 'standard', absolute_scale: float = 1.0, keep_processed_workspaces: bool = True, output_workspace: str | None = None, output_prefix: str = '')[source]

This function provides full data processing for a single experimental configuration, starting from workspaces (no data loading is happening inside this function)

Steps applied to the sample and background workspaces: 1. centering the detector 2. dark current subtraction 3. normalization by time or monitor 4. masking 5. solid angle correction 6. sensitivity correction 7. transmission correction

Additional steps applied to the sample workspace: 1. background subtraction 2. thickness correction 3. absolute scaling

Parameters:
  • sample_ws_raw – raw data histogram workspace, or a string with the workspace name

  • sample_trans_ws – optional histogram workspace for sample transmission

  • sample_trans_value – optional value for sample transmission

  • bkg_ws_raw – optional raw histogram workspace for background

  • bkg_trans_ws – optional histogram workspace for background transmission

  • bkg_trans_value – optional value for background transmission

  • blocked_ws_raw – optional histogram workspace for blocked beam

  • theta_dependent_transmission (bool) – flag to apply angle dependent transmission

  • center_x – x center for the beam

  • center_y – y center for the beam

  • center_y_wing – y center for the wing detector

  • center_y_midrange – y center for the midrange detector

  • dark_current – dark current workspace

  • flux_method – normalization by ‘time’ or ‘monitor’

  • monitor_fail_switch – resort to normalization by ‘time’ if ‘monitor’ was selected but no monitor counts are available

  • mask_ws – user-defined mask

  • mask_detector – Name of one or more instrument components to mask: (e.g wing_detector,midrange_detector)

  • mask_panel – mask front or back panel of tubes

  • mask_btp – optional bank, tube, pixel to mask. These are options passed as optional arguments to Mantid algorithm MaskBTP

  • solid_angle – flag to apply solid angle

  • sensitivity_workspace – workspace containing sensitivity

  • thickness – sample thickness (cm)

  • absolute_scale_method – method to do absolute scaling. One of [“standard”, “direct_beam”]

  • absolute_scale – absolute scaling value for standard method

  • keep_processed_workspaces – flag to keep the processed blocked beam and background workspaces

  • output_workspace – output workspace name for the sample. If None, the name will be output_suffix + "_sample"

  • output_prefix – prefix for output workspaces (output_suffix + "_sample", output_suffix + "_blocked", and output_suffix + "_background")

Returns:

Reference to the processed workspace

Return type:

Workspace2D

drtsans.mono.biosans.reduce_single_configuration(loaded_ws: dict, reduction_input: dict, prefix: str = '', skip_nan: bool = True, debug_output: bool = False) list[source]

Do data reduction for the loaded workspaces according to the given reduction configuration

Saves to file the resulting I(Q) profiles in ASCII format as well as a reduction log.

Parameters:
  • loaded_ws – Dictionary with loaded workspaces (e.g. background, sensitivity, etc.) to use in the reduction

  • reduction_input – Reduction configuration parameters

  • prefix – String to prepend to output file names

  • skip_nan – If True, data points with value NaN will be ignored when writing I(Q) profiles to file.

  • debug_output – If True, saves 2D plots representative of the workspace at different stages of the reduction

Returns:

List of tuple of I(Q):s, one tuple per sample in the workspace. Each tuple holds I(Q):s with 1D and 2D binning for the individual detector panels, as well as a stitched 1D I(Q) profile.

Return type:

list

drtsans.mono.biosans.reduction_parameters(parameters_particular=None, instrument_name=None, validate=True, permissible=False)[source]

Serve all necessary (and validated if so desired) parameters for a reduction session of a particular instrument.

Parameters:
  • parameters_particular (dict) – Non-default parameters, particular to the reduction session. If None, then the default parameters for the specified instrument are passed.

  • instrument_name (str) – Mix the non-default parameters with the remaining default parameters appropriate for this instrument. If left as None, the instrument name is looked under keyword ‘instrumentName’ in dictionary parameters_particular

  • validate (bool) – Perform validation of the parameters

  • permissible (bool) – If False, raise an exception if a parameter in the parameters dictionary is not found in the instrument’s schema, and a warning otherwise.

Return type:

dict

drtsans.mono.biosans.registered_workspace(source)[source]

Find out if the source is a workspace registered in the Analysis Data Service.

Parameters:

source (str, Workspace)

Return type:

bool

drtsans.mono.biosans.sample_aperture_diameter(input_workspace, unit='mm')[source]

Find and return the sample aperture diameter from the logs.

Log keys searched are ‘sample_aperture_diameter’ and additional log entries for specific instruments. It is assumed that the units of the logged value is mm

Parameters:
  • input_workspace (MatrixWorkspace) – Input workspace from which to find the aperture

  • unit (str) – return aperture in requested length unit, either ‘m’ or ‘mm’

Return type:

float

drtsans.mono.biosans.sample_detector_distance(source, unit: str = 'mm', log_key: str | None = None, search_logs: bool = True, forbid_calculation: bool = False) float[source]

Return the distance from the sample to the main detector bank plane

The function checks the logs for the distance, otherwise returns the minimum distance between the sample and the detectors of the bank

Parameters:
  • source (PyObject) – Instrument object, MatrixWorkspace, workspace name, file name, run number.

  • unit (str) – ‘mm’ (millimeters), ‘m’ (meters)

  • log_key (str) – Only search for the given string in the logs. Do not use default log keys

  • search_logs (bool) – Report the value found in the logs.

  • forbid_calculation (bool) – Flag to raise an exception if it is required to get SDD from meta data but no associated meta data is found

Returns:

distance between sample and detector, in selected units

Return type:

float

drtsans.mono.biosans.save_iqmod(iq, file, sep=' ', float_format='%.6E', skip_nan=True, header_type='MantidAscii')[source]

Write the ~drtsans.dataobjects.IQmod object into an ASCII file.

Current output columns (Line 0: ) intensity error mod_q Expected (Line 0: ) mod_q intensity error mod_q_error

Parameters:
  • iq (IQmod) – Profile to be saved

  • file (str) – Path to output file

  • sep (str) – String of length 1. Field delimiter for the output file.

  • float_format (str) – Format string for floating point numbers.

  • skip_nan (bool) – If true, any data point where intensity is NAN will not be written to file

  • header (text) – Determine the header type to make 1D data compatible with panda or Mantid possible values: HeaderType.MANTID_ASCII.value HeaderType.PANDAS.value

drtsans.mono.biosans.search_sample_detector_distance_meta_name(source, specified_meta_name)[source]

Search meta data (sample logs) for sample detector distance

Parameters:
  • source (PyObject) – Instrument object, MatrixWorkspace, workspace name, file name, run number.

  • specified_meta_name (str, None) – Only search for the given string in the source’s meta data (logs). Do not use default log keys

Returns:

item = (str, float, str) meta data name, sample detector distance value, unit

Return type:

~list

drtsans.mono.biosans.search_source_sample_distance_meta_name(source, specified_meta_name)[source]

Search meta data (sample logs) for source-sample distance

Parameters:
  • source (PyObject) – Instrument object, MatrixWorkspace, workspace name, file name, run number.

  • specified_meta_name (str, None) – Only search for the given string in the source’s meta data (logs). Do not use default log keys

Returns:

item = (str, float, str) meta data name, sample detector distance value, unit

Return type:

~list

drtsans.mono.biosans.select_i_of_q_by_wedge(i_of_q, min_wedge_angle, max_wedge_angle)[source]

Select a sub set of I(Q) by 2D wedge

Parameters:
  • i_of_q (IQazimuthal) – “intensity”: intensity, “error”: sigma(I), “qx”: qx, “qy”: qy, “delta_qx”: dqx, “delta_qy”, dqy

  • min_wedge_angle (float) – minimum value of theta/azimuthal angle for wedge

  • max_wedge_angle (float) – maximum value of theta/azimuthal angle for wedge

Returns:

subset of input I(Qx, Qy) with (Qx, Qy) inside defined wedge

Return type:

drtsans.dataobjects.IQazimuthal

drtsans.mono.biosans.set_init_uncertainties(input_workspace, output_workspace=None)[source]

Set the initial uncertainty of a MatrixWorkspace

Mantid algorithm SetUncertainties will be called to make sure 1: set the uncertainty to square root of intensity 2: make sure all zero uncertainties will be set to 1

In case of output workspace is py:obj:None, the input workspace will be replaced by output workspace.

Raises:

RuntimeError – output workspace (string) is empty

Mantid algorithms used: CloneWorkspace SetUncertainties

Parameters:
  • input_workspace (MatrixWorkspace) – Input workspace

  • output_workspace (str) – Output workspace (workspace name or instance) or py:obj:None for in-place operation

Return type:

MatrixWorkspace

drtsans.mono.biosans.solid_angle_correction(input_workspace, detector_type='VerticalTube', output_workspace=None, solid_angle_ws=None, **kwargs)[source]

The algorithm calculates solid angles subtended by the individual pixel-detectors when vieved from the sample position. The returned workspace is the input workspace normalized (divided) by the pixel solid angles.

Mantid algorithms used: ClearMaskFlag, DeleteWorkspace, Divide, ReplaceSpecialValues, SolidAngle

Parameters:
  • input_workspace (str, IEventWorkspace, MatrixWorkspace) – Input workspace to be normalized by the solid angle.

  • detector_type (str) – Select the method to calculate the Solid Angle. Allowed values: [‘GenericShape’, ‘Rectangle’, ‘VerticalTube’, ‘HorizontalTube’, ‘VerticalWing’, ‘HorizontalWing’]

  • output_workspace (str) – Optional name of the output workspace. if None, the name of the input workspace is taken, thus the output workspace replaces the input workspace.

  • solid_angle_ws (str, MatrixWorkspace) – Workspace containing the solid angle calculation

  • kwargs (dict) – Additional arguments to Mantid algorithm SolidAngle

Return type:

IEventWorkspace, MatrixWorkspace

drtsans.mono.biosans.source_aperture_diameter(input_workspace, unit='mm')[source]

Find and return the sample aperture diameter from the logs, or compute this quantity from other log entries.

Log key searched is ‘source_aperture_diameter’. It is assumed that the units of the logged value is mm

Parameters:
  • input_workspace (MatrixWorkspace) – Input workspace from which to find the aperture

  • unit (str) – return aperture in requested length unit, either ‘m’ or ‘mm’

Return type:

float

drtsans.mono.biosans.source_sample_distance(source, unit='mm', log_key=None, search_logs=True)[source]

Report the distance (always positive!) between source and sample aperture.

If logs are not used or distance fails to be found in the logs, then calculate the distance using the instrument configuration file.

Parameters:
  • source (PyObject) – Instrument object, MatrixWorkspace, workspace name, file name, run number

  • unit (str) – ‘mm’ (millimeters), ‘m’ (meters)

  • log_key (str) – Only search for the given string in the logs. Do not use default log keys

  • search_logs (bool) – Report the value found in the logs.

Returns:

distance between source and sample, in selected units

Return type:

float

drtsans.mono.biosans.split_barscan_run(input_file, output_directory, bar_position_log='dcal_Readback')[source]

Split a barscan file containing many positions of the bar into a set of files each holding the bar at a unique position.

The input file must be an events file. The output files contain only the total intensity per pixel. If input file is of the name ‘INST_1234.nxs.h5’, the output files’ names are ‘INST_1234_0.nxs’, ‘INST_1234_1.nxs’, and so on.

Parameters:
  • input_file (str) – Events Nexus file containing a full barscan (many positions of the bar)

  • ouput_directory (str) – Path where the individual scans are saved

drtsans.mono.biosans.standard_sample_scaling(input_workspace, f, f_std, output_workspace=None)[source]

Normalize input workspace using a calibrated standard sample

Parameters:
  • input_workspace (str, MatrixWorkspace) – Workspace to be normalized

  • f (WorkspaceSingleValue) – Level of flat scattering

  • f_std (WorkspaceSingleValue) – Known value of the scattering level of the material

  • output_workspace (MatrixWorkspace) – Name of the normalized workspace. If None, then the name of input_workspace will be used, thus overwriting input_workspace.

Return type:

MatrixWorkspace

drtsans.mono.biosans.stitch_profiles(profiles, overlaps, target_profile_index=0)[source]

Stitch together a sequence of intensity profiles with overlapping domains, returning a single encompassing profile.

drtsans objects used: ~drtsans.dataobjects.IQmod <https://code.ornl.gov/sns-hfir-scse/sans/sans-backend/blob/next/drtsans/dataobjects.py>

Parameters:
  • profiles (list) – A list of ~drtsans.dataobjects.IQmod objects, ordered with increasing Q-values

  • overlaps (list of lists or list) – The overlap regions either as: [(start_1, end_1), (start_2, end_2), (start_3, end_3), …] or (for backwards compatibility): [start_1, end_1, start_2, end_2, start_3, end_3, …]

  • target_profile_index (int) – Index of the profiles list indicating the target profile, that is, the profile defining the final scaling.

Return type:

IQmod

Raises:

ValueError – If either the arguments are incorrect ((i) profiles not in order or increasing Q or (ii) the number of overlaps not congruent with the number of profiles or (iii) overlaps is not a list of numbers or list of lists/tuples) or a stitching scaling factor <= 0 is calculated.

drtsans.mono.biosans.subtract_dark_current(data_workspace, dark, output_workspace=None)[source]

Subtract normalized dark from data, taking into account the duration of both the data and dark runs.

normalized_data = data - (data_duration / dark_duration) * dark

Mantid algorithms used: Scale, Minus DeleteWorkspace

Parameters:
  • data_workspace (MatrixWorkspace) – Sample scattering with intensities versus wavelength.

  • dark (int, str, MatrixWorkspace) – run number, file path, workspace name, or MatrixWorkspace for dark current.

  • output_workspace (str) – Name of the output workspace. If None, the name of the input workspace data_workspace is chosen (and the input workspace is overwritten).

Return type:

MatrixWorkspace

drtsans.mono.biosans.sum_data(data_list, output_workspace, sum_logs=('duration', 'timer', 'monitor', 'monitor1'))[source]

Merge data set together, summing the listed logs

Parameters:
  • data_list (list of Workspace2D, list of workspace names, comma separated list of workspace names, WorkspaceGroup) – Examples: [ws1, ws1], [‘ws1’, ‘ws2’] or ‘ws1, ws2’

  • output_workspace (str) – Name of output workspace, required

  • sum_logs (list of str) – numeric logs that will be summed during merging

Return type:

Workspace2D

drtsans.mono.biosans.transform_to_wavelength(input_workspace, output_workspace=None)[source]

Transforms the event files with fake time of flight from the SANS instruments at HFIR into histograms in wavelength.

Mantid Algorithms used: HFIRSANS2Wavelength,

Parameters:
  • input_workspace (str, IEventWorkspace) – Events workspace in time-of-flight.

  • output_workspace (str) – Name of the output workspace. If None, the name of the input_workspace will be used, thus overwriting the input workspace.

Return type:

MatrixWorkspace

drtsans.mono.biosans.translate_detector_by_z(input_workspace, z=None, relative=True)[source]

Adjust the Z-coordinate of the detector.

Parameters:
  • input_workspace (MatrixWorkspace) – Input workspace containing instrument file

  • z (float) – Translation to be applied, in units of meters. If None, the quantity stored in log_key ~drtsans.geometry.detector_z_log is used, unless the detector has already been translated by this quantity.

  • relative (bool) – If True, add to the current z-coordinate. If False, substitute the current z-coordinate with the new value.

drtsans.mono.biosans.translate_sample_by_z(workspace, z)[source]

Shift the position of the sample by the desired amount

Parameters:
  • workspace (MatrixWorkspace) – Input workspace containing instrument file

  • z (float) – Translation to be applied in meters. Positive values are downstream.

drtsans.mono.biosans.update_reduction_parameters(parameters_original, parameter_changes, validate=True, permissible=False)[source]

Update the values of a reduction parameters dictionary with values from another dictionary. Handles nested dictionaries. Validate after update is done.

Dictionary parameters_original is not modified, but a new copy is produced an updated with parameter_changes

Parameters:
  • parameters_original (dict)

  • parameter_changes (dict)

  • validate (bool) – Perform validation of the parameters

  • permissible (bool) – If False, raise an exception if a parameter in the overall parameters dictionary is not found in the instrument’s schema, and a warning otherwise.

Return type:

dict

drtsans.mono.biosans.validate_reduction_parameters(parameters, permissible=False)[source]

Validate reduction parameters against the instrument’s schema.

Parameters:
  • parameters (dict, ReductionParameters) – Reduction configuration

  • permissible (bool) – If False, raise an exception if a parameter in the parameters dictionary is not found in the instrument’s schema, and a warning otherwise.

Returns:

Validated reduction parameters

Return type:

dict