drtsans.tof.eqsans package

Submodules

drtsans.tof.eqsans.api module

Top-level API for EQSANS

drtsans.tof.eqsans.api.apply_solid_angle_correction(input_workspace)[source]

Apply solid angle correction. This uses drtsans.solid_angle_correction().

drtsans.tof.eqsans.api.load_all_files(reduction_input, prefix='', load_params=None)[source]

overwrites metadata for sample workspace

Workflow: 1. parse reduction_input 2. remove existing related workspaces with same run numbers 3. process beam center - output: load_params, reduction_input 4. adjust pixel heights and widths - output: load_params, reduction_input 5. load and optionally slice sample runs 6. load other runs: bkgd, empty, sample_trans, bkgd_trans

Returned namedtuple:
  • sample, background, empty, sample_transmission, background_transmission: namedtuple(data[ws], monitor[ws])

  • dark_current, sensitivity, mask: workspace

Returns:

Named tuple including all loaded workspaces

Return type:

namedtuple

drtsans.tof.eqsans.api.plot_reduction_output(reduction_output, reduction_input, imshow_kwargs=None)[source]
drtsans.tof.eqsans.api.pre_process_single_configuration(sample_ws_raw: namedtuple, sample_trans_ws=None, sample_trans_value=None, bkg_ws_raw=None, bkg_trans_ws=None, bkg_trans_value=None, theta_dependent_transmission=True, dark_current=None, flux_method=None, flux=None, mask_ws=None, mask_panel=None, mask_btp=None, solid_angle=True, sensitivity_workspace=None, output_workspace=None, output_suffix='', thickness=1.0, absolute_scale_method='standard', empty_beam_ws=None, beam_radius=None, absolute_scale=1.0, keep_processed_workspaces=True)[source]

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

Parameters:
  • sample_ws_raw (namedtuple) – (~mantid.dataobjects.Workspace2D, ~mantid.dataobjects.Workspace2D) raw data histogram workspace and monitor

  • sample_trans_ws (Workspace2D) – optional histogram workspace for sample transmission (already prepared)

  • sample_trans_value (float) – optional value for sample transmission

  • bkg_ws_raw (Workspace2D) – optional raw histogram workspace for background

  • bkg_trans_ws (Workspace2D) – optional histogram workspace for background transmission

  • bkg_trans_value (float) – optional value for background transmission

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

  • dark_current (Workspace2D) – dark current workspace

  • flux_method (str) – normalization by time or monitor

  • mask_ws (Workspace2D) – user defined mask

  • mask_panel (str) – mask fron or back panel

  • mask_btp (dict) – optional bank, tube, pixel to mask

  • solid_angle (bool) – flag to apply solid angle

  • sensitivity_workspace (Workspace2D) – workspace containing sensitivity

  • output_workspace (str) – output workspace name

  • output_suffix (str) – suffix for output workspace

  • thickness (float) – sample thickness (cm)

  • absolute_scale_method (str) – method to do absolute scaling (standard or direct_beam)

  • empty_beam_ws (Workspace2D) – empty beam workspace for absolute scaling

  • beam_radius (float) – beam radius for absolute scaling

  • absolute_scale (float) – absolute scaling value for standard method

  • keep_processed_workspaces (bool) – flag to keep the processed background workspace

Returns:

Reference to the processed workspace

Return type:

Workspace2D

drtsans.tof.eqsans.api.prepare_data(data, pixel_calibration=False, detector_offset=0, sample_offset=0, bin_width=0.1, low_tof_clip=500, high_tof_clip=2000, center_x=None, center_y=None, dark_current=None, flux_method=None, flux=None, mask=None, mask_panel=None, btp={}, solid_angle=True, sensitivity_file_path=None, sensitivity_workspace=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='')[source]

