drtsans package

Subpackages

Submodules

drtsans.absolute_units module

Links to Mantid algorithms DeleteWorkspace <https://docs.mantidproject.org/nightly/algorithms/DeleteWorkspace-v1.html> Divide <https://docs.mantidproject.org/nightly/algorithms/Divide-v1.html> Multiply <https://docs.mantidproject.org/nightly/algorithms/Multiply-v1.html>

drtsans.absolute_units.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.api module

drtsans.api.half_polarization(flipper_off_workspace, flipper_on_workspace, polarization, efficiency, spin_up_workspace=None, spin_down_workspace=None)[source]

Calculate the spin up/down workspaces from flipper on/off.

Mantid algorithms used: RenameWorkspace

Parameters:
  • flipper_off_workspace (str, MatrixWorkspace) – Flipper off measurement

  • flipper_on_workspace (str, MatrixWorkspace) – Flipper on measurement

  • polarization (str, MatrixWorkspace) – Polarization state

  • efficiency (str, MatrixWorkspace) – Flipper efficiency

  • spin_up_workspace (str) – Name of the resulting spin up workspace. If None, then flipper_off_workspace will be overwritten.

  • spin_down_workspace (str) – Name of the resulting spin down workspace. If None, then flipper_on_workspace will be overwritten.

Return type:

py:obj:tuple of 2 ~mantid.api.MatrixWorkspace

drtsans.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.auto_wedge module

drtsans.auto_wedge.getWedgeSelection(data2d, q_min, q_delta, q_max, azimuthal_delta, peak_width=0.25, background_width=1.5, signal_to_noise_min=2.0, peak_search_window_size_factor=0.6, debug_dir='/tmp/') List[List[Tuple[float, float]]][source]

Calculate azimuthal binning ranges automatically based on finding peaks in the annular ring. The output of this is intended to be used in select_i_of_q_by_wedge().

Parameters:
  • data2d (Azimuthal)

  • q_min (float) – The left bin boundary for the first Q-bin

  • q_delta (float) – The size of the bins in Q

  • q_max (float) – The left bin boundary for the last Q-bin

  • azimuthal_delta (float) – The size of the bins in azimuthal angle

  • peak_width (float) – Percent of full-width-half-max (FWHM) of the peak to define the signal to be within when determining the final range for azimuthal binning.

  • background_width (float) – Percent of full-width-half-max (FWHM) of the peak to define the background between peaks to be within when determining the final range for azimuthal binning.

  • signal_to_noise_min (float) – Minimum signal to noise ratio for the data to be considered “fittable”

  • peak_search_window_size_factor (float) – Factor of 360 / (num peaks) to construct the search range for wedge peak

  • debug_dir (str) – Full path of the output directory for debugging output files

  • Results

  • =======

  • ~list – list containing 2 lists each contains 2 2-tuples as [[(peak1_min, peak1_max), (peak2_min, peak2_max)], [(..., ...), (..., ...)]]

drtsans.beam_finder module

drtsans.beam_finder.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.beam_finder.fbc_options_json(reduction_input)[source]
drtsans.beam_finder.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.chopper module

This module provides class DiskChopper representing a rotating chopper with an aperture of certain width. The main goal is to find the set of neutron wavelength bands transmitted by the chopper, given definite chopper settings such as aperture and starting phase.

class drtsans.chopper.DiskChopper(to_source, aperture, speed, sensor_phase, offset=0)[source]

Bases: object

Rotating disk chopper with an aperture of a certain width letting neutrons through.

The angular position of the middle of the chopper aperture at the moment a neutron pulse happens is given by a metadata entry (the sensor phase) and an additional angle (the offset). The offset server to calibrate the value reported by the metadata.

Parameters:
  • to_source (float) – Distance to the neutron source (moderator) in meters

  • aperture (float) – Width of the opening window letting neutrons through, in degrees

  • speed (float) – rotational frequency, in Hz

  • sensor_phase (float) – phase reported by the installed sensor in the metadata. It’s the time for the chopper to rotate by and angle created by the following three points: (1) the center of the chopper, (2) the middle of the aperture, and (3) the point of intersection of the chopper and the pulse prompt neutrons. Units are micro seconds

  • offset (float) – Additional phase difference to be added to the sensor_phase due to miscalibrations. The offset calibrates the value sensor_phase reported by the metadata. Units are in micro seconds.

property closing_phase

Time (starting from the current pulse) when the closing edge of the chopper aperture will intersect with the neutron beam axis, in micro seconds.

property cutoff_wl

Discard neutrons transmitted by the disk chopper having a wavelength above this quantity. This property can override the default cutoff wavelength _cutoff_wl.

property opening_phase

Time (starting from the current pulse) when the opening edge of the chopper aperture will intersect with the neutron beam axis, in micro seconds.

property period

Time span required by the chopper for a full spin, in micro seconds.

property phase

Time (starting from the current pulse) when the middle of the chopper aperture will intersect with the neutron beam axis, in micro seconds.

property pulse_width

Neutrons of a given wavelength \(\lambda\) emitted from the moderator have a distribution of delayed times that depends on the wavelength, and is characterized by a \(FWHM(\lambda) \simeq pulsewidth \cdot \lambda\). This property can override the default pulse width _pulse_width.

property rewind

Spin the chopper backwards until the chopper aperture intersects with the neutron beam axis. At this point, the opening_phase will be negative, and the closing_phase will be positive.

Returns:

Opening phase, in micro seconds. The opening phase will be negative (most likely) or zero.

Return type:

float

tof(wavelength, delay=0, pulsed=False)[source]

Convert wavelength to measured time-of-flight, for a neutron that has traveled the distance from the moderator to the chopper.

The measured time of flight \(t_m\) plus the additional delay \(d\) is equal to the real time of flight \(t_r\) plus the delayed emission time from the moderator \(p \lambda\), where \(p\) is constant _pulse_width.

\[ \begin{align}\begin{aligned}t_m + d = t_r + p \lambda\\D = t_r / v\\v = \frac{h}{m\lambda}\end{aligned}\end{align} \]

where \(D\) is the distance from moderator to chopper and \(v\) is the neutron velocity. Solving this system of equations for \(t_m\), one obtains

\[t_m = \lambda \frac{D + hp/m}{h/m} - d\]
Parameters:
  • wavelength (float) – wavelength of the neutron, in micro seconds.

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

time-of-flight, in micro seconds.

Return type:

float

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

Wavelength bands transmitted by the chopper aperture. 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

property transmission_duration

Time span taking the chopper to spin an angle equal to its aperture, in micro seconds.

wavelength(tof, delay=0, pulsed=False)[source]

Convert time-of-flight to neutron wavelength, for a neutron that has traveled the distance from the moderator to the chopper.

The measured time of flight \(t_m\) plus the additional delay \(d\) is equal to the real time of flight \(tof\) plus the delayed emission time from the moderator \(p \lambda\), where \(p\) is constant _pulse_width.

\[ \begin{align}\begin{aligned}t_m + d = tof + p \lambda\\D = tof / v\\v = \frac{h}{m\lambda}\end{aligned}\end{align} \]

where \(D\) is the distance from moderator to chopper and \(v\) is the neutron velocity. Solving this system of equations for \(\lambda\), one obtains

\[\lambda = \frac{h}{m} \frac{t_m + d}{D + hp/m}\]
Parameters:
  • tof (float) – time of flight, in micro seconds

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

Neutron wavelength (in Angstroms). Returns zero for negative tof.

Return type:

float

drtsans.dark_current module

drtsans.dark_current.counts_in_detector(input_workspace)[source]

Find the total number of neutron counts in each detector pixel.

In a detector pixel has no counts, then the error of the zero counts is set to one.

Parameters:

input_workspace (str, EventsWorkspace) – Usually a dark current workspace for which we need to know the total number of counts per pixel-detector

Returns:

counts, error in the counts

Return type:

tuple

drtsans.dark_current.duration(input_workspace, log_key=None)[source]

Compute the duration of the workspace by iteratively searching the logs for the following keys: ‘duration’, ‘start_time/end_time’, and ‘timer’.

Parameters:
  • input_workspace (str, MatrixWorkspace) – Usually the dark current workspace

  • log_key (str) – If a log entry is passed, only the contents under this log entry are searched. No iterative search over the default values is performed.

Returns:

Fields of the namedtuple: - value: float, contents under the log - log_key: str, log used to return the duration

Return type:

namedtuple

drtsans.dataobjects module

This module contains data objects for storing the various projections of I(Q).

class drtsans.dataobjects.DataType(value)[source]

Bases: Enum

An enumeration.

IQ_AZIMUTHAL = 'IQazimuthal'
IQ_CRYSTAL = 'IQcrystal'
IQ_MOD = 'IQmod'
WORKSPACE2D = 'Workspace2D'
class drtsans.dataobjects.IQazimuthal(intensity, error, qx, qy, delta_qx=None, delta_qy=None, wavelength=None)[source]

Bases: IQazimuthal

This class holds the information for the azimuthal projection, I(Qx, Qy). The resolution terms, (delta_qx, delta_qy) and wavelength fields are optional.

All of the arrays must be 1-dimensional or 2-dimensional and matching length. For the 1-dimensional case, all of the arrays must be parallel (same length). For the 2-dimensional case, (intensity, error, delta_qx, delta_qy, wavelength) must all be parallel. However, for (qx, qy), they must either (both) be 2-dimensional and parallel, or (both) 1-dimensional with len(qx) == intensity.shape[0] and len(qy) == intensity.shape[1].

if intensity is 2D, and qx and qy are 1D: In this constructor, it is assumed that intensity 2D array will match qx = [[qx0, qx1, …], [qx0, qx1, …], …] qy = [[qy0, qy0, …], [qy1, qy1, …], …] because qx and qy will be created in such style.

be_finite()[source]

Remove NaN by flattening first

Returns:

I(qx, qy, wavelength) with NaN removed

Return type:

IQazimuthal

concatenate(other)[source]

Append additional data points from another ~drtsans.dataobjects.IQazimuthal object and return the composite as a new ~drtsans.dataobjects.IQazimuthal object.

Parameters:

other (IQazimuthal) – Additional data points.

Return type:

IQazimuthal

id()[source]
ravel()[source]

Create a new ~drtsans.dataobjects.IQazimuthal with all of the arrays flattened

class drtsans.dataobjects.IQcrystal(intensity, error, qx, qy, qz, delta_qx=None, delta_qy=None, delta_qz=None, wavelength=None)[source]

Bases: IQazimuthal

This class holds the information for the crystallographic projection, I(Qx, Qy, Qz). All of the arrays must be 1-dimensional and parallel (same length). The resolution terms, (delta_qx, delta_qy, delta_qz) and wavelength fields are optional.

id()[source]
class drtsans.dataobjects.IQmod(intensity, error, mod_q, delta_mod_q=None, wavelength=None)[source]

Bases: IQmod

This class holds the information for I(Q) scalar. All of the arrays must be 1-dimensional and parallel (same length). The delta_mod_q and wavelength fields are optional.

be_finite()[source]
concatenate(other)[source]

Append additional data points from another ~drtsans.dataobjects.IQmod object and return the composite as a new ~drtsans.dataobjects.IQmod object.

Parameters:

other (IQmod) – Additional data points.

Return type:

IQmod

extract(selection)[source]

Extract a subset of data points onto a new ~drtsans.dataobjects.IQmod object.

Examples: - IQmod().extract(42) # extract data point number 42 - IQmod().extract(slice(None, None, 2)) # extract every other data point - IQmod().extract(IQmod().mod_q < 0.1) # extract points with Q < 0.1

Parameters:

selection (int, slice, ndarray) – Any selection that can be passed onto a ~numpy.ndarray

Return type:

IQmod