Load an EQSANS 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

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

  • 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.

  • bin_width (float) – Bin width for the output workspace, in Angstroms.

  • low_tof_clip (float) – Ignore events with a time-of-flight (TOF) smaller than the minimal TOF plus this quantity.

  • high_tof_clip (float) – Ignore events with a time-of-flight (TOF) bigger than the maximal TOF minus this quantity.

  • 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 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 y=0.

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

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

  • flux (str) – if flux_method is proton charge, then path to file containing the wavelength distribution of the neutron flux. If flux method is monitor, then path to file containing the flux-to-monitor ratios. if flux_method is time, then pass one log entry name such as duration or leave it as None for automatic log search.

  • 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.

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

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

  • source_aperture_diameter (float, None) – source aperture diameter in unit meter

  • 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-resolutio 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.tof.eqsans.api.prepare_data_workspaces(data: namedtuple, dark_current=None, flux_method=None, flux=None, mask_ws=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:

  • 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 (namedtuple) – (~mantid.dataobjects.Workspace2D, ~mantid.dataobjects.Workspace2D) raw workspace (histogram) for data and monitor

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

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

  • flux (str) – if flux_method is proton charge, then path to file containing the wavelength distribution of the neutron flux. If flux method is monitor, then path to file containing the flux-to-monitor ratios. if flux_method is time, then pass one log entry name such as duration or leave it as None for automatic log search.

  • mask_ws (Workspace2D) – Mask workspace

  • 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.tof.eqsans.api.reduce_single_configuration(loaded_ws: namedtuple, reduction_input, prefix='', skip_nan=True, not_apply_incoherence_correction: bool = False)[source]

Reduce samples from raw workspaces including 1. prepare data 1.

This is the main entry point of reduction

Input loaded workspaces as namedtuple:
  • sample, background, empty, sample_transmission, background_transmission: namedtuple(data[ws], monitor[ws])

  • dark_current, sensitivity, mask: workspace

Parameters:
  • loaded_ws (namedtuple) – loaded workspaces, usually the return value of load_all_files()

  • reduction_input (dict) – reduction configuration

  • prefix

  • skip_nan

  • not_apply_incoherence_correction (bool) – If true, then no incoherence scattering correction will be applied to reduction overriding JSON

Returns:

list of IofQ_output: [‘I2D_main’, ‘I1D_main’]

Return type:

~list

drtsans.tof.eqsans.api.save_ascii_1D(wksp, title, filename)[source]

Save the I(q) workspace in Ascii format

Parameters:
  • wksp (MatrixWorkspace) – Workspace containing only one spectrum (the I(q) curve)

  • title (string) – first line of the ascii file

  • filename (string) – The output filename

drtsans.tof.eqsans.api.save_nexus(input_workspace, title, filename)[source]

Write the given Mantid workspace to a NeXus file.

Parameters:
  • input_workspace (MatrixWorkspace) – Name of the workspace to be saved

  • title (string) – Title to describe the saved worksapce

  • filename (string) – The bame of the NeXus file to write, as a full or relative path. Allowed extensions: [.nxs, .nx5, .xml]

drtsans.tof.eqsans.api.save_nist_dat(input_workspace, filename)[source]

Save I(Qx, Qy) data to a text file compatible with NIST and DANSE readers

Parameters:
  • input_workspace (MatrixWorkspace) – Workspace to be saved

  • filename (string) – Filename of the output text file. Allowed extensions: [.dat]

drtsans.tof.eqsans.api.save_xml_1D(wksp, title, filename)[source]

Save the I(q) workspace in SaveCanSAS (XML) format

Parameters:
  • wksp (MatrixWorkspace) – Workspace containing only one spectrum (the I(q) curve)

  • title (string) – Text to append to Process section

  • filename (string) – The output filename

drtsans.tof.eqsans.api.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.tof.eqsans.api.subtract_background(input_workspace, background, scale=1.0, scale_error=0.0, output_workspace=None)[source]

Subtract a prepared background from a prepared sample.

Perform a rebin if sample and background have different binning.

Mantid algorithms used: CloneWorkspace CreateSingleValuedWorkspace Minus Multiply RebinToWorkspace

Parameters:
  • input_workspace (str, MatrixWorkspace, IQmod, IQazimuthal) – Sample workspace.

  • background (str, MatrixWorkspace, IQmod, IQazimuthal) – Background workspace.

  • scale (float) – Rescale background intensities by this multiplicative factor before subtraction from the sample.

  • scale_error (float) – Uncertainty in scale factor

  • output_workspace (str) – Name of the sample corrected by the background. If None, then input_workspace will be overwritten. In the case of using data from dataobjects, this parameter is ignored.

Return type:

MatrixWorkspace

drtsans.tof.eqsans.azimuthal_average_1D module

drtsans.tof.eqsans.cfg module

Reader for EQSANS configuration files in the old format

drtsans.tof.eqsans.cfg.load_config(source, config_dir='/SNS/EQSANS/shared/instrument_configuration')[source]

Load the configuration file appropriate to the input source info

Parameters:
  • source (str) – The filename (absolute path or relative) to a configuration file or a run-number

  • config_dir (str) – Directory containing configuration files

Returns:

keys are entries in the file

Return type:

dict

drtsans.tof.eqsans.chopper module

This module provides class EQSANSDiskChopperSet representing the set of four disk choppers (two of them paired as a double chopper). The main goal is to find the set of neutron wavelength bands transmitted by the chopper set, given definite choppers settings such as aperture and starting phase.

class drtsans.tof.eqsans.chopper.EQSANSDiskChopperSet(other)[source]

Bases: object

Set of disks choppers installed in EQSANS.

Parameters:

other (file name, workspace, Run object, run number) – Load the chopper settings from this object.

property period
property pulse_width
transmission_bands(cutoff_wl=None, delay=0, pulsed=False)[source]

Wavelength bands transmitted by the chopper apertures. The number of bands is determined by the slowest neutrons emitted from the moderator.

Parameters:
  • cutoff_wl (float) – maximum wavelength of incoming neutrons. Discard slower neutrons when finding the transmission bands.

  • delay (float) – Additional time-of-flight to include in the calculations. For instance, this could be a multiple of the the pulse period.

  • pulsed (bool) – Include a correction due to delayed emission of neutrons from the moderator. See _pulse_width for a more detailed explanation.

Returns:

Set of wavelength bands transmitted by the chopper.

Return type:

Wbands

drtsans.tof.eqsans.correct_frame module

drtsans.tof.eqsans.correct_frame.transform_to_wavelength(input_workspace, bin_width=0.1, low_tof_clip=0.0, high_tof_clip=0.0, keep_events=True, interior_clip=True, output_workspace=None, bands=None)[source]

API function that converts corrected TOF’s to Wavelength.

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

  • bin_width (float) – Bin width for the output workspace, in Angstroms.

  • low_tof_clip (float) – Ignore events with a time-of-flight (TOF) smaller than the minimal TOF plus this quantity.

  • high_tof_clip (float) – Ignore events with a time-of-flight (TOF) bigger than the maximal TOF minus this quantity.

  • keep_events (bool) – The final histogram will be an EventsWorkspace if True.

  • interior_clip (bool) – If True, trim slow neutrons from the lead pulse (using high_tof_clip) and fast neutrons from the skip pulse (using low_tof_clip)

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

Returns:

~mantid.api.IEventWorkspace, ~mantid.api.MatrixWorkspace

Return type:

tuple

drtsans.tof.eqsans.correction_api module

class drtsans.tof.eqsans.correction_api.CorrectionConfiguration(do_correction=False, select_min_incoherence=False, select_intensityweighted=False, qmin=None, qmax=None, factor=None, output_wavelength_dependent_profile=False)[source]

Bases: object

A data class/structure to hold the parameters configured to do incoherence/inelastic scattering correction

Parameters:
  • do_correction (bool) – if to do correction or not

  • select_minimum_incoherence (bool) – flag to determine correction B by minimum incoherence

  • intensity_weighted (bool) – flag to determine if the b factor is calculated in a weighted function by intensity

  • qmin_index (float) – optional, manually set the qmin used for incoherent calculation

  • qmax_index (float) – optional, manually set the qmax used for incoherent calculation

  • factor (float) – optional, automatically determine the qmin qmax by checking the intensity profile

  • output_wavelength_dependent_profile (bool) – if True then output Iq for each wavelength before and after k and b correction

property do_correction
property elastic_reference

elastic scattering normalization reference run and background run

property factor
property output_wavelength_dependent_profile
property qmax
property qmin
property sample_thickness
property select_intensityweighted
property select_min_incoherence
set_elastic_reference(reference_run_setup)[source]

Set elastic reference run reduction setup

Parameters:

reference_run_setup (ElasticReferenceRunSetup) – reduction setup

class drtsans.tof.eqsans.correction_api.ElasticReferenceRunSetup(ref_run_number: int | str, thickness: float, trans_run_number: None | str | int = None, trans_value: None | float = None)[source]

Bases: object

A data class/structure to hold the reference run

set_background(run_number: int | str, trans_run_number: None | str | int = None, trans_value: None | float = None)[source]

Set elastic reference background run setup

class drtsans.tof.eqsans.correction_api.NormFactor(k, k_error, p, s)

Bases: tuple

k

Alias for field number 0

k_error

Alias for field number 1

p

Alias for field number 2

s

Alias for field number 3

drtsans.tof.eqsans.correction_api.do_inelastic_incoherence_correction(iq2d: IQazimuthal, iq1d: IQmod, correction_setup: CorrectionConfiguration, prefix: str, output_dir: str, output_filename: str = '') tuple[IQazimuthal, IQmod][source]

Do inelastic incoherence correction on 2D and 1D I(Q)

Parameters:
  • iq2d (IQazimuthal) – I(Q2D)

  • iq1d (IQmod) – I(Q1D)

  • correction_setup (CorrectionConfiguration) – correction configuration

  • prefix (str) – prefix for b factor file

  • output_dir (str) – output directory for b1d(lambda)

  • output_filename (str) – output filename parsed from input configuration file (JSON)

Returns:

The corrected I(Q2D) and I(Q1D)

Return type:

tuple[IQazimuthal, IQmod]

drtsans.tof.eqsans.correction_api.parse_correction_config(reduction_config)[source]

Parse correction configuration from reduction configuration (top level)

Parameters:

reduction_config (~dict) – reduction configuration from JSON

Returns:

incoherence/inelastic scattering correction configuration

Return type:

CorrectionConfiguration

drtsans.tof.eqsans.correction_api.save_b_factor(i_of_q: CorrectedIQ1D | CorrectedIQ2D, path: str) None[source]
drtsans.tof.eqsans.correction_api.save_k_vector(wavelength_vec, k_vec, delta_k_vec, path: str) None[source]

Save K vector from elastic scattering normalization

drtsans.tof.eqsans.dark_current module

drtsans.tof.eqsans.dark_current.load_dark_current_workspace(dark_current_filename, output_workspace)[source]

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

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

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

drtsans.tof.eqsans.dark_current.normalize_dark_current(dark_workspace, data_workspace, output_workspace=None)[source]

Scale and Rebin in wavelength a dark current workspace with information from a data workspace.

Rescale and rebin to the data workspace according to:

\[frame\_width\_clipped / (frame\_width * n\_bins * duration) * I\_dc(x, y)\]

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: Integration, CreateWorkspace DeleteWorkspace

Parameters:
  • dark_workspace (str, EventsWorkspace) – Dark current workspace with units in time-of-flight

  • data_workspace (str, MatrixWorkspace) – Sample scattering with intensities versus wavelength

  • 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, dark current rebinned to wavelength and rescaled

Return type:

MatrixWorkspace

drtsans.tof.eqsans.dark_current.subtract_dark_current(input_workspace, dark, output_workspace=None)[source]
Parameters:
  • input_workspace (int, str, IEventWorkspace) – The workspace to be normalized

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

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.elastic_reference_normalization module

drtsans.tof.eqsans.elastic_reference_normalization.build_i_of_q1d(wl_vector, q_vector, intensity_array, error_array, delta_q_array)[source]

From wavelength, Q, intensity, error and delta Q to build I(Q1D)

This is the reversed operation to method reshape_q_wavelength_matrix

Parameters:
  • wl_vector (ndarray) – wavelength (1D)

  • q_vector (ndarray) – Q (1D)

  • intensity_array (ndarray) – intensities (2D)

  • error_array (ndarray) – intensity errors (2D)

  • delta_q_array (ndarray) – delta Q (1D) size = number wavelength * number Q

Returns:

constructed I(Q, wavelength)

Return type:

IQmod

drtsans.tof.eqsans.elastic_reference_normalization.determine_common_mod_q_range_mesh(q_vec, intensity_array)[source]

Determine the common Q1D range among all the wavelengths such that I(q, lambda) does exist.

This method assumes that I(Q, wavelength) are on mesh grid of Q and wavelength

Detailed requirement:

Determine q_min and q_max that exist in all I(q, lambda) for the fitting (minimization) process

Parameters:
  • q_vec (numpy.ndarray) – vector of sorted unique Q

  • intensity_array (numpy.ndarray) – 2D array of intensity. Each row is of same wavelength

Returns:

index of qmin and qmax

Return type:

tuple

drtsans.tof.eqsans.elastic_reference_normalization.determine_reference_wavelength_q1d_mesh(wavelength_vec, q_vec, intensity_array, error_array, qmin_index, qmax_index, min_wl_index=0)[source]

Determine the reference wavelength for each Q.

The reference wavelength of a specific Q or (qx, qy) is defined as the shortest wavelength for all the finite I(Q, wavelength) or I(qx, qy, wavelength)

Parameters:
Returns:

Reference wavelengths for each momentum transfer Q and the corresponding intensity and error

Return type:

ReferenceWavelengths

drtsans.tof.eqsans.elastic_reference_normalization.normalize_by_elastic_reference_1d(i_of_q, k_vec, k_error_vec, output_wavelength_dependent_profile=False, output_dir=None)[source]

Normalize I(Q1D) by wavelength-dependent elastic reference normalization factor

Parameters:
  • i_of_q (IQmod) – Input I(Q, wavelength) to normalize

  • k_vec (ndarray) – Elastic reference normalization factors (one for each wavelength)

  • k_error_vec (ndarray) – Elastic reference normalization factor errors (one for each wavelength)

  • output_wavelength_dependent_profile (bool) – If True then output Iq for each wavelength before and after k correction

  • output_dir (str) – output directory for Iq profiles

Returns:

normalized Q(1D), K vector and delta K vector

Return type:

tuple

drtsans.tof.eqsans.elastic_reference_normalization.normalize_by_elastic_reference_2d(i_of_q, k_vec, k_error_vec)[source]

Normalize I(Q2D) by wavelength-dependent elastic reference normalization factor

Parameters:
  • i_of_q (IQazimuthal) – Input I(Q2D, wavelength) to normalize

  • k_vec (ndarray) – Elastic reference normalization factors (one for each wavelength)

  • k_error_vec (ndarray) – Elastic reference normalization factor errors (one for each wavelength)

Returns:

normalized I(Q2D)

Return type:

IQazimuthal

drtsans.tof.eqsans.elastic_reference_normalization.normalize_by_elastic_reference_all(i_of_q_2d, i_of_q_1d, ref_i_of_q_1d, output_wavelength_dependent_profile=False, output_dir=None)[source]

Normalize I(Q2D) and I(Q1D) by elastic reference run

Parameters:
  • i_of_q_2d (IQazimuthal) – Input I(Q2D, wavelength) to normalize

  • i_of_q_1d (IQmod) – Input I(Q1D, wavelength) to normalize

  • ref_i_of_q_1d (IQmod) – Input I(Q1D, wavelength) as elastic reference run

  • output_wavelength_dependent_profile (bool) – If True then output Iq for each wavelength before and after k correction

  • output_dir (str) – output directory for Iq profiles

Returns:

normalized I(Q2D), normalized I(Q1D), K vector and delta K vector

Return type:

tuple

drtsans.tof.eqsans.elastic_reference_normalization.reshape_q_wavelength_matrix(i_of_q)[source]

Reshape I(Q) into a mesh grid of (Q, wavelength)

Parameters:

i_of_q (IQmod) – Input I(Q, wavelength) to find common Q range from

Returns:

wavelength vector, q vector, intensity (2D), error (2D), dq array (2D) or None

Return type:

tuple

drtsans.tof.eqsans.geometry module

drtsans.tof.eqsans.geometry.beam_radius(input_workspace, unit='mm')[source]

Calculate the beam radius impinging on the detector bank.

\[R_{beam} = R_{sampleAp} + SDD * (R_{sampleAp} + R_{sourceAp}) / SSD\]
Parameters:
  • input_workspace (MatrixWorkspace, str) – Input workspace, contains all necessary info in the logs

  • unit (str) – Either ‘mm’ or ‘m’

Returns:

Estimated beam radius

Return type:

float

drtsans.tof.eqsans.geometry.sample_aperture_diameter(run, unit='mm')[source]

Find the sample aperture diameter from the logs.

Log keys searched are ‘sample_aperture_diameter’ (override beamslit4) and ‘beamslit4’.

Parameters:
  • run (Mantid Run instance, MatrixWorkspace, file name, run number) – Input from which to find the aperture

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

Returns:

Sample aperture diameter, in requested units

Return type:

float

drtsans.tof.eqsans.geometry.source_aperture_diameter(run, unit='mm')[source]

Find the source aperture diameter

Either report log vale or compute this quantity.

After the moderator (source) there are three consecutive discs (termed wheels), each with eight holes in them (eight slits). Appropriate log entries (VbeamSlit, VbeamSlit2, VbeamSlit3) indicate the slit index for each of the three wheels. Thus, the position of the source and the source aperture are not the same. The most restrictive slit will define the source aperture

Log entries beamslit, beamslit2, and beamslit3 store the required rotation angle for each wheel in order to align the appropriate slit with the neutron beam. These angles are not used in reduction.

If the aperture is computed, then the value is stored in log key “source_aperture_diameter”, with mili meter units

Parameters:
  • run (Mantid Run instance, MatrixWorkspace, file name, run number)

  • unit (str) – Length unit, either ‘m’ or ‘mm’

Returns:

Source aperture diameter, in requested units

Return type:

float

drtsans.tof.eqsans.geometry.source_aperture_sample_distance(run, unit='mm')[source]

Find the distance from the source aperture to the sample.

Either report log vale or compute this quantity. If the distance has to be computed, then stores the value in log key “source_aperture_sample_distance”, with mili-meter units.

Parameters:
  • run (Mantid Run instance, MatrixWorkspace, file name, run number)

  • unit (str) – Length unit, either ‘m’ or ‘mm’

Return type:

float

drtsans.tof.eqsans.geometry.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.tof.eqsans.geometry.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.tof.eqsans.incoherence_correction_1d module

class drtsans.tof.eqsans.incoherence_correction_1d.CorrectedIQ1D(iq1d, b_factor, b_error)

Bases: tuple

b_error

Alias for field number 2

b_factor

Alias for field number 1

iq1d

Alias for field number 0

drtsans.tof.eqsans.incoherence_correction_1d.correct_incoherence_inelastic_1d(wl_vec, q_vec, i_array, error_array, dq_array, b_array, qmin_index, qmax_index, ref_wl_ie, output_wavelength_dependent_profile=False, output_dir=None)[source]
Parameters:
  • wl_vec (ndarray) – 1D vector of wavelength (in ascending order)

  • q_vec (ndarray) – 1D vector of Q (in ascending order)

  • i_array (ndarray) – 2D array of intensities, shape[0] = number of Q, shape[1] = number of wavelength

  • error_array (ndarray) – 2D array if intensity errors

  • dq_array (ndarray) – 2D array of errors, shape[0] = number of Q, shape[1] = number of wavelength

  • b_array (ndarray) – incoherence inelastic correction factor B, row 0: B factor, row 1: delta B

  • qmin_index (int) – index of minimum common q in q vector

  • qmax_index (int) – index of maximum common q in q vector

  • ref_wl_ie (ReferenceWavelength) – the reference wavelength data used to calculate B

  • output_wavelength_dependent_profile (bool) – If True then output Iq for each wavelength before and after b correction

  • output_dir (str) – output directory for Iq profiles

Returns:

I(Q1D) with inelastic incoherent correction applied

Return type:

CorrectedIQ1D

drtsans.tof.eqsans.incoherence_correction_1d.correct_incoherence_inelastic_all(i_of_q_2d, i_of_q_1d, select_minimum_incoherence, intensity_weighted=False, qmin=None, qmax=None, factor=None, output_wavelength_dependent_profile=False, output_dir=None)[source]

Correct I(Q2D) and I(Q1D) accounting wavelength dependant incoherent inelastic scattering

This is the envelope method for the complete workflow to correct I(Q1D) and I(Q2D) accounting wavelength-dependent incoherent inelastic scattering

Parameters:
  • i_of_q_2d (IQazimuthal or None) – I(Q2D, wavelength) and error

  • i_of_q_1d (IQmod) – I(Q1D, wavelength) and error

  • select_minimum_incoherence (bool) – flag to determine correction B by minimum incoherence

  • intensity_weighted (bool) – if set to true, the B factor is calculated using weighted function by intensity

  • qmin (float) – manually set the qmin used for incoherent calculation

  • qmax (float) – manually set the qmax used for incoherent calculation

  • factor (float) – automatically determine the qmin qmax by checking the intensity profile

  • output_wavelength_dependent_profile (bool) – If True then output Iq for each wavelength before and after b correction

  • output_dir (str) – output directory for Iq profiles

Returns:

named tuple include ~drtsans.dataobjects.IQmod (corrected I(Q, wavelength)), B vector, B error vector

Return type:

tuple[CorrectedIQ2D, CorrectedIQ1D]

drtsans.tof.eqsans.incoherence_correction_2d module

class drtsans.tof.eqsans.incoherence_correction_2d.CorrectedIQ2D(iq2d, b_factor, b_error)

Bases: tuple

b_error

Alias for field number 2

b_factor

Alias for field number 1

iq2d

Alias for field number 0

drtsans.tof.eqsans.incoherence_correction_2d.correct_incoherence_inelastic_2d(i_of_q, b_array, ref_wl_index)[source]

Correct I(Q2D) with wavelength dependent incoherence inelastic scattering

This method implements the workflow for correcting I(Q2D) with wavelength-dependent incoherent inelastic scattering

Parameters:
  • i_of_q (IQazimuthal) – I(Qx, Qy, wavelength) with error

  • b_array (ndarray) – 2D numpy array for B[wavelength], B error[wavelength]

  • ref_wl_index (int) – Index of reference wavelength in the wavelength vector

Returns:

named tuple of corrected I(Qx, Qy, wavelength), b2d, b2d error

Return type:

CorrectedIQ2D

drtsans.tof.eqsans.load module

drtsans.tof.eqsans.load.load_and_split_and_histogram(run, detector_offset=0.0, sample_offset=0.0, path_to_pixel=True, data_dir=None, output_workspace=None, output_suffix='', overwrite_instrument=True, pixel_calibration=False, bin_width=0.1, low_tof_clip=500, high_tof_clip=2000, center_x=None, center_y=None, centering_method='center_of_mass', centering_options={}, mask=None, keep_events=True, time_interval: float | List[float] | None = None, time_offset: float = 0.0, time_period: float | None = None, log_name=None, log_value_interval=None, reuse_workspace=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.

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

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

  • centering_method (str) – Method to calculate the beam center. Available methods are: - ‘center_of_mass’, invokes FindCenterOfMassPosition - ‘gaussian’, 2D Gaussian fit to beam center data

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

  • 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.

Returns:

(WorkspaceGroup, Bands): Reference to the workspace groups containing all the split workspaces

Return type:

~tuple

drtsans.tof.eqsans.load.load_events(run, pixel_calibration=False, detector_offset=0.0, sample_offset=0.0, path_to_pixel=True, data_dir=None, output_workspace=None, output_suffix='', **kwargs)[source]

Load events with initial corrections for geometry and time-of-flight

Note: Detector is translated along the Z-axis by the value specified in keyword detectorZ of the logs. The final sample to detector distance is detectorZ + detector_offset - sample_offset.

Mantid algorithms used: LoadEventNexus,

Parameters:
  • run (int, str) – Examples: 55555 or EQSANS_55555 or file path.

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

  • 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.

  • path_to_pixel (bool) – When correcting the recorded time of flight of each neutron, use the path from the moderator to the detector pixel (True) or to the center of the detector panel (False). The latter for comparison to the old data reduction.

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

  • output_workspace (str) – If not specified it will be EQSANS_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.

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

Returns:

Reference to the events workspace

Return type:

IEventWorkspace

drtsans.tof.eqsans.load.load_events_and_histogram(run, pixel_calibration=False, detector_offset=0.0, sample_offset=0.0, path_to_pixel=True, data_dir=None, output_workspace=None, output_suffix='', bin_width=0.1, low_tof_clip=500, high_tof_clip=2000, center_x=None, center_y=None, centering_method='center_of_mass', centering_options={}, mask=None, monitors=False, keep_events=True, sample_bands=None, **kwargs)[source]

Load events from one or more NeXus files with initial corrections for geometry, time-of-flight and beam center. Convert to wavelength and sum.

Note: Detector is translated along the Z-axis by the value specified in keyword detectorZ of the logs. The final sample to detector distance is detectorZ + detector_offset - sample_offset.

Parameters:
  • run (list of runs to load) – Examples: 55555 or EQSANS_55555 or file path or EQSANS_55555, EQSANS_55556

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

  • 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.

  • path_to_pixel (bool) – When correcting the recorded time of flight of each neutron, use the path from the moderator to the detector pixel (True) or to the center of the detector panel (False). The latter for comparison to the old data reduction.

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

  • output_workspace (str) – If not specified it will be EQSANS_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.

  • bin_width (float) – Bin width for the output workspace, in Angstroms.

  • low_tof_clip (float) – Ignore events with a time-of-flight (TOF) smaller than the minimal TOF plus this quantity.

  • high_tof_clip (float) – Ignore events with a time-of-flight (TOF) bigger than the maximal TOF minus this quantity.

  • 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 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 y=0.

  • centering_method (str) – Method to calculate the beam center. Available methods are: - ‘center_of_mass’, invokes FindCenterOfMassPosition - ‘gaussian’, 2D Gaussian fit to beam center data

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

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

  • monitors (boolean) – Option to load the monitors as well as the data, if False monitor will be None

  • keep_events (bool) – The final histogram will be an EventsWorkspace if True.

  • sample_bands (bands or None) – sample bands

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

Returns:

Fields of namedtuple data: the loaded data monitor: the monitor for the data, if monitors==True else None

Return type:

namedtuple

drtsans.tof.eqsans.load.load_events_monitor(run, data_dir=None, output_workspace=None)[source]

Load monitor events with initial corrections for geometry and time-of-flight

Parameters:
  • run (int, str) – Examples: 55555 or EQSANS_55555 or file path.

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

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.load.prepare_monitors(data, bin_width=0.1, output_workspace=None)[source]

Loads monitor counts, correct TOF, and transforms to wavelength.

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

  • bin_width (float) – Bin width for the output workspace, in Angstroms.

  • output_workspace (str) – Name of the output workspace. If None, then it will be EQSANS_XXXXX_monitors with number XXXXX determined from data.

Return type:

MatrixWorkspace

drtsans.tof.eqsans.load.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.tof.eqsans.meta_data module

drtsans.tof.eqsans.meta_data.set_meta_data(workspace, wave_length=None, wavelength_spread=None, sample_offset=0.0, sample_aperture_diameter=None, sample_thickness=None, source_aperture_diameter=None, smearing_pixel_size_x=None, smearing_pixel_size_y=None)[source]

Set meta data to SANS Mantid Workspace as run properties

Parameters:
  • workspace (str, MatrixWorkspace) – Mantid workspace instance or workspace name

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

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

  • sample_offset (float) – offset of sample from origin in unit mm

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

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

  • source_aperture_diameter (float, None) – source aperture diameter in unit meter

  • smearing_pixel_size_x (float, None) – pixel size in x direction in unit as meter

  • smearing_pixel_size_y (float, None) – pixel size in Y direction in unit as meter

drtsans.tof.eqsans.momentum_transfer module

drtsans.tof.eqsans.momentum_transfer.convert_to_q(ws, mode, resolution_function=<function eqsans_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.tof.eqsans.momentum_transfer.split_by_frame(input_workspace, *args, **kwargs)[source]

Split the output of convert_to_q into a list of outputs, one for each frame.

Parameters:
Returns:

A list with namedtuples

Return type:

~list

drtsans.tof.eqsans.normalization module

Links to mantid algorithms CloneWorkspace <https://docs.mantidproject.org/nightly/algorithms/CloneWorkspace-v1.html> ConvertToHistogram <https://docs.mantidproject.org/nightly/algorithms/ConvertToHistogram-v1.html> DeleteWorkspace <https://docs.mantidproject.org/nightly/algorithms/DeleteWorkspace-v1.html> Divide <https://docs.mantidproject.org/nightly/algorithms/Divide-v1.html> Load <https://docs.mantidproject.org/nightly/algorithms/Load-v1.html> LoadAscii <https://docs.mantidproject.org/nightly/algorithms/LoadAscii-v1.html> Multiply <https://docs.mantidproject.org/nightly/algorithms/Multiply-v1.html> NormaliseByCurrent <https://docs.mantidproject.org/nightly/algorithms/NormaliseByCurrent-v1.html> RebinToWorkspace <https://docs.mantidproject.org/nightly/algorithms/RebinToWorkspace-v1.html> RemoveSpectra <https://docs.mantidproject.org/nightly/algorithms/RemoveSpectra-v1.html> Scale <https://docs.mantidproject.org/nightly/algorithms/Scale-v1.html> SplineInterpolation <https://docs.mantidproject.org/nightly/algorithms/SplineInterpolation-v1.html>

drtsans.tof.eqsans.normalization.normalize_by_flux(input_workspace, flux, method='proton charge', monitor_workspace=None, output_workspace=None)[source]

Normalize counts by several methods to estimate the neutron flux.

This function calls specialized normalizing functions based on method argument. Those functions are: - normalize_by_time - normalize_by_monitor - normalize_by_proton_charge_and_flux

Parameters:
  • input_workspace (MatrixWorkspace) – Input workspace, binned in wavelength

  • flux (str) – If method is ‘proton charge’, flux is the path to the file containing the wavelength distribution of the neutron flux. If method is ‘monitor’, then flux is the path to the file containing a pre-measured flux-to-monitor ratio spectrum. If flux_method is ‘time’, then pass one log entry name such as ‘duration’ or pass None for automatic log search.

  • method (str) – Either ‘proton charge’, ‘monitor’, or ‘time’

  • monitor_workspace (str, MatrixWorkspace) – Prepared monitor workspace

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.normalization.normalize_by_monitor(input_workspace, flux_to_monitor, monitor_workspace, output_workspace=None)[source]

Normalizes the input workspace by monitor count and flux-to-monitor ratio.

Mantid algorithms used: RebinToWorkspace, RemoveSpectra, CloneWorkspace, SplineInterpolation, Multiply, Divide, DeleteWorkspace

Parameters:
  • input_workspace (str, MatrixWorkspace) – Workspace to be normalized, rebinned in wavelength.

  • flux_to_monitor (str, MatrixWorkspace) – Flux to monitor ratio. A file path or a workspace resulting from calling load_flux_to_monitor_ratio_file.

  • monitor_workspace (str, MatrixWorkspace) – Counts from the monitor.

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.normalization.normalize_by_proton_charge_and_flux(input_workspace, flux, output_workspace=None)[source]

Normalizes the input workspace by proton charge and measured flux

Mantid algorithms used: RebinToWorkspace, Divide, DeleteWorkspace, NormaliseByCurrent,

Parameters:
  • input_workspace (str, MatrixWorkspace) – Workspace to be normalized, rebinned in wavelength.

  • flux (Workspace) – Measured beam flux file ws, usually the output of load_beam_flux_file

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.normalization.normalize_by_time(input_workspace, log_key=None, output_workspace=None)[source]

Divide the counts by the duration of the run

Mantid algorithms used: Scale

Parameters:
  • input_workspace (str, MatrixWorkspace)

  • log_key (str) – Use this log entry to figure out the run duration. If None, logs are sequentially searched for keys duration, start_time, proton_charge, and timer, in order to find out the duration.

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.parameters module

drtsans.tof.eqsans.parameters.CONFIG_FILE_PREFIX = 'eqsans_configuration.'

This module parses the EQSANS configuration file and transforms it into a dictionary

drtsans.tof.eqsans.parameters.get_parameters(run_number)[source]

Get the parameters from the configuration file If the same key exist, the value is appended with

Returns a dictionary

drtsans.tof.eqsans.prepare module

drtsans.tof.eqsans.prepare.prepare_background_scattering()[source]

Prepare a run containing an empty sample holder, or a background material

drtsans.tof.eqsans.prepare.prepare_background_transmission()[source]

Prepare a run containing an empty sample holder or a background material, plus an attenuator

drtsans.tof.eqsans.prepare.prepare_beam_center()[source]

Recipe for the beam center file prior to finding the center coords.

drtsans.tof.eqsans.prepare.prepare_dark_current()[source]

Recipe to normalize the dark current

drtsans.tof.eqsans.prepare.prepare_sample_scattering()[source]

Prepare a run containing a sample

drtsans.tof.eqsans.prepare.prepare_sample_transmission()[source]

Prepare a run containing a sample plus an attenuator

drtsans.tof.eqsans.prepare.prepare_scattering()[source]

Prepare a run containing an element capable of scattering neutrons

drtsans.tof.eqsans.prepare.prepare_sensitivity()[source]

Recipe to generate a sensitivity file from a flood run

drtsans.tof.eqsans.prepare.prepare_transmission()[source]

Prepare a run containing an element capable of scattering neutrons attenuator plus an attenuator

drtsans.tof.eqsans.reduce module

drtsans.tof.eqsans.reduce.load_w(run, low_tof_clip=0, high_tof_clip=0, dw=0.1, data_dir=None, output_workspace=None)[source]

Load a run, correct the TOF frame, and convert to wavelength

Parameters:
  • run (str) – Run number or filename. Passed onto Mantid’s Load algorithm

  • low_tof_clip (float) – Lower TOF clipping

  • high_tof_clip (float) – Upper TOF clipping

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

  • dw (float) – Wavelength bin width

Return type:

MatrixWorkspace

drtsans.tof.eqsans.reduction_api module

drtsans.tof.eqsans.reduction_api.BinningSetup

alias of binning_setup

drtsans.tof.eqsans.reduction_api.bin_i_with_correction(iq1d_in_frames, iq2d_in_frames, wl_frame, weighted_errors, user_qmin, user_qmax, num_x_bins, num_y_bins, num_q1d_bins, num_q1d_bins_per_decade, decade_on_center, bin1d_type, log_binning, annular_bin, wedges, symmetric_wedges, incoherence_correction_setup, iq1d_elastic_ref_fr, iq2d_elastic_ref_fr, raw_name, output_dir, output_filename='')[source]

Bin I(Q) in 1D and 2D with the option to do inelastic incoherent correction

Parameters:
  • iq1d_in_frames (list[IQmod]) – Objects containing 1D unbinned data I(|Q|). It will be used for scalar binned data

  • iq2d_in_frames (list[IQazimuthal]) – Objects containing 2D unbinned data I(Qx, Qy). It will be used for 2D binned data, and 1D wedge or annular binned data

  • wl_frame (int) – Index of the frame in iq1d_in_frames and iq2d_in_frames to bin and correct

  • weighted_errors (bool) – If True, the binning is done using the Weighted method

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

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

  • num_x_bins (int) – Number of bins in the x direction for 2D binning

  • num_y_bins (int) – Number of bins in the y direction for 2D binning

  • num_q1d_bins (int) – Number of bins for the 1d binning.

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

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

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

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

  • annular_bin (float) – Width of annular bin in degrees. 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

  • incoherence_correction_setup (CorrectionConfiguration) – Parameters for incoherence/inelastic scattering correction

  • iq1d_elastic_ref_fr (list[IQmod]) – Objects containing 1D unbinned data I(|Q|) for the elastic reference run

  • iq2d_elastic_ref_fr (list[IQazimuthal]) – Objects containing 2D unbinned data I(Qx, Qy) for the elastic reference run

  • raw_name (str) – Prefix for file to save inelastic incoherent correction (B) data

  • output_dir (str) – Output directory for I(Q) profiles

  • output_filename (str) – Output filename parsed from input configuration file (JSON)

Returns:

  • Binned and optionally corrected IQazimuthal

  • List of binned and optionally corrected 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[IQmod])

drtsans.tof.eqsans.reduction_api.prepare_data_workspaces(data: namedtuple, dark_current=None, flux_method=None, flux=None, mask_ws=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:

  • 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 (namedtuple) – (~mantid.dataobjects.Workspace2D, ~mantid.dataobjects.Workspace2D) raw workspace (histogram) for data and monitor

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

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

  • flux (str) – if flux_method is proton charge, then path to file containing the wavelength distribution of the neutron flux. If flux method is monitor, then path to file containing the flux-to-monitor ratios. if flux_method is time, then pass one log entry name such as duration or leave it as None for automatic log search.

  • mask_ws (Workspace2D) – Mask workspace

  • 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.tof.eqsans.reduction_api.process_transmission(transmission_ws, empty_trans_ws, transmission_radius, sensitivity_ws, flux_method, flux, prefix, type_name, output_dir, output_file_name)[source]
drtsans.tof.eqsans.reduction_api.remove_workspaces(reduction_config: Dict, instrument_name: str, prefix: str, sample_run_number, center_run_number, extra_run_numbers: List)[source]

Helping method to remove existing workspaces

drtsans.tof.eqsans.transmission module

drtsans.tof.eqsans.transmission.calculate_transmission(input_sample, input_reference, radius=None, radius_unit='mm', fit_function='name=LinearBackground', output_workspace=None, output_raw_transmission=None)[source]

Calculate the transmission coefficients at zero scattering angle from already prepared sample and reference data.

For EQ-SANS, one additional step fitting the values with an analytic wavelength-dependent function may be requested. In this case the fitted transmission values are stored in output_workspace and the raw transmission values can be optionally stored in workspace output_raw_transmissions.

Parameters:
  • input_sample (str, MatrixWorkspace) – Prepared sample workspace (possibly obtained with an attenuated beam)

  • input_reference (str, MatrixWorkspace) – Prepared direct beam workspace (possibly obtained with an attenuated beam)

  • radius (float) – Radius around the bean center for pixel integration, in milimeters. If None, radius will be obtained or calculated using input_reference.

  • radius_unit (str) – Either ‘mm’ or ‘m’, and only used in conjunction with option radius.

  • fit_function (str) – String representation of the fit function. See Mantid’s UserFunction or any of Mantid’s built-in functions. The default value represents a linear model. If this option is left as None or empty string, then no fitting is performed.

  • output_workspace (str) – Name of the output workspace containing the raw transmission values when fit_function is None, or the fitted transmission values when fit_function` is not None. If None, an anonymous hidden name will be automatically provided.

  • output_raw_transmission (str) – When fit_function is not None, this option allows to store the unfitted transmission values to a workspace. If the option is left as None, then the unfitted values are not kep.

Returns:

Workspace containing the raw transmission values when fit_function is None, and the fitted transmission values when fit_function` is not None.

Return type:

MatrixWorkspace

drtsans.tof.eqsans.transmission.fit_raw_transmission(input_workspace, fit_function='name=LinearBackground', output_workspace=None)[source]

Fit the wavelength dependence of the raw zero-angle transmission values with a model.

If working in frame skipping mode, apply the fit separately to the wavelength bands of the lead and skipped pulses.

Parameters:
  • input_workspace (MatrixWorkspace) – Input workspace containing the raw transmission values

  • output_workspace (str) – Name of the workspace containing the fitted transmission values and errors. If None, the input worskpace will be overwritten

  • fit_function (str) – String representation of the fit function. See Mantid’s fitting functions

Returns:

The fields of the returned ~collections.namedtuple are:

  • transmission: ~mantid.api.MatrixWorkspace containing the fitted transmissiom values and errors. The name of this workspace is the value of output_workspace

  • lead_transmission: ~mantid.api.MatrixWorkspace containing the fitted transmission values and errors of the lead pulse

  • lead_mantid_fit: return value of running Mantid’s Fit algorithm when fitting the raw transmission over the lead pulse wavelength range

  • skip_transmission: workspace containing the fitted transmission values and errors of the skip pulse. None if not working in frame skipping mode

  • skip_mantid_fit: return value of running Mantid’s Fit algorithm when fitting the raw transmission over the skip pulse wavelength range None if not working in frame skipping mode

Return type:

namedtuple

Module contents

class drtsans.tof.eqsans.BinningMethod(value)[source]

Bases: Enum

Binning method

NOWEIGHT = 1
WEIGHTED = 2
class drtsans.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.apply_solid_angle_correction(input_workspace)[source]

Apply solid angle correction. This uses drtsans.solid_angle_correction().

drtsans.tof.eqsans.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.tof.eqsans.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.tof.eqsans.beam_radius(input_workspace, unit='mm')[source]

Calculate the beam radius impinging on the detector bank.

\[R_{beam} = R_{sampleAp} + SDD * (R_{sampleAp} + R_{sourceAp}) / SSD\]
Parameters:
  • input_workspace (MatrixWorkspace, str) – Input workspace, contains all necessary info in the logs

  • unit (str) – Either ‘mm’ or ‘m’

Returns:

Estimated beam radius

Return type:

float

drtsans.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.calculate_transmission(input_sample, input_reference, radius=None, radius_unit='mm', fit_function='name=LinearBackground', output_workspace=None, output_raw_transmission=None)[source]

Calculate the transmission coefficients at zero scattering angle from already prepared sample and reference data.

For EQ-SANS, one additional step fitting the values with an analytic wavelength-dependent function may be requested. In this case the fitted transmission values are stored in output_workspace and the raw transmission values can be optionally stored in workspace output_raw_transmissions.

Parameters:
  • input_sample (str, MatrixWorkspace) – Prepared sample workspace (possibly obtained with an attenuated beam)

  • input_reference (str, MatrixWorkspace) – Prepared direct beam workspace (possibly obtained with an attenuated beam)

  • radius (float) – Radius around the bean center for pixel integration, in milimeters. If None, radius will be obtained or calculated using input_reference.

  • radius_unit (str) – Either ‘mm’ or ‘m’, and only used in conjunction with option radius.

  • fit_function (str) – String representation of the fit function. See Mantid’s UserFunction or any of Mantid’s built-in functions. The default value represents a linear model. If this option is left as None or empty string, then no fitting is performed.

  • output_workspace (str) – Name of the output workspace containing the raw transmission values when fit_function is None, or the fitted transmission values when fit_function` is not None. If None, an anonymous hidden name will be automatically provided.

  • output_raw_transmission (str) – When fit_function is not None, this option allows to store the unfitted transmission values to a workspace. If the option is left as None, then the unfitted values are not kep.

Returns:

Workspace containing the raw transmission values when fit_function is None, and the fitted transmission values when fit_function` is not None.

Return type:

MatrixWorkspace

drtsans.tof.eqsans.center_detector(input_workspace, center_x, center_y, component='detector1')[source]

Translate the beam center currently located at (center_x, center_y) by an amount (-center_x, -center_y), so that the beam center is relocated to the origin of coordinates on the XY-plane

Mantid algorithms used: MoveInstrumentComponent,

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

  • center_x (float) – in meters

  • center_y (float) – in meters

  • component (string) – name of the detector to be centered

drtsans.tof.eqsans.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.tof.eqsans.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.tof.eqsans.convert_to_q(ws, mode, resolution_function=<function eqsans_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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.fbc_options_json(reduction_input)[source]
drtsans.tof.eqsans.find_beam_center(input_workspace, method='center_of_mass', mask=None, mask_options={}, centering_options={}, solid_angle_method='VerticalTube')[source]

Calculate absolute coordinates of beam impinging on the detector. Usually employed for a direct beam run (no sample and not sample holder).

Mantid algorithms used:

FindCenterOfMassPosition, Integration,

Parameters:
  • input_workspace (str, MatrixWorkspace, IEventWorkspace)

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

  • 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.

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

Returns:

(X, Y, results) coordinates of the beam center (units in meters), dictionary of special parameters

Return type:

tuple

drtsans.tof.eqsans.fit_raw_transmission(input_workspace, fit_function='name=LinearBackground', output_workspace=None)[source]

Fit the wavelength dependence of the raw zero-angle transmission values with a model.

If working in frame skipping mode, apply the fit separately to the wavelength bands of the lead and skipped pulses.

Parameters:
  • input_workspace (MatrixWorkspace) – Input workspace containing the raw transmission values

  • output_workspace (str) – Name of the workspace containing the fitted transmission values and errors. If None, the input worskpace will be overwritten

  • fit_function (str) –

    String representation of the fit function. See Mantid’s fitting functions

Returns:

The fields of the returned ~collections.namedtuple are:

  • transmission: ~mantid.api.MatrixWorkspace containing the fitted transmissiom values and errors. The name of this workspace is the value of output_workspace

  • lead_transmission: ~mantid.api.MatrixWorkspace containing the fitted transmission values and errors of the lead pulse

  • lead_mantid_fit: return value of running Mantid’s Fit algorithm when fitting the raw transmission over the lead pulse wavelength range

  • skip_transmission: workspace containing the fitted transmission values and errors of the skip pulse. None if not working in frame skipping mode

  • skip_mantid_fit: return value of running Mantid’s Fit algorithm when fitting the raw transmission over the skip pulse wavelength range None if not working in frame skipping mode

Return type:

namedtuple

drtsans.tof.eqsans.load_all_files(reduction_input, prefix='', load_params=None)[source]

overwrites metadata for sample workspace

Workflow: 1. parse reduction_input 2. remove existing related workspaces with same run numbers 3. process beam center - output: load_params, reduction_input 4. adjust pixel heights and widths - output: load_params, reduction_input 5. load and optionally slice sample runs 6. load other runs: bkgd, empty, sample_trans, bkgd_trans

Returned namedtuple:
  • sample, background, empty, sample_transmission, background_transmission: namedtuple(data[ws], monitor[ws])

  • dark_current, sensitivity, mask: workspace

Returns:

Named tuple including all loaded workspaces

Return type:

namedtuple

drtsans.tof.eqsans.load_and_split_and_histogram(run, detector_offset=0.0, sample_offset=0.0, path_to_pixel=True, data_dir=None, output_workspace=None, output_suffix='', overwrite_instrument=True, pixel_calibration=False, bin_width=0.1, low_tof_clip=500, high_tof_clip=2000, center_x=None, center_y=None, centering_method='center_of_mass', centering_options={}, mask=None, keep_events=True, time_interval: float | List[float] | None = None, time_offset: float = 0.0, time_period: float | None = None, log_name=None, log_value_interval=None, reuse_workspace=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.

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

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

  • centering_method (str) – Method to calculate the beam center. Available methods are: - ‘center_of_mass’, invokes FindCenterOfMassPosition - ‘gaussian’, 2D Gaussian fit to beam center data

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

  • 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.

Returns:

(WorkspaceGroup, Bands): Reference to the workspace groups containing all the split workspaces

Return type:

~tuple

drtsans.tof.eqsans.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.tof.eqsans.load_config(source, config_dir='/SNS/EQSANS/shared/instrument_configuration')[source]

Load the configuration file appropriate to the input source info

Parameters:
  • source (str) – The filename (absolute path or relative) to a configuration file or a run-number

  • config_dir (str) – Directory containing configuration files

Returns:

keys are entries in the file

Return type:

dict

drtsans.tof.eqsans.load_dark_current_workspace(dark_current_filename, output_workspace)[source]

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

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

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

drtsans.tof.eqsans.load_events(run, pixel_calibration=False, detector_offset=0.0, sample_offset=0.0, path_to_pixel=True, data_dir=None, output_workspace=None, output_suffix='', **kwargs)[source]

Load events with initial corrections for geometry and time-of-flight

Note: Detector is translated along the Z-axis by the value specified in keyword detectorZ of the logs. The final sample to detector distance is detectorZ + detector_offset - sample_offset.

Mantid algorithms used: LoadEventNexus,

Parameters:
  • run (int, str) – Examples: 55555 or EQSANS_55555 or file path.

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

  • 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.

  • path_to_pixel (bool) – When correcting the recorded time of flight of each neutron, use the path from the moderator to the detector pixel (True) or to the center of the detector panel (False). The latter for comparison to the old data reduction.

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

  • output_workspace (str) – If not specified it will be EQSANS_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.

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

Returns:

Reference to the events workspace

Return type:

IEventWorkspace

drtsans.tof.eqsans.load_events_and_histogram(run, pixel_calibration=False, detector_offset=0.0, sample_offset=0.0, path_to_pixel=True, data_dir=None, output_workspace=None, output_suffix='', bin_width=0.1, low_tof_clip=500, high_tof_clip=2000, center_x=None, center_y=None, centering_method='center_of_mass', centering_options={}, mask=None, monitors=False, keep_events=True, sample_bands=None, **kwargs)[source]

Load events from one or more NeXus files with initial corrections for geometry, time-of-flight and beam center. Convert to wavelength and sum.

Note: Detector is translated along the Z-axis by the value specified in keyword detectorZ of the logs. The final sample to detector distance is detectorZ + detector_offset - sample_offset.

Parameters:
  • run (list of runs to load) – Examples: 55555 or EQSANS_55555 or file path or EQSANS_55555, EQSANS_55556

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

  • 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.

  • path_to_pixel (bool) – When correcting the recorded time of flight of each neutron, use the path from the moderator to the detector pixel (True) or to the center of the detector panel (False). The latter for comparison to the old data reduction.

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

  • output_workspace (str) – If not specified it will be EQSANS_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.

  • bin_width (float) – Bin width for the output workspace, in Angstroms.

  • low_tof_clip (float) – Ignore events with a time-of-flight (TOF) smaller than the minimal TOF plus this quantity.

  • high_tof_clip (float) – Ignore events with a time-of-flight (TOF) bigger than the maximal TOF minus this quantity.

  • 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 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 y=0.

  • centering_method (str) – Method to calculate the beam center. Available methods are: - ‘center_of_mass’, invokes FindCenterOfMassPosition - ‘gaussian’, 2D Gaussian fit to beam center data

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

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

  • monitors (boolean) – Option to load the monitors as well as the data, if False monitor will be None

  • keep_events (bool) – The final histogram will be an EventsWorkspace if True.

  • sample_bands (bands or None) – sample bands

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

Returns:

Fields of namedtuple data: the loaded data monitor: the monitor for the data, if monitors==True else None

Return type:

namedtuple

drtsans.tof.eqsans.load_events_monitor(run, data_dir=None, output_workspace=None)[source]

Load monitor events with initial corrections for geometry and time-of-flight

Parameters:
  • run (int, str) – Examples: 55555 or EQSANS_55555 or file path.

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

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.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.tof.eqsans.normalize_by_flux(input_workspace, flux, method='proton charge', monitor_workspace=None, output_workspace=None)[source]

Normalize counts by several methods to estimate the neutron flux.

This function calls specialized normalizing functions based on method argument. Those functions are: - normalize_by_time - normalize_by_monitor - normalize_by_proton_charge_and_flux

Parameters:
  • input_workspace (MatrixWorkspace) – Input workspace, binned in wavelength

  • flux (str) – If method is ‘proton charge’, flux is the path to the file containing the wavelength distribution of the neutron flux. If method is ‘monitor’, then flux is the path to the file containing a pre-measured flux-to-monitor ratio spectrum. If flux_method is ‘time’, then pass one log entry name such as ‘duration’ or pass None for automatic log search.

  • method (str) – Either ‘proton charge’, ‘monitor’, or ‘time’

  • monitor_workspace (str, MatrixWorkspace) – Prepared monitor workspace

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.normalize_by_monitor(input_workspace, flux_to_monitor, monitor_workspace, output_workspace=None)[source]

Normalizes the input workspace by monitor count and flux-to-monitor ratio.

Mantid algorithms used: RebinToWorkspace, RemoveSpectra, CloneWorkspace, SplineInterpolation, Multiply, Divide, DeleteWorkspace

Parameters:
  • input_workspace (str, MatrixWorkspace) – Workspace to be normalized, rebinned in wavelength.

  • flux_to_monitor (str, MatrixWorkspace) – Flux to monitor ratio. A file path or a workspace resulting from calling load_flux_to_monitor_ratio_file.

  • monitor_workspace (str, MatrixWorkspace) – Counts from the monitor.

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.normalize_by_proton_charge_and_flux(input_workspace, flux, output_workspace=None)[source]

Normalizes the input workspace by proton charge and measured flux

Mantid algorithms used: RebinToWorkspace, Divide, DeleteWorkspace, NormaliseByCurrent,

Parameters:
  • input_workspace (str, MatrixWorkspace) – Workspace to be normalized, rebinned in wavelength.

  • flux (Workspace) – Measured beam flux file ws, usually the output of load_beam_flux_file

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.normalize_by_thickness(input_workspace, thickness)[source]

Normalize input workspace by thickness

Parameters:
Return type:

MatrixWorkspace

drtsans.tof.eqsans.normalize_by_time(input_workspace, log_key=None, output_workspace=None)[source]

Divide the counts by the duration of the run

Mantid algorithms used: Scale

Parameters:
  • input_workspace (str, MatrixWorkspace)

  • log_key (str) – Use this log entry to figure out the run duration. If None, logs are sequentially searched for keys duration, start_time, proton_charge, and timer, in order to find out the duration.

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.normalize_dark_current(dark_workspace, data_workspace, output_workspace=None)[source]

Scale and Rebin in wavelength a dark current workspace with information from a data workspace.

Rescale and rebin to the data workspace according to:

\[frame\_width\_clipped / (frame\_width * n\_bins * duration) * I\_dc(x, y)\]

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: Integration, CreateWorkspace DeleteWorkspace

Parameters:
  • dark_workspace (str, EventsWorkspace) – Dark current workspace with units in time-of-flight

  • data_workspace (str, MatrixWorkspace) – Sample scattering with intensities versus wavelength

  • 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, dark current rebinned to wavelength and rescaled

Return type:

MatrixWorkspace

drtsans.tof.eqsans.plot_reduction_output(reduction_output, reduction_input, imshow_kwargs=None)[source]
drtsans.tof.eqsans.pre_process_single_configuration(sample_ws_raw: namedtuple, sample_trans_ws=None, sample_trans_value=None, bkg_ws_raw=None, bkg_trans_ws=None, bkg_trans_value=None, theta_dependent_transmission=True, dark_current=None, flux_method=None, flux=None, mask_ws=None, mask_panel=None, mask_btp=None, solid_angle=True, sensitivity_workspace=None, output_workspace=None, output_suffix='', thickness=1.0, absolute_scale_method='standard', empty_beam_ws=None, beam_radius=None, absolute_scale=1.0, keep_processed_workspaces=True)[source]

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

Parameters:
  • sample_ws_raw (namedtuple) – (~mantid.dataobjects.Workspace2D, ~mantid.dataobjects.Workspace2D) raw data histogram workspace and monitor

  • sample_trans_ws (Workspace2D) – optional histogram workspace for sample transmission (already prepared)

  • sample_trans_value (float) – optional value for sample transmission

  • bkg_ws_raw (Workspace2D) – optional raw histogram workspace for background

  • bkg_trans_ws (Workspace2D) – optional histogram workspace for background transmission

  • bkg_trans_value (float) – optional value for background transmission

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

  • dark_current (Workspace2D) – dark current workspace

  • flux_method (str) – normalization by time or monitor

  • mask_ws (Workspace2D) – user defined mask

  • mask_panel (str) – mask fron or back panel

  • mask_btp (dict) – optional bank, tube, pixel to mask

  • solid_angle (bool) – flag to apply solid angle

  • sensitivity_workspace (Workspace2D) – workspace containing sensitivity

  • output_workspace (str) – output workspace name

  • output_suffix (str) – suffix for output workspace

  • thickness (float) – sample thickness (cm)

  • absolute_scale_method (str) – method to do absolute scaling (standard or direct_beam)

  • empty_beam_ws (Workspace2D) – empty beam workspace for absolute scaling

  • beam_radius (float) – beam radius for absolute scaling

  • absolute_scale (float) – absolute scaling value for standard method

  • keep_processed_workspaces (bool) – flag to keep the processed background workspace

Returns:

Reference to the processed workspace

Return type:

Workspace2D

drtsans.tof.eqsans.prepare_data(data, pixel_calibration=False, detector_offset=0, sample_offset=0, bin_width=0.1, low_tof_clip=500, high_tof_clip=2000, center_x=None, center_y=None, dark_current=None, flux_method=None, flux=None, mask=None, mask_panel=None, btp={}, solid_angle=True, sensitivity_file_path=None, sensitivity_workspace=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='')[source]

Load an EQSANS 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

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

  • 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.

  • bin_width (float) – Bin width for the output workspace, in Angstroms.

  • low_tof_clip (float) – Ignore events with a time-of-flight (TOF) smaller than the minimal TOF plus this quantity.

  • high_tof_clip (float) – Ignore events with a time-of-flight (TOF) bigger than the maximal TOF minus this quantity.

  • 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 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 y=0.

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

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

  • flux (str) – if flux_method is proton charge, then path to file containing the wavelength distribution of the neutron flux. If flux method is monitor, then path to file containing the flux-to-monitor ratios. if flux_method is time, then pass one log entry name such as duration or leave it as None for automatic log search.

  • 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.

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

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

  • source_aperture_diameter (float, None) – source aperture diameter in unit meter

  • 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-resolutio 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.tof.eqsans.prepare_data_workspaces(data: namedtuple, dark_current=None, flux_method=None, flux=None, mask_ws=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:

  • 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 (namedtuple) – (~mantid.dataobjects.Workspace2D, ~mantid.dataobjects.Workspace2D) raw workspace (histogram) for data and monitor

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

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

  • flux (str) – if flux_method is proton charge, then path to file containing the wavelength distribution of the neutron flux. If flux method is monitor, then path to file containing the flux-to-monitor ratios. if flux_method is time, then pass one log entry name such as duration or leave it as None for automatic log search.

  • mask_ws (Workspace2D) – Mask workspace

  • 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.tof.eqsans.prepare_monitors(data, bin_width=0.1, output_workspace=None)[source]

Loads monitor counts, correct TOF, and transforms to wavelength.

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

  • bin_width (float) – Bin width for the output workspace, in Angstroms.

  • output_workspace (str) – Name of the output workspace. If None, then it will be EQSANS_XXXXX_monitors with number XXXXX determined from data.

Return type:

MatrixWorkspace

drtsans.tof.eqsans.reduce_single_configuration(loaded_ws: namedtuple, reduction_input, prefix='', skip_nan=True, not_apply_incoherence_correction: bool = False)[source]

Reduce samples from raw workspaces including 1. prepare data 1.

This is the main entry point of reduction

Input loaded workspaces as namedtuple:
  • sample, background, empty, sample_transmission, background_transmission: namedtuple(data[ws], monitor[ws])

  • dark_current, sensitivity, mask: workspace

Parameters:
  • loaded_ws (namedtuple) – loaded workspaces, usually the return value of load_all_files()

  • reduction_input (dict) – reduction configuration

  • prefix

  • skip_nan

  • not_apply_incoherence_correction (bool) – If true, then no incoherence scattering correction will be applied to reduction overriding JSON

Returns:

list of IofQ_output: [‘I2D_main’, ‘I1D_main’]

Return type:

~list

drtsans.tof.eqsans.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.tof.eqsans.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.tof.eqsans.sample_aperture_diameter(run, unit='mm')[source]

Find the sample aperture diameter from the logs.

Log keys searched are ‘sample_aperture_diameter’ (override beamslit4) and ‘beamslit4’.

Parameters:
  • run (Mantid Run instance, MatrixWorkspace, file name, run number) – Input from which to find the aperture

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

Returns:

Sample aperture diameter, in requested units

Return type:

float

drtsans.tof.eqsans.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.tof.eqsans.save_ascii_1D(wksp, title, filename)[source]

Save the I(q) workspace in Ascii format

Parameters:
  • wksp (MatrixWorkspace) – Workspace containing only one spectrum (the I(q) curve)

  • title (string) – first line of the ascii file

  • filename (string) – The output filename

drtsans.tof.eqsans.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.tof.eqsans.save_nexus(input_workspace, title, filename)[source]

Write the given Mantid workspace to a NeXus file.

Parameters:
  • input_workspace (MatrixWorkspace) – Name of the workspace to be saved

  • title (string) – Title to describe the saved worksapce

  • filename (string) – The bame of the NeXus file to write, as a full or relative path. Allowed extensions: [.nxs, .nx5, .xml]

drtsans.tof.eqsans.save_nist_dat(input_workspace, filename)[source]

Save I(Qx, Qy) data to a text file compatible with NIST and DANSE readers

Parameters:
  • input_workspace (MatrixWorkspace) – Workspace to be saved

  • filename (string) – Filename of the output text file. Allowed extensions: [.dat]

drtsans.tof.eqsans.save_xml_1D(wksp, title, filename)[source]

Save the I(q) workspace in SaveCanSAS (XML) format

Parameters:
  • wksp (MatrixWorkspace) – Workspace containing only one spectrum (the I(q) curve)

  • title (string) – Text to append to Process section

  • filename (string) – The output filename

drtsans.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.source_aperture_diameter(run, unit='mm')[source]

Find the source aperture diameter

Either report log vale or compute this quantity.

After the moderator (source) there are three consecutive discs (termed wheels), each with eight holes in them (eight slits). Appropriate log entries (VbeamSlit, VbeamSlit2, VbeamSlit3) indicate the slit index for each of the three wheels. Thus, the position of the source and the source aperture are not the same. The most restrictive slit will define the source aperture

Log entries beamslit, beamslit2, and beamslit3 store the required rotation angle for each wheel in order to align the appropriate slit with the neutron beam. These angles are not used in reduction.

If the aperture is computed, then the value is stored in log key “source_aperture_diameter”, with mili meter units

Parameters:
  • run (Mantid Run instance, MatrixWorkspace, file name, run number)

  • unit (str) – Length unit, either ‘m’ or ‘mm’

Returns:

Source aperture diameter, in requested units

Return type:

float

drtsans.tof.eqsans.source_aperture_sample_distance(run, unit='mm')[source]

Find the distance from the source aperture to the sample.

Either report log vale or compute this quantity. If the distance has to be computed, then stores the value in log key “source_aperture_sample_distance”, with mili-meter units.

Parameters:
  • run (Mantid Run instance, MatrixWorkspace, file name, run number)

  • unit (str) – Length unit, either ‘m’ or ‘mm’

Return type:

float

drtsans.tof.eqsans.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.tof.eqsans.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.tof.eqsans.split_by_frame(input_workspace, *args, **kwargs)[source]

Split the output of convert_to_q into a list of outputs, one for each frame.

Parameters:
Returns:

A list with namedtuples

Return type:

~list

drtsans.tof.eqsans.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.tof.eqsans.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.tof.eqsans.subtract_background(input_workspace, background, scale=1.0, scale_error=0.0, output_workspace=None)[source]

Subtract a prepared background from a prepared sample.

Perform a rebin if sample and background have different binning.

Mantid algorithms used: CloneWorkspace CreateSingleValuedWorkspace Minus Multiply RebinToWorkspace

Parameters:
  • input_workspace (str, MatrixWorkspace, IQmod, IQazimuthal) – Sample workspace.

  • background (str, MatrixWorkspace, IQmod, IQazimuthal) – Background workspace.

  • scale (float) – Rescale background intensities by this multiplicative factor before subtraction from the sample.

  • scale_error (float) – Uncertainty in scale factor

  • output_workspace (str) – Name of the sample corrected by the background. If None, then input_workspace will be overwritten. In the case of using data from dataobjects, this parameter is ignored.

Return type:

MatrixWorkspace

drtsans.tof.eqsans.subtract_dark_current(input_workspace, dark, output_workspace=None)[source]
Parameters:
  • input_workspace (int, str, IEventWorkspace) – The workspace to be normalized

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

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

Return type:

MatrixWorkspace

drtsans.tof.eqsans.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.tof.eqsans.transform_to_wavelength(input_workspace, bin_width=0.1, low_tof_clip=0.0, high_tof_clip=0.0, keep_events=True, interior_clip=True, output_workspace=None, bands=None)[source]

API function that converts corrected TOF’s to Wavelength.

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

  • bin_width (float) – Bin width for the output workspace, in Angstroms.

  • low_tof_clip (float) – Ignore events with a time-of-flight (TOF) smaller than the minimal TOF plus this quantity.

  • high_tof_clip (float) – Ignore events with a time-of-flight (TOF) bigger than the maximal TOF minus this quantity.

  • keep_events (bool) – The final histogram will be an EventsWorkspace if True.

  • interior_clip (bool) – If True, trim slow neutrons from the lead pulse (using high_tof_clip) and fast neutrons from the skip pulse (using low_tof_clip)

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

Returns:

~mantid.api.IEventWorkspace, ~mantid.api.MatrixWorkspace

Return type:

tuple

drtsans.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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.tof.eqsans.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