id()[source]
static read_csv(file, sep=' ')[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 IQmod iq = IQmod.read_csv(file_name) `

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

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

Return type:

IQmod

sort(key='mod_q')[source]

Sort the data points according to one of the components of the ~drtsans.dataobjects.IQmod object.

Parameters:

key (str) – Component prescribing the sorting order. Default sorting is by increasing Q value.

Return type:

IQmod

to_csv(file_name, sep=' ', float_format='%.6E', skip_nan=True)[source]

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

Parameters:
  • file_name (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

to_workspace(name=None)[source]
drtsans.dataobjects.getDataType(obj)[source]
drtsans.dataobjects.verify_same_q_bins(iq0, iq1, raise_exception_if_diffrent=False, tolerance=None)[source]

Verify whether 2 I(Q) has the same range of Q

Parameters:
Returns:

True if they are same

Return type:

bool

drtsans.detector module

class drtsans.detector.Component(workspace, component_name)[source]

Bases: object

Stores information about the component

dim_x = -1
dim_y = -1
dims = -1
first_index = -1
masked_ws_indices()[source]

return an array with True or False if a detector is either masked or not for all the component

Returns:

array with True or False if a detector is either masked or not for all the component

Return type:

bool np.array

monitor_indices()[source]
class drtsans.detector.Detector(workspace, component_name)[source]

Bases: object

Auxiliary class that has all the information about a detector It allows to read tube by tube.

get_current_ws_indices()[source]

First and last workspace indices for the currently considered tube.

Return type:

tuple

get_current_ws_indices_range()[source]

Array of workspace indexes for the currently considered tube.

Return type:

ndarray

get_pixels_infinite()[source]

Pixel mask for pixels with non-finite intensities in the currently considered tube. Returns an array of booleans for this tube where the pixel count is EMPTY_DBL

Returns:

Array of Bool values, with True for the pixels with non-finite intensities, and False otherwise.

Return type:

ndarray

get_pixels_masked()[source]

Pixel masks for the currently considered tube.

Returns:

Array of Bool values, with True for the masked pixels and False otherwise.

Return type:

ndarray

get_ws_data()[source]

Intensities and associated uncertainties for the currently considered tube.

Returns:

A two-item tuple containing, in this order, intensites and uncertainties in the shape of ~numpy.ndarray.

Return type:

tuple

get_y_coordinates()[source]

Y-coordinates of the pixels for the currently considered tube.

Return type:

ndarray

next_tube()[source]

Initializes/ updates attributes _current_start_ws_index and _current_stop_ws_index

drtsans.determine_bins module

class drtsans.determine_bins.BinningParams(min, max, bins)

Bases: tuple

bins

Alias for field number 2

max

Alias for field number 1

min

Alias for field number 0

class drtsans.determine_bins.Bins(edges, centers)

Bases: tuple

centers

Alias for field number 1

edges

Alias for field number 0

drtsans.determine_bins.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.determine_bins.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.frame_mode module

class drtsans.frame_mode.FrameMode(value)[source]

Bases: Enum

Selects if instrument operating in frame-skipping mode

not_skip = 0
skip = 1

drtsans.geometry module

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

Find and return the sample aperture diameter from the logs.

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

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

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

Return type:

float

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

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

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

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

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

Return type:

float

drtsans.geometry.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.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.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.instruments module

class drtsans.instruments.InstrumentEnumName(value)[source]

Bases: Enum

An enumeration.

BIOSANS = <mantid.kernel._kernel.InstrumentInfo object>
EQSANS = <mantid.kernel._kernel.InstrumentInfo object>
GPSANS = <mantid.kernel._kernel.InstrumentInfo object>
UNDEFINED = None
static names()[source]

Standard names for all instruments, in alphabetical order

drtsans.instruments.instrument_enum_name(input_query)[source]

Resolve the instrument name as a unique enumeration.

Parameters:

input_query (str, MatrixWorkspace, IEventsWorkspace) – string representing a filepath, a valid instrument name, or a Mantid workspace containing an instrument

Returns:

The name of the instrument as one of the InstrumentName enumerations

Return type:

InstrumentEnumName

drtsans.instruments.instrument_standard_name(input_query)[source]

Resolve the standard instrument name.

Parameters:

input_query (str, MatrixWorkspace, IEventsWorkspace) – string representing a filepath, a valid instrument name, or a Mantid workspace containing an instrument

Returns:

The name of the instrument as the string representation of one of the InstrumentName enumerations

Return type:

str

drtsans.instruments.is_time_of_flight(input_query)[source]

Find if the instrument is a time-of-flight one

Parameters:

input_query (str, MatrixWorkspace, IEventsWorkspace, InstrumentEnumName) – string representing a valid instrument name, or a Mantid workspace containing an instrument

Return type:

bool

drtsans.integrate_roi module

drtsans.integrate_roi.integrate_detector_roi(workspace, roi_det_list)[source]

Integrate neutron counts in ROI of detectors (pixels)

Integrate neutron counts and uncertainties in ROI of detectors

Parameters:
  • workspace (String or MatrixWorkspace) – Name of workspace or Workspace instance

  • roi_det_list (List of integers) – Workspace indexes for the detectors in ROI

Returns:

Integrated intensity, Integrated uncertainties

Return type:

float, float

drtsans.iq module

class drtsans.iq.BinningMethod(value)[source]

Bases: Enum

Binning method

NOWEIGHT = 1
WEIGHTED = 2
class drtsans.iq.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.iq.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.iq.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.iq.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.iq.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.iq.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.iq.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.iq.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.iq.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.load module

drtsans.load.load_and_split(run, data_dir=None, output_workspace=None, output_suffix='', overwrite_instrument=True, pixel_calibration=False, detector_offset=0.0, sample_offset=0.0, 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, monitors=False, instrument_unique_name=None, is_mono=None, **kwargs)[source]

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

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

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

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

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

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

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

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

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

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

  • time_interval (float or list of floats) – 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, in seconds. 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.

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

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

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

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

Returns:

Reference to the workspace groups containing all the split workspaces

Return type:

WorkspaceGroup

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

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

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

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

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

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

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

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

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

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

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

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

Returns:

Reference to the events workspace

Return type:

IEventWorkspace

drtsans.load.move_instrument(workspace, sample_offset, detector_offset, is_mono=False, sample_si_name=None, si_window_to_nominal_distance=None)[source]

Move instrument sample and detector

Parameters:
  • workspace – Workspace with instrument’s sample or detector translated along z-axis

  • sample_offset (float) – sample offset in unit meter

  • detector_offset (float) – detector offset in unit meter

  • is_mono (bool) – Flag that it belongs to a mono-SANS

  • sample_si_name (str) – Name of Sample to silicon window name

  • si_window_to_nominal_distance (float or None) – distance between Silicon window and sample in unit of meter

Returns:

Workspace with instrument moved

Return type:

IEventWorkspace, MatrixWorkspace

drtsans.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.mask_utils module

drtsans.mask_utils.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.mask_utils.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.meta_data module

drtsans.meta_data.set_meta_data(workspace, wave_length=None, wavelength_spread=None, sample_to_detector_distance=None, source_to_sample_distance=None, sample_aperture_size=None, sample_thickness=None, source_aperture_size=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_to_detector_distance (float, None) – sample to detector distance in meter

  • source_to_sample_distance (float, None) – source to sample distance in meter

  • sample_aperture_size (float, None) – sample aperture radius in unit mm

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

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

  • 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.meta_data.set_up_sample_detector_distance(workspace, sample_detector_distance, distance_unit, non_exist_default_name)[source]

Set detector to sample distance to meta data

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

  • sample_detector_distance (float, None) – sample to detector distance in meter

  • distance_unit (str) – unit for source sample distance

  • non_exist_default_name (str) – meta data name for sample detector distance if None of the default name exist

Returns:

item = (str, float, str) as log name, log value, log unit

Return type:

~list

drtsans.meta_data.set_up_source_sample_distance(workspace, source_sample_distance, distance_unit, non_exist_default_name)[source]

Set source to sample distance to meta data

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

  • source_sample_distance (float, None) – source to sample distance in meter

  • distance_unit (str) – unit for source sample distance

  • non_exist_default_name (str) – meta data name for sample detector distance if None of the default name exist

Returns:

item = (str, float, str) as log name, log value, log unit

Return type:

~list

drtsans.momentum_transfer module

drtsans.momentum_transfer.convert_to_q(ws, mode, resolution_function=None, **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} \]

Note the minus sign in \(Q_x\) in the azimuthal mode, so it increases to the right when looking at the detector.

devs - Andrei Savici <saviciat@ornl.gov>

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. If None, then we assume an infinite preccission in Q and the associated error is thus zero.

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

drtsans.path.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.path.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.path.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.path.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.path.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.pixel_calibration module

This module contains functions and classes to calculate and apply barscan and tube-widths calibrations.

drtsans.pixel_calibration.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.pixel_calibration.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.pixel_calibration.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.pixel_calibration.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.pixel_calibration.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.pixel_calibration.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.pixel_calibration.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.prepare_sensivities_correction module

class drtsans.prepare_sensivities_correction.PrepareSensitivityCorrection(instrument, component='detector1')[source]

Bases: object

Workflow (container) class to prepare sensitivities correction file

It tries to manage the various configuration and approaches for instrument scientists to prepare sensitivities file for EQSANS, GPSANS and BIOSANS.

property beam_center_radius: float
execute(use_moving_detector_method, min_threshold, max_threshold, output_nexus_name, enforce_use_nexus_idf=False, debug_mode=False)[source]

Main workflow method to calculate sensitivities correction

Parameters:
  • use_moving_detector_method (bool) – Flag to use ‘moving detectors’ method; Otherwise, use ‘detector patch’ method

  • min_threshold (float) – minimum threshold of normalized count for GOOD pixels

  • max_threshold (float) – maximum threshold of normalized count for GOOD pixels

  • output_nexus_name (str) – path to the output processed NeXus file

  • enforce_use_nexus_idf (bool) – flag to enforce to use IDF XML in NeXus file; otherwise, it may use IDF from Mantid library

  • debug_mode (bool) – flag for debugging mode

Return type:

None

set_beam_center_radius(radius)[source]

Set beam center radius

Parameters:

radius (float) – radius in mm

set_dark_current_runs(dark_current_runs)[source]

Set dark current runs

Parameters:

dark_current_runs (~list or ~tuple or int) – Dark current run(s)’s run number(s)

Return type:

None

set_direct_beam_runs(direct_beam_runs)[source]

Set direct beam runs

Parameters:

direct_beam_runs (~list or int or tuple)

set_flood_runs(flood_runs)[source]

Set flood run numbers

Parameters:

flood_runs (~list or int or tuple) – list of run number as integers

Return type:

None

set_masks(default_mask, pixels)[source]

Set masks

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

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

Return type:

None

set_pixel_calibration_flag(apply_calibration)[source]

Set the flag to apply pixel calibrations.

Parameters:

apply_calibration (bool, str) – Flag for applying the pixel calibration. No calibration (False), Default (True), Calibration file (str)

set_solid_angle_correction_flag(apply_correction)[source]

Set the flag to apply solid angle correction

Parameters:

apply_correction (bool) – Flag for applying

static sum_input_runs(flood_workspaces)[source]

Do NaN sum to all input flood workspaces

Parameters:

flood_workspaces

drtsans.prepare_sensivities_correction.debug_output(workspace, output_file)[source]

Exporting a workspace to NeXus file and HDF5 for debugging purpose

Parameters:
  • workspace (numpy.ndarray) – data to plot

  • output_file (str) – output file name as reference

Return type:

None

drtsans.process_uncertainties module

drtsans.process_uncertainties.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.redparms module

drtsans.redparms.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.redparms.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.redparms.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

drtsans.reductionlog module

drtsans.reductionlog.savereductionlog(filename='', detectordata=None, **kwargs)[source]

Save the reduction log

There are three NXentry. The first is for the 1d reduced data, second is for the 2d reduced data, and the third is for the extra information about how the data was processed.

The options read from the kwargs parameter are listed with the other parameters.

Parameters:
  • detectordata (dict) – for each key (name of detector), will have iq: Iqmod and iqxqy: IQazimuthal where Iqmod is a tuple with the following informations: intensity, error, mod_q, delta_mode_q and IQazimuthal is a tuple with the following informations: intensity, error, qx, delta_qx, qy, delta_y

  • python (string) – The script used to create everything (optional)

  • pythonfile (string) – The name of the file containing the python script. Will be read into python argument if not already supplied (optional)

  • reductionparams (str, dict) – The parameters supplied to the reduction script as either a nested dict or a json formatted str (optional)

  • logslicedata (dict) – data corresponding to the various slices

  • starttime (str) – When the original script was started (optional, default: now)

  • hostname (str) – Name of the computer used. If not provided, will be gotten from the system environment HOSTNAME (optional)

  • user (str) – User-id of who reduced the data (as in xcamms). If not provided will be gotten from the system environment USER (optional)

  • username (str) – Username of who reduced the data (as in actual name). If not provided will be gotten from the system environment USERNAME (optional)

  • specialparameters (dict) – dictionary of any other arguments you want to keep in the log file

  • samplelogs (SampleLogs) – SampleLogs object of all the EPICS infos logged into the NeXus (and visible on ONCat)

drtsans.resolution module

Smearing Pixels

There are three different sources for smearing pixel width (X) and height (Y), ranked by their priority:

  1. Reduction parameters smearingPixelSizeX and smearingPixelSizeY,

  2. Barscan and tube-width pixel calibrations, and

  3. Instrument definition file

A variety of scenarios giving rise to different final smearing pixel sizes are presented:

1. If no reduction parameters and no pixel calibration is supplied, then the instrument definition file provides a smearing width \(w_0\) and height \(h_0\) for all pixels.

2. If reduction parameters smearingPixelSizeX and smearingPixelSizeY are supplied, and no pixel calibration is supplied, then smearingPixelSizeX and smearingPixelSizeY become the smearing width and height for all pixels.

3. If no reduction parameters are supplied but pixel calibration is supplied, then the smearing width and height are taken from pixel calibration pixel sizes.

4. Finally, if reduction parameters smearingPixelSizeX and smearingPixelSizeY are supplied, and a pixel calibration is also supplied, the smearing width \(w_i\) of pixel \(i\) becomes

\[w_i = \frac{smearingPixelSizeX}{w_0} \cdot w_{pc, i},\]

where \(w_{pc, i}\) is the pixel width of pixel \(i\) provided by the pixel calibration. An analogous relation follows for the final smearing height.

digraph foo {
   A1 [label="drtsans.mono.biosans.api.load_all_files", shape=box, href="#drtsans.mono.biosans.api.load_all_files"]
   A2 [label="drtsans.mono.gpsans.api.load_all_files", shape=box, href="#drtsans.mono.gpsans.api.load_all_files"]
   A3 [label="drtsans.tof.eqsans.api.load_all_files", shape=box, href="#drtsans.tof.eqsans.api.load_all_files"]
   B1 [label="drtsans.mono.meta_data.set_meta_data", shape=box, href="#drtsans.mono.meta_data.set_meta_data"]
   B2 [label="drtsans.tof.eqsans.meta_data.set_meta_data", shape=box, href="#drtsans.tof.eqsans.meta_data.set_meta_data"]
   C [label="drtsans.geometry.logged_smearing_pixel_size", shape=box, href="#drtsans.geometry.logged_smearing_pixel_size"]
   D1 [label="drtsans.mono.momentum_transfer.retrieve_instrument_setup", shape=box, href="#drtsans.mono.momentum_transfer.retrieve_instrument_setup"]
   D2 [label="drtsans.tof.eqsans.momentum_transfer.retrieve_instrument_setup", shape=box, href="#drtsans.tof.eqsans.momentum_transfer.retrieve_instrument_setup"]
   E [label="drtsans.resolution.InstrumentSetUpParameters", shape=box, href="#drtsans.resolution.InstrumentSetupParameters"]
   F [label="drtsans.resolution.calculate_sigma_theta_geometry", shape=box, fontcolor=blue, href="#drtsans.resolution.calculate_sigma_theta_geometry"]
   A1 -> B1
   A2 -> B1
   A3 -> B2
   B1 -> C
   B2 -> C
   C -> D1 -> E
   C -> D2 -> E
   E -> F;
}

Above is a diagram of the functions involved in porting input reduction parameters smearingPixelSizeX and smearingPixelSizeY into the function calculating the undeterminacy in momentum transfer.

class drtsans.resolution.InstrumentSetupParameters(l1, sample_det_center_dist, source_aperture_radius, sample_aperture_radius, pixel_width_ratio=None, pixel_height_ratio=None)[source]

Bases: object

Data structure containing the parameters used to calculate Q resolution

property l1

Get L1 value :return: L1 (meter)

property sample_aperture_radius

Sample aperture radius, which is R2 in SANS master document :return: sample aperture radius (R2) in meter

property sample_det_center_distance

Distance from sample to detector bank center, which is L2 in the SANS master document :return: sample detector center distance, aka SANS L2 (meter)

property source_aperture_radius

Source aperture radius, which is R1 in SANS master document :return: source aperture radius (R1) in meter

drtsans.resolution.calculate_sigma_geometry(mode, wavelength, delta_wavelength, pixel_info, instrument_parameters)[source]

Calculates the Q independent part of the resolution, the common parts in formula 10.3 - 10.6

Parameters:
  • mode (str) – One of “scalar”, “azimuthal”, “crystalographic”

  • wavelength (array) – the array of wavelengths (same shape as momentum transfer)

  • delta_wavelength (array) – the array of wavelength widths (same shape as momentum transfer)

  • pixel_info (namedtuple) – A namedtuple with fields for two_theta, azimuthal, l2, keep

  • instrument_parameters (InstrumentSetupParameters) – Data structure containing the parameters used to calculate Q resolution. In particular: 1. distance from source aperture to sample, 2. distance from sample to detector, 3. source aperture radius, 4. sample aperture radius, 5. custom pixel width and height to replace nominal pixel width and height, only for Q-resolution calculation.

Return type:

array

drtsans.resolution.calculate_sigma_theta_geometry(mode, pixel_info, instrument_parameters)[source]

Calculates the effect of the geometry and wavelength uncertainty on the uncertainty in the value of Q.

\[\left(\frac {L_2}{L_1}\right)^2\frac{R_1^2}{4}+\left(\frac {L_1+L_2}{L_1}\right)^2\frac{R_2^2}{4}+ \frac {1}{12}(\Delta R)^2\]

If mode is “scalar”, \(((\Delta R)^2=(\Delta x)^2+(\Delta y)^2)/2\), else

\((\Delta R)^2=[(\Delta x)^2,(\Delta y)^2]\). The formula for scalar is consistent with the equations 10.3 and 10.4 in the master document. when you add the two together, the geometry part is twice the contribution of \((\Delta R)^2\) plus the gravity part.

Parameters:
  • mode (str) – One of “scalar”, “azimuthal”, “crystalographic”

  • pixel_info (namedtuple) – A namedtuple with fields for two_theta, azimuthal, l2, keep, smearing_pixel_size_x, smearing_pixel_size_y

  • instrument_parameters (InstrumentSetupParameters) – Data structure containing the parameters used to calculate Q resolution. In particular: 1. distance from source aperture to sample, 2. distance from sample to detector, 3. source aperture radius, 4. sample aperture radius, 5. custom pixel width and height to replace nominal pixel width and height, only for Q-resolution calculation.

Returns:

The coefficient described above

Return type:

float or list

drtsans.resolution.calculate_sigma_theta_gravity(wavelength, delta_wavelength, instrument_parameters)[source]

Calculates

\[\frac 23 B^2\lambda^2(\Delta\lambda)^2\]

where \(B=g m_N^2L_2(L_1+L_2)/(2h^2)\)

Parameters:
  • wavelength (array) – the array of wavelengths

  • delta_wavelength (array) – the array of wavelength spreads

  • instrument_parameters (InstrumentSetupParameters) – Data structure containing the parameters used to calculate Q resolution. In particular: 1. distance from source aperture to sample, 2. distance from sample to detector, 3. source aperture radius, 4. sample aperture radius, 5. custom pixel width and height to replace nominal pixel width and height, only for Q-resolution calculation.

Returns:

The formula above

Return type:

array

drtsans.resolution.calculate_sigma_theta_prefactor(wavelength, pixel_info, instrument_parameters)[source]

Calculates for every pixel and wavelength

\[\left(\frac{2\pi\cos\theta\cos^2(2\theta)}{\lambda L_2}\right)^2\]
Parameters:
  • wavelength (array) – the array of wavelengths (same shape as momentum transfer)

  • pixel_info (namedtuple) – A namedtuple with fields for two_theta, azimuthal, l2, keep

  • instrument_parameters (InstrumentSetupParameters) – Data structure containing the parameters used to calculate Q resolution. In particular: 1. distance from source aperture to sample, 2. distance from sample to detector, 3. source aperture radius, 4. sample aperture radius, 5. custom pixel width and height to replace nominal pixel width and height, only for Q-resolution calculation.

Returns:

The coefficient described above

Return type:

float

drtsans.samplelogs module

class drtsans.samplelogs.SampleLogs(source)[source]

Bases: object

Log reader, a bit more pythonic

source: PyObject

Instrument object, MatrixWorkspace, workspace name, file name, run number

find_log_with_units(log_key, unit=None)[source]

Find a log entry in the logs, and ensure it has the right units

Parameters:
  • log_key (string) – key of the log to find

  • unit (None or string) – units string to enforce

Return type:

log value

find_run(other)[source]

Retrieve the Run object

Parameters:

other (Run, str, MatrixWorkspace)

Returns:

Reference to the run object

Return type:

Run

insert(name: str, value: str | int | float | list | BoolTimeSeriesProperty | FloatTimeSeriesProperty | Int64TimeSeriesProperty | StringTimeSeriesProperty, unit: str | None = None)[source]

Wrapper to Mantid AddSampleLog algorithm

The following properties of AddSampleLog are determined by inspection of value: LogText, LogType, NumberType

Parameters:
  • name – log entry name. If value is one of Mantid’s time series property objects, it is expected that this is the name of the series.

  • value – Value to insert. If value is a list object, it will insert only the first value of the list.

  • unit (str) – Log unit. If value is one of Mantid’s time series property objects, it is expected that this is the unit of the series.

insert_time_series(name, elapsed_times, values, start_time='2000-01-01T00:00:00', unit='')[source]

Insert a ~mantid.kernel.FloatTimeSeriesProperty in the logs

Parameters:
  • name (str) – log entry name

  • elapsed_times (list) – List of elapsed times after `start_time`, in seconds.

  • values (list) – List of log values, same length as the list of times

  • start_time (str) – Starting time for the run

  • unit (str) – units of the log values

property mantid_logs
single_value(log_key, operation=<function mean>)[source]
property workspace
drtsans.samplelogs.periodic_index_log(period: float, interval: float, duration: float, run_start: str | DateAndTime, offset: float = 0.0, step: float = 1.0, name: str = 'periodic_index') FloatTimeSeriesProperty[source]

Generate a periodic log whose values are integers ranging from 0 to period / interval.

The first log entry is at run_start + offset with value 0. The next entry at run_start + offset + interval with value 1, and so on. The log wraps around at run_start + offset + period so the next value is again 0.

Parameters:
  • period – Period of the log, in seconds

  • interval – Interval between consecutive log entries, in seconds

  • duration – Duration of the log from run_start, in seconds

  • run_start – Time of the first log entry, unless offset is also specified

  • offset – Time of the first log entry after run_start, in seconds

  • step – Absolute value of the change in the log value between two consecutive entries

  • name – Name of the log

Return type:

A Mantid timeseries property object which can be attached to a Run object.

Raises:

ValueError – If period is not a multiple of interval.

drtsans.samplelogs.time_series(name: str, elapsed_times: ndarray | List[DateAndTime], values: List[bool | float | int | str], start_time: DateAndTime | str = '2000-01-01T00:00:00', unit: str = '') BoolTimeSeriesProperty | FloatTimeSeriesProperty | Int64TimeSeriesProperty | StringTimeSeriesProperty[source]

Create time series log

Parameters:
  • name – log entry name

  • elapsed_times – List of elapsed times after `start_time`, in seconds.

  • start_time – Starting time for the run

  • values – List of log values, same length as the list of times

  • unit – Log unit

Return type:

mantid log that can be added as a property to a Run object

Raises:

ValueError – If items in sequence `values` is not one of bool, ``float, int, str

drtsans.save_2d module

drtsans.save_2d.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.save_2d.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.save_ascii module

drtsans.save_ascii.load_ascii_binned_2D(filename)[source]

Load the format produced by save_ascii_binned_2D

Parameters:

filename (str) – Input filename

Return type:

drtsans.dataobjects.IQazimuthal

drtsans.save_ascii.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.save_ascii.save_ascii_2D(q2, q2x, q2y, title, filename)[source]

Save the I(qx,qy) workspace in Ascii format

Parameters:
  • q2 (Workspace2D) – Workspace containing the 2D I(qx,qy)

  • q2x (Workspace2D) – Workspace containing the 2D dqx(qx,qy)

  • q2y (Workspace2D) – Workspace containing the 2D dqy(qx,qy)

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

  • filename (string) – The output filename

drtsans.save_ascii.save_ascii_binned_1D(filename: str, title, *args, **kwargs)[source]

Save I(q) data in Ascii format

Parameters:
  • filename – absolute path to output filename for the 1D I(Q) profile

  • title (str) – title to be added on the first line

  • args (drtsans.dataobjects.IQmod) – output from 1D binning

  • kwargs – intensity, error, mod_q, delta_mod_q - 1D numpy arrays of the same length, output from 1D binning

drtsans.save_ascii.save_ascii_binned_2D(filename: str, title, *args, **kwargs)[source]

Save I(qx, qy) data in Ascii format

Parameters:
  • filename – absolute path for output 2D profile file

  • title (str) – title to be added on the first line

  • args (IQazimuthal) – output from 2D binning

  • kwargs – intensity, error, qx, qy, delta_qx, delta_qy - 1D numpy arrays of the same length, output from 1D binning

drtsans.save_ascii.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.script_utility module

drtsans.script_utility.create_output_directory(output_dir='', subfolder=None, hfir_sans=True)[source]

Create output folder if not there already. If subfolder is provided with a list of string, those subfolders will be created inside the output_dir. If hfir_sans is set to True (default value) 2 subfolders 1D and 2D will be automatically created

Parameters:
  • output_dir – str name of the output folder

  • subfolder – list list of subfolders to create inside that output folder

  • hfir_sans – boolean if True, subfolders 1D and 2D will be created automatically

Raise:

ValueError if not output_dir has been provided

drtsans.script_utility.run_reduction(reduction_input, q_type='', sample_name='', instrument=InstrumentEnumName.GPSANS)[source]

Run a full reduction for GP or BIO sans instruments

Parameters:
  • reduction_input – dictionary dictionary of all the paremeters used to run reduction

  • q_type – str (ex: “low”, “mid”, “high” Use to create uniq output file name

  • sample_name – str name of the sample used. This is used to create a uniq output filename

  • instrument – InstrumentEnumName name of the instrument as InstrumentEnumName. Default being GPSANS

Returns:

tuple, (out object, name of file created)

drtsans.sensitivity module

drtsans.sensitivity.apply_sensitivity_correction(input_workspace, sensitivity_filename=None, sensitivity_workspace=None, min_threshold=None, max_threshold=None, output_workspace=None)[source]

Apply a previously calculated sensitivity correction

Mantid algorithms used: CloneWorkspace, DeleteWorkspace, Divide, LoadNexusProcessed, MaskDetectors MaskDetectorsIf

Parameters:
  • input_workspace (str, MatrixWorkspace) – workspace to apply the correction to

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

  • min_threshold (float or None) – if not None, the data will be masked if the sensitivity is below this threshold

  • max_threshold (float or None) – if not None, the data will be masked if the sensitivity is above this threshold

  • output_workspace (MatrixWorkspace) – corrected workspace. This is the input workspace by default

drtsans.sensitivity.load_sensitivity_workspace(sensitivity_filename, output_workspace)[source]

Loads sensitivity workspace. Useful to avoid multiple loads from disk.

Mantid algorithms used: LoadNexusProcessed,

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

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

drtsans.sensitivity_correction_moving_detectors module

Module for algorithms to prepare sensitivity for instrument with moving detector

drtsans.sensitivity_correction_moving_detectors.calculate_sensitivity_correction(flood_run_ws_list, threshold_min, threshold_max)[source]

Prepare sensitivities with

Parameters:
  • flood_run_ws_list (~list) – List of references to Mantid workspaces for normalized and masked (default and beam center)

  • threshold_min (float) – minimum threshold

  • threshold_max (float) – maximum threshold

Returns:

Reference to the events workspace

Return type:

MatrixWorkspace

drtsans.sensitivity_correction_moving_detectors.mask_beam_center(data_ws, beam_center_ws, beam_center_radius)[source]

Mask detectors in a workspace

Mask (1) beam center

Parameters:
  • data_ws (MatrixWorkspace) – Flood data workspace

  • beam_center_ws (MatrixWorkspace) – Beam center workspace used to generate beam center mask

  • beam_center_radius (float) – beam center radius in unit of mm

Return type:

MatrixWorkspace

drtsans.sensitivity_correction_moving_detectors.prepare_sensitivity(flood_data_matrix, flood_sigma_matrix, threshold_min, threshold_max)[source]

Prepare sensitivity for moving detector

Data files are processed such that intensities and errors are stored in numpy.ndarray with shape (N, M), where - N: number of data files to calculate sensitivities - M: number of pixels (aka spectra) in instrument’s detector; The 2D data from 2D detector are flattened to 1D

Prerequisite of the input data: - Input data has been normalized by monitor counts already - top and bottom of the detector shall be masked (set to value as NaN) due to edge effects - in each file, beam center shall be found and masked out - errors are then calculated from the flood intensities

Workflow to prepare sensitivities - normalize the flood field data by monitor - find weighted average for each fie and error - apply bad pixel threshold to each file - correct for beam stop and add all the flood files together to non-normalized sensitivities - apply weighted average to sensitivities

Parameters:
  • flood_data_matrix (ndaray) – multiple set of flood data intensities with shape = N, M

  • flood_sigma_matrix (ndaray) – multiple set of flood data intensities’ error with shape = N, M

  • threshold_min (float) – minimum allowed detector counts to mask out ‘bad’ pixels

  • threshold_max (float) – maximum allowed detector counts to mask out ‘bad’ pixels

Returns:

sensitivities, sensitivities error

Return type:

ndaray, ndaray

drtsans.sensitivity_correction_patch module

drtsans.sensitivity_correction_patch.calculate_sensitivity_correction(input_workspace, min_threshold=0.5, max_threshold=2.0, poly_order=2, min_detectors_per_tube=50, filename=None, component_name='detector1', output_workspace=None)[source]

Calculate the detector sensitivity

Prerequisites for input workspace: 1. All previously masked values to NaN as required by Numpy functions but not masked pixels for beam centers 2. All masked pixels at beam centers are set to -infinity

Mantid algorithms used: SaveNexusProcessed CreateWorkspace

Parameters:
  • input_workspace (str, MatrixWorkspace) – Workspace to calculate the sensitivity from

  • min_threshold (float) – Minimum threshold for efficiency value.

  • max_threshold (float) – Maximum threshold for efficiency value

  • poly_order (int) – ploy order. default to 2

  • min_detectors_per_tube (int, optional) – Minimum detectors with a value existing in the tube to fit. Only fits tubes with at least min_detectors_per_tube (the default is 50).

  • component_name (str, optional) – Component name to (the default is ‘detector1’, which is the main detector)

  • filename (str) – Name of the file to save the sensitivity calculation to

  • output_workspace (MatrixWorkspace) – The calculated sensitivity workspace

drtsans.settings module

class drtsans.settings.MultiOrderedDict[source]

Bases: OrderedDict

drtsans.settings.namedtuplefy(func)[source]

Decorator to transform the return dictionary of a function into a namedtuple

Parameters:
  • func (Function) – Function to be decorated

  • name (str) – Class name for the namedtuple. If None, the name of the function will be used

Return type:

Function

drtsans.settings.unpack_v3d(functor, index)[source]

Retain only the cartesian coordinates of the V3D object returned by `functor`

This function reduces the memory imprint, from a V3D object to a mere 3-component list. Speeds up execution by avoiding crowding the heap when interating over the detectors. e.g. x = [detectorInfo().position(i) for i in range(number_detectors)] # number_detectors V3D objects in the heap x = [unpackV3D(detectorInfo.position, i) for i in range(number_detectors)] # 100 times faster

Parameters:
  • functor (function) – Callable receiving argument `index` and returning a V3D object.

  • index (int) – DetectorInfo, ComponentInfo, or SpectrumInfo index

Return type:

list

drtsans.solid_angle module

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

Calculate the solid angle from the input_workspace.

Mantid algorithms used: SolidAngle

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

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

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

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

Return type:

IEventWorkspace, MatrixWorkspace

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

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

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

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

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

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

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

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

Return type:

IEventWorkspace, MatrixWorkspace

drtsans.stitch module

drtsans.stitch.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.thickness_normalization module

drtsans.thickness_normalization.normalize_by_thickness(input_workspace, thickness)[source]

Normalize input workspace by thickness

Parameters:
Return type:

MatrixWorkspace

drtsans.transmission module

drtsans.transmission.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.transmission.calculate_transmission(input_sample, input_reference, radius, radius_unit='mm', output_workspace=None)[source]

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

For EQ-SANS, one additional step fitting the returned raw values is necessary. Use eqsans.calculate_transmission instead.

Mantid algorithms used: Divide GroupDetectors RebinToWorkspace

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

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

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

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

  • output_workspace (str) – Name of the output workspace containing the raw transmission values. If None, a hidden random name will be provided.

Returns:

Workspace containing the raw transmission values

Return type:

MatrixWorkspace

drtsans.tubecollection module

class drtsans.tubecollection.ElementComponentInfo(component_info, component_info_index)[source]

Bases: object

property children
class drtsans.tubecollection.PixelSpectrum(input_workspace, component_info_index=None, workspace_index=None)[source]

Bases: ElementComponentInfo, SpectrumInfo

property area

Product of pixel width and height

property detector_id
property height

Extent of the pixel detector along the Z-axis

property intensity

Summed intensity for the spectrum associated to this pixel

property position

Cartesian coordinates of the pixel detector. Overrides componentInfo().position

Coordinates typically correspond to the center of a cuboid detector, or the center for the base of a cylindrical pixel.

property width

Extent of the pixel detector along the Y-axis

class drtsans.tubecollection.SpectrumInfo(input_workspace, workspace_index)[source]

Bases: object

property readE
property readX
property readY
class drtsans.tubecollection.TubeCollection(input_workspace, component_name)[source]

Bases: ElementComponentInfo

static map_detector_to_spectrum(input_workspace)[source]

A mapping from detector info index (or component info index) to spectrum index (or workspace index)

Parameters:

input_workspace (str, MatrixWorkspace, IEventWorkspace)

Return type:

dict

sorted(key=None, reverse=False, view='decreasing X')[source]

Sort the list of ~drtsans.tubecollection.TubeInfo objects in the prescribed order.

Parameters:
  • key (function) – Function of one argument to extract a comparison key from each element in self.tubes. If None, then the selected view determines the order

  • reverse (bool) – Reverse the order resulting from application of key or view

  • view (str) – Built-in permutations of the tubes prescribing a particular order. Valid views are: - ‘fbfb’: order the tubes alternating front tube and back tube. It is assumed that all front tubes are first listed in the instrument definition file for the double panel, followed by the back tubes. It is also assumed the number of front and back tubes is the same. - ‘decreasing X’: order the tubes by decreasing X-coordinate. This view can “flatten” a double detector panel when viewed from the sample “from left to right”. - ‘workspace index’: order the tubes by increasing workspace index for the first pixel of each tube.

property sorted_views

Dictionary mapping a particular sorting of the tubes to the permutation of their component info indexes required to attain the desired sorting.

property tubes

List of ~drtsans.tubecollection.TubeSpectrum objects ordered using their component info indexes, from smallest to highest index.

class drtsans.tubecollection.TubeSpectrum(input_workspace, component_info_index, workspace_indexes)[source]

Bases: ElementComponentInfo, SpectrumInfo

property detector_ids
property detector_info_index

Array of detector info indexes for the pixels contained in the tube.

property isMasked

Mask flag for each pixel in the tube

static is_valid_tube(component_info, component_index)[source]

Determine if all the immediate children-components are detectors, as in the case of a tube.

Warning

This function does not invalidate other components than tubes whose immediate children-components are all detectors.

Parameters:
Return type:

bool

property pixel_heights

Convenience property to get/set the pixel heights

property pixel_intensities

Array of pixel_intensities for every pixel

property pixel_positions
property pixel_scale_factors

Convenience property to get the size scale factors for each pixel

property pixel_widths

Convenience property to get/set the pixel widths

property pixel_y

Convenience property to get/set the pixel Y-coordinate

property pixel_y_boundaries

Coordinates along the Y-axis of the pixel boundaries

property pixels

List of ~drtsans.tubecollection.PixelSpectrum objects making up the tube.

Return type:

list

property width

Tube width, taken as width of the first pixel

property x_boundaries

Coordinates along the X-axis of the tube boundaries.

drtsans.tubecollection.unpack_v3d(function, *args)[source]

if the return value of `function(args)` is a V3D object, then cast to numpy.ndarray and return, otherwise return `function(*args)`

Parameters:
  • function (function) – Callable receiving argument `index` and returning a V3D object.

  • args (list) – Arguments to be passed to function.

drtsans.wavelength module

Disk choppers allow neutrons through with only certain wavelengths. These permitted wavelengths are grouped into one or more wavelength bands. This module provides objects to represent one or a set of wavelength bands. In addition, the module contains helper functions for conversion between wavelength and time-of-flight, taking into account the distance traveled by the neutron and its delayed emission time from the moderator.

class drtsans.wavelength.Wband(w_min, w_max)[source]

Bases: object

A wavelength band, useful for defining one of the possible bands transmitted by a disk chopper.

Parameters:
  • w_min (float) – Lower boundary wavelength.

  • w_max (float) – Upper boundary wavelength.

Raises:

ValueError – Negative input values or lower boundary is bigger than the upper one.

property max

Upper wavelength boundary.

property min

Lower wavelength boundary.

property width

Difference between the upper and lower wavelength boundaries.

class drtsans.wavelength.Wbands(*args)[source]

Bases: object

A list of non overlapping wavelength bands. Useful for defining a set of bands transmitted by one or a set of disk choppers.

Parameters:
drtsans.wavelength.from_tof(tof, distance, pulse_width=0.0)[source]

Convert time of flight of arriving neutron to wavelength.

Parameters:
  • tof (float) – time of flight of the traveling neutron, in Angstroms.

  • distance (float) – Distance traveled by the neutron, in meters.

  • pulse_width (float) – Neutrons emitted from the moderator with a certain wavelength \(\lambda\) have a distribution of delayed emission times that depends on the wavelength, with \(FWHM(\lambda) \simeq pulsewidth \cdot \lambda\). Units are microseconds/Angstroms.

Returns:

wavelength (in Angstroms)

Return type:

float

drtsans.wavelength.tof(wavelength, distance, pulse_width=0.0)[source]

Convert neutron wavelength to time of flight

Parameters:
  • wavelength (float) – wavelength of the travelling neutron, in microseconds

  • distance (float) – Distance travelled by the neutron, in meters

  • pulse_width (float) – Neutrons emitted from the moderator with a certain wavelength \(\lambda\) have a distribution of delayed emission times with \(FWHM(\lambda) \simeq pulsewidth \cdot \lambda\). Units are microseconds/Angstroms.

Returns:

time of flight (in micro seconds)

Return type:

float

Module contents

class drtsans.InstrumentEnumName(value)[source]

Bases: Enum

An enumeration.

BIOSANS = <mantid.kernel._kernel.InstrumentInfo object>
EQSANS = <mantid.kernel._kernel.InstrumentInfo object>
GPSANS = <mantid.kernel._kernel.InstrumentInfo object>
UNDEFINED = None
static names()[source]

Standard names for all instruments, in alphabetical order

class drtsans.InstrumentSetupParameters(l1, sample_det_center_dist, source_aperture_radius, sample_aperture_radius, pixel_width_ratio=None, pixel_height_ratio=None)[source]

Bases: object

Data structure containing the parameters used to calculate Q resolution

property l1

Get L1 value :return: L1 (meter)

property sample_aperture_radius

Sample aperture radius, which is R2 in SANS master document :return: sample aperture radius (R2) in meter

property sample_det_center_distance

Distance from sample to detector bank center, which is L2 in the SANS master document :return: sample detector center distance, aka SANS L2 (meter)

property source_aperture_radius

Source aperture radius, which is R1 in SANS master document :return: source aperture radius (R1) in meter

drtsans.apply_sensitivity_correction(input_workspace, sensitivity_filename=None, sensitivity_workspace=None, min_threshold=None, max_threshold=None, output_workspace=None)[source]

Apply a previously calculated sensitivity correction

Mantid algorithms used: CloneWorkspace, DeleteWorkspace, Divide, LoadNexusProcessed, MaskDetectors MaskDetectorsIf

Parameters:
  • input_workspace (str, MatrixWorkspace) – workspace to apply the correction to

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

  • min_threshold (float or None) – if not None, the data will be masked if the sensitivity is below this threshold

  • max_threshold (float or None) – if not None, the data will be masked if the sensitivity is above this threshold

  • output_workspace (MatrixWorkspace) – corrected workspace. This is the input workspace by default

drtsans.calculate_sigma_geometry(mode, wavelength, delta_wavelength, pixel_info, instrument_parameters)[source]

Calculates the Q independent part of the resolution, the common parts in formula 10.3 - 10.6

Parameters:
  • mode (str) – One of “scalar”, “azimuthal”, “crystalographic”

  • wavelength (array) – the array of wavelengths (same shape as momentum transfer)

  • delta_wavelength (array) – the array of wavelength widths (same shape as momentum transfer)

  • pixel_info (namedtuple) – A namedtuple with fields for two_theta, azimuthal, l2, keep

  • instrument_parameters (InstrumentSetupParameters) – Data structure containing the parameters used to calculate Q resolution. In particular: 1. distance from source aperture to sample, 2. distance from sample to detector, 3. source aperture radius, 4. sample aperture radius, 5. custom pixel width and height to replace nominal pixel width and height, only for Q-resolution calculation.

Return type:

array

drtsans.calculate_sigma_theta_geometry(mode, pixel_info, instrument_parameters)[source]

Calculates the effect of the geometry and wavelength uncertainty on the uncertainty in the value of Q.

\[\left(\frac {L_2}{L_1}\right)^2\frac{R_1^2}{4}+\left(\frac {L_1+L_2}{L_1}\right)^2\frac{R_2^2}{4}+ \frac {1}{12}(\Delta R)^2\]

If mode is “scalar”, \(((\Delta R)^2=(\Delta x)^2+(\Delta y)^2)/2\), else

\((\Delta R)^2=[(\Delta x)^2,(\Delta y)^2]\). The formula for scalar is consistent with the equations 10.3 and 10.4 in the master document. when you add the two together, the geometry part is twice the contribution of \((\Delta R)^2\) plus the gravity part.

Parameters:
  • mode (str) – One of “scalar”, “azimuthal”, “crystalographic”

  • pixel_info (namedtuple) – A namedtuple with fields for two_theta, azimuthal, l2, keep, smearing_pixel_size_x, smearing_pixel_size_y

  • instrument_parameters (InstrumentSetupParameters) – Data structure containing the parameters used to calculate Q resolution. In particular: 1. distance from source aperture to sample, 2. distance from sample to detector, 3. source aperture radius, 4. sample aperture radius, 5. custom pixel width and height to replace nominal pixel width and height, only for Q-resolution calculation.

Returns:

The coefficient described above

Return type:

float or list

drtsans.calculate_sigma_theta_gravity(wavelength, delta_wavelength, instrument_parameters)[source]

Calculates

\[\frac 23 B^2\lambda^2(\Delta\lambda)^2\]

where \(B=g m_N^2L_2(L_1+L_2)/(2h^2)\)

Parameters:
  • wavelength (array) – the array of wavelengths

  • delta_wavelength (array) – the array of wavelength spreads

  • instrument_parameters (InstrumentSetupParameters) – Data structure containing the parameters used to calculate Q resolution. In particular: 1. distance from source aperture to sample, 2. distance from sample to detector, 3. source aperture radius, 4. sample aperture radius, 5. custom pixel width and height to replace nominal pixel width and height, only for Q-resolution calculation.

Returns:

The formula above

Return type:

array

drtsans.calculate_sigma_theta_prefactor(wavelength, pixel_info, instrument_parameters)[source]

Calculates for every pixel and wavelength

\[\left(\frac{2\pi\cos\theta\cos^2(2\theta)}{\lambda L_2}\right)^2\]
Parameters:
  • wavelength (array) – the array of wavelengths (same shape as momentum transfer)

  • pixel_info (namedtuple) – A namedtuple with fields for two_theta, azimuthal, l2, keep

  • instrument_parameters (InstrumentSetupParameters) – Data structure containing the parameters used to calculate Q resolution. In particular: 1. distance from source aperture to sample, 2. distance from sample to detector, 3. source aperture radius, 4. sample aperture radius, 5. custom pixel width and height to replace nominal pixel width and height, only for Q-resolution calculation.

Returns:

The coefficient described above

Return type:

float

drtsans.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.convert_to_q(ws, mode, resolution_function=None, **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} \]

Note the minus sign in \(Q_x\) in the azimuthal mode, so it increases to the right when looking at the detector.

devs - Andrei Savici <saviciat@ornl.gov>

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. If None, then we assume an infinite preccission in Q and the associated error is thus zero.

  • 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.fbc_options_json(reduction_input)[source]
drtsans.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.getWedgeSelection(data2d, q_min, q_delta, q_max, azimuthal_delta, peak_width=0.25, background_width=1.5, signal_to_noise_min=2.0, peak_search_window_size_factor=0.6, debug_dir='/tmp/') List[List[Tuple[float, float]]][source]

Calculate azimuthal binning ranges automatically based on finding peaks in the annular ring. The output of this is intended to be used in select_i_of_q_by_wedge().

Parameters:
  • data2d (Azimuthal)

  • q_min (float) – The left bin boundary for the first Q-bin

  • q_delta (float) – The size of the bins in Q

  • q_max (float) – The left bin boundary for the last Q-bin

  • azimuthal_delta (float) – The size of the bins in azimuthal angle

  • peak_width (float) – Percent of full-width-half-max (FWHM) of the peak to define the signal to be within when determining the final range for azimuthal binning.

  • background_width (float) – Percent of full-width-half-max (FWHM) of the peak to define the background between peaks to be within when determining the final range for azimuthal binning.

  • signal_to_noise_min (float) – Minimum signal to noise ratio for the data to be considered “fittable”

  • peak_search_window_size_factor (float) – Factor of 360 / (num peaks) to construct the search range for wedge peak

  • debug_dir (str) – Full path of the output directory for debugging output files

  • Results

  • =======

  • ~list – list containing 2 lists each contains 2 2-tuples as [[(peak1_min, peak1_max), (peak2_min, peak2_max)], [(..., ...), (..., ...)]]

drtsans.half_polarization(flipper_off_workspace, flipper_on_workspace, polarization, efficiency, spin_up_workspace=None, spin_down_workspace=None)[source]

Calculate the spin up/down workspaces from flipper on/off.

Mantid algorithms used: RenameWorkspace

Parameters:
  • flipper_off_workspace (str, MatrixWorkspace) – Flipper off measurement

  • flipper_on_workspace (str, MatrixWorkspace) – Flipper on measurement

  • polarization (str, MatrixWorkspace) – Polarization state

  • efficiency (str, MatrixWorkspace) – Flipper efficiency

  • spin_up_workspace (str) – Name of the resulting spin up workspace. If None, then flipper_off_workspace will be overwritten.

  • spin_down_workspace (str) – Name of the resulting spin down workspace. If None, then flipper_on_workspace will be overwritten.

Return type:

py:obj:tuple of 2 ~mantid.api.MatrixWorkspace

drtsans.instrument_enum_name(input_query)[source]

Resolve the instrument name as a unique enumeration.

Parameters:

input_query (str, MatrixWorkspace, IEventsWorkspace) – string representing a filepath, a valid instrument name, or a Mantid workspace containing an instrument

Returns:

The name of the instrument as one of the InstrumentName enumerations

Return type:

InstrumentEnumName

drtsans.instrument_standard_name(input_query)[source]

Resolve the standard instrument name.

Parameters:

input_query (str, MatrixWorkspace, IEventsWorkspace) – string representing a filepath, a valid instrument name, or a Mantid workspace containing an instrument

Returns:

The name of the instrument as the string representation of one of the InstrumentName enumerations

Return type:

str

drtsans.is_time_of_flight(input_query)[source]

Find if the instrument is a time-of-flight one

Parameters:

input_query (str, MatrixWorkspace, IEventsWorkspace, InstrumentEnumName) – string representing a valid instrument name, or a Mantid workspace containing an instrument

Return type:

bool

drtsans.load_sensitivity_workspace(sensitivity_filename, output_workspace)[source]

Loads sensitivity workspace. Useful to avoid multiple loads from disk.

Mantid algorithms used: LoadNexusProcessed,

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

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

drtsans.normalize_by_thickness(input_workspace, thickness)[source]

Normalize input workspace by thickness

Parameters:
Return type:

MatrixWorkspace

drtsans.savereductionlog(filename='', detectordata=None, **kwargs)[source]

Save the reduction log

There are three NXentry. The first is for the 1d reduced data, second is for the 2d reduced data, and the third is for the extra information about how the data was processed.

The options read from the kwargs parameter are listed with the other parameters.

Parameters:
  • detectordata (dict) – for each key (name of detector), will have iq: Iqmod and iqxqy: IQazimuthal where Iqmod is a tuple with the following informations: intensity, error, mod_q, delta_mode_q and IQazimuthal is a tuple with the following informations: intensity, error, qx, delta_qx, qy, delta_y

  • python (string) – The script used to create everything (optional)

  • pythonfile (string) – The name of the file containing the python script. Will be read into python argument if not already supplied (optional)

  • reductionparams (str, dict) – The parameters supplied to the reduction script as either a nested dict or a json formatted str (optional)

  • logslicedata (dict) – data corresponding to the various slices

  • starttime (str) – When the original script was started (optional, default: now)

  • hostname (str) – Name of the computer used. If not provided, will be gotten from the system environment HOSTNAME (optional)

  • user (str) – User-id of who reduced the data (as in xcamms). If not provided will be gotten from the system environment USER (optional)

  • username (str) – Username of who reduced the data (as in actual name). If not provided will be gotten from the system environment USERNAME (optional)

  • specialparameters (dict) – dictionary of any other arguments you want to keep in the log file

  • samplelogs (SampleLogs) – SampleLogs object of all the EPICS infos logged into the NeXus (and visible on ONCat)

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

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

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

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

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

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

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

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

Return type:

IEventWorkspace, MatrixWorkspace

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