drtsans.mono.gpsans package¶
Submodules¶
drtsans.mono.gpsans.api module¶
GPSANS API
- drtsans.mono.gpsans.api.adjust_back_panels_to_effective_position(workspace)[source]¶
As the back panels are shadowed by its neighboring front panels when the incident beam is hitting at an angle, the effective position of the back panels needs to be adjusted to the center of the gap between its two neighboring front panels.
- Parameters:
workspace – intput workspace
@NOTE: this adjustment must be done right before convert to q space
- drtsans.mono.gpsans.api.load_all_files(reduction_input, prefix='', load_params=None, path: str | List[str] = None, use_nexus_idf: bool = False, debug_output: bool = False, back_panel_correction: bool = False)[source]¶
load all required files at the beginning, and transform them to histograms
- Parameters:
reduction_input
prefix
load_params
path – Absolute path to one or more directories where to search for the NeXus files
use_nexus_idf (bool) – Flag to use IDF inside NeXus file. True for SPICE data
debug_output (bool) – Flag to save out internal result
back_panel_correction (bool) – Move the z direction of back panel to remove artifacts in azimuthal plots
- drtsans.mono.gpsans.api.plot_reduction_output(reduction_output, reduction_input, loglog=True, imshow_kwargs=None, close_figures=False)[source]¶
- drtsans.mono.gpsans.api.prepare_data(data, pixel_calibration=False, mask_detector=None, detector_offset=0, sample_offset=0, center_x=None, center_y=None, dark_current=None, flux_method=None, monitor_fail_switch=False, mask=None, mask_panel=None, btp={}, solid_angle=True, sensitivity_file_path=None, sensitivity_workspace=None, wave_length=None, wavelength_spread=None, sample_aperture_diameter=None, sample_thickness=None, source_aperture_diameter=None, smearing_pixel_size_x=None, smearing_pixel_size_y=None, output_workspace=None, output_suffix='', **kwargs)[source]¶
Load a GPSANS data file and bring the data to a point where it can be used. This includes applying basic corrections that are always applied regardless of whether the data is background or scattering data.
- Parameters:
data (int, str, IEventWorkspace) – Run number as int or str, file path,
IEventWorkspace
pixel_calibration (bool, str) – Adjust pixel heights and widths according to barscan and tube-width calibrations. Options are (1) No calibration (False), (2) default calibration file (True) (3) user specified calibration file (str)
mask_detector (str) – Name of an instrument component to mask
detector_offset (float) – Additional translation of the detector along Z-axis, in millimeters.
sample_offset (float) – Additional translation of the sample along the Z-axis, in millimeters.
center_x (float) – Move the center of the detector to this X-coordinate. If
None
, the detector will be moved such that the X-coordinate of the intersection point between the neutron beam and the detector array will havex=0
.center_y (float) – Move the center of the detector to this Y-coordinate. If
None
, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will havey=0
.dark_current (int, str, IEventWorkspace) – Run number as int or str, file path,
IEventWorkspace
flux_method (str) – Method for flux normalization. Either ‘monitor’, or ‘time’.
monitor_fail_switch (bool) – Resort to ‘time’ normalization if ‘monitor’ was selected but no monitor counts are available
mask_panel (str) – Either ‘front’ or ‘back’ to mask whole front or back panel.
mask (mask file path, MaskWorkspace, list) – Additional mask to be applied. If list, it is a list of detector ID’s.
btp (dict) – Additional properties to Mantid’s MaskBTP algorithm
solid_angle (bool) – Apply the solid angle correction
sensitivity_file_path (str) – file containing previously calculated sensitivity correction
sensitivity_workspace (str, MatrixWorkspace) – workspace containing previously calculated sensitivity correction. This overrides the sensitivity_filename if both are provided.
wave_length (float, None) – wave length in Angstrom
wavelength_spread (float, None) – wave length spread in Angstrom
sample_aperture_diameter (float, None) – sample aperture diameter in mm
sample_thickness (None, float) – sample thickness in unit cm
source_aperture_diameter (float, None) – source aperture size radius in unit mm
smearing_pixel_size_x (float, None) – pixel size in x direction in unit as meter, only for Q-resolution calculation
smearing_pixel_size_y (float, None) – pixel size in Y direction in unit as meter, only for Q-resolution calculation
output_workspace (str) – Name of the output workspace. If not supplied, will be determined from the supplied value of
data
.output_suffix (str) – If the
output_workspace
is not specified, this is appended to the automatically generated output workspace name.
- Returns:
Reference to the events workspace
- Return type:
- drtsans.mono.gpsans.api.prepare_data_workspaces(data, center_x=None, center_y=None, dark_current=None, flux_method=None, monitor_fail_switch=False, mask_ws=None, mask_panel=None, mask_btp=None, solid_angle=True, sensitivity_workspace=None, output_workspace_name=None, debug=False)[source]¶
Given a “ raw”data workspace, this function provides the following:
centers the detector
subtracts dark current
normalize by time or monitor
applies masks
corrects for solid angle
corrects for sensitivity
All steps are optional. data, mask_ws, dark_current are either None or histogram workspaces. This function does not load any file.
- Parameters:
data (Workspace2D) – raw workspace (histogram)
center_x (float) – Move the center of the detector to this X-coordinate. If
None
, the detector will be moved such that the X-coordinate of the intersection point between the neutron beam and the detector array will havex=0
.center_y (float) – Move the center of the detector to this Y-coordinate. If
None
, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will havey=0
.dark_current (Workspace2D) – histogram workspace containing the dark current measurement
flux_method (str) – Method for flux normalization. Either ‘monitor’, or ‘time’.
monitor_fail_switch (bool) – Resort to ‘time’ normalization if ‘monitor’ was selected but no monitor counts are available
mask_ws (Workspace2D) – Mask workspace
mask_panel (str) – Either ‘front’ or ‘back’ to mask whole front or back panel.
mask_btp (dict) – Additional properties to Mantid’s MaskBTP algorithm
solid_angle (bool) – Apply the solid angle correction
sensitivity_workspace (str, MatrixWorkspace) – workspace containing previously calculated sensitivity correction. This overrides the sensitivity_filename if both are provided.
output_workspace_name (str) – The output workspace name. If None will create data.name()+output_suffix
debug (bool) – Flag for debugging output
- Returns:
Reference to the processed workspace
- Return type:
Workspace2D
- drtsans.mono.gpsans.api.process_single_configuration(sample_ws_raw, sample_trans_ws=None, sample_trans_value=None, bkg_ws_raw=None, bkg_trans_ws=None, bkg_trans_value=None, blocked_ws_raw=None, theta_deppendent_transmission=True, center_x=None, center_y=None, dark_current=None, flux_method=None, monitor_fail_switch=False, mask_ws=None, mask_panel=None, mask_btp=None, solid_angle=True, sensitivity_workspace=None, output_workspace=None, output_suffix='', thickness=1.0, absolute_scale_method='standard', empty_beam_ws=None, beam_radius=None, absolute_scale=1.0, keep_processed_workspaces=True, debug=False)[source]¶
This function provides full data processing for a single experimental configuration, starting from workspaces (no data loading is happening inside this function)
- Parameters:
sample_ws_raw (Workspace2D) – raw data histogram workspace
sample_trans_ws (Workspace2D) – optional histogram workspace for sample transmission
sample_trans_value (float) – optional value for sample transmission
bkg_ws_raw (Workspace2D) – optional raw histogram workspace for background
bkg_trans_ws (Workspace2D) – optional histogram workspace for background transmission
bkg_trans_value (float) – optional value for background transmission
blocked_ws_raw (Workspace2D) – optional histogram workspace for blocked beam
theta_deppendent_transmission (bool) – flag to apply angle dependent transmission
center_x (float) – x center for the beam
center_y (float) – y center for the beam
dark_current (Workspace2D) – dark current workspace
flux_method (str) – normalization by time or monitor
monitor_fail_switch (bool) – resort to ‘time’ normalization if ‘monitor’ was selected but no monitor counts are available
mask_ws (Workspace2D) – user defined mask
mask_panel (str) – mask fron or back panel
mask_btp (dict) – optional bank, tube, pixel to mask
solid_angle (bool) – flag to apply solid angle
sensitivity_workspace (Workspace2D) – workspace containing sensitivity
output_workspace (str) – output workspace name
output_suffix (str) – suffix for output workspace
thickness (float) – sample thickness (cm)
absolute_scale_method (str) – method to do absolute scaling (standard or direct_beam)
empty_beam_ws (Workspace2D) – empty beam workspace for absolute scaling
beam_radius (float) – beam radius for absolute scaling
absolute_scale (float) – absolute scaling value for standard method
keep_processed_workspaces (bool) – flag to keep the processed blocked beam and background workspaces
debug (bool) – flag to do some debugging output
- Returns:
Reference to the processed workspace
- Return type:
Workspace2D
drtsans.mono.gpsans.attenuation module¶
- drtsans.mono.gpsans.attenuation.attenuation_factor(input_workspace)[source]¶
This gets the wavelength and attenuator value from the workspace logs then calculates the attenuation factor based on the fitted parameters for each different attenuator based on the equation
\[attenuation factor = A e^{-B \lambda} + C\]The attenuation scale factor and the uncertainty for this is returned.
The attenuator value pulled from the logs is mapped to the attenuator name by:
0: “Undefined” 1: “Close” 2: “Open”, 3: “x3”, 4: “x30”, 5: “x300”, 6: “x2k”, 7: “x10k”, 8: “x100k”
If the attenuator is one of Undefined, Close or Open then a attenuation factor of 1 with uncertainty 0 is returned
- Parameters:
input_workspace (str, MatrixWorkspace) – Input workspace for which to calculate attenuation factor
- Returns:
attenuation_factor, attenuation_factor_uncertainty
- Return type:
drtsans.mono.gpsans.cg2_spice_to_nexus module¶
- class drtsans.mono.gpsans.cg2_spice_to_nexus.CG2EventNexusConvert[source]¶
Bases:
EventNexusConverter
SPICE to NeXus converter
- drtsans.mono.gpsans.cg2_spice_to_nexus.convert_spice_to_nexus(ipts_number, exp_number, scan_number, pt_number, template_nexus, output_dir=None, spice_dir=None)[source]¶
Convert one SPICE to NeXus
- Parameters:
ipts_number (int) – IPTS
exp_number (int) – experiment number
scan_number (int) – scan
pt_number (int) – pt
template_nexus (str) – path to a GPSANS nED event Nexus file especially for IDF
output_dir (None or str) – output directory of the converted data
spice_dir (None or str) – data file directory for SPICE file. None using default
- Returns:
generated event Nexus file
- Return type:
drtsans.mono.gpsans.prepare_sensitivities_correction module¶
- drtsans.mono.gpsans.prepare_sensitivities_correction.prepare_spice_sensitivities_correction(flood_spice_runs: List[SpiceRun], direct_beam_spice_runs: List[SpiceRun] | None, moving_detectors_methods: bool, min_count_threshold: float, max_count_threshold: float, nexus_dir: str | None, mask_file: str | None, masked_pixels: str | None, beam_center_mask_radius: float, output_dir: str | None, file_suffix: str = 'spice', pixel_calibration_file: str | None = None, solid_angle_correction: bool = True) str [source]¶
- Parameters:
flood_spice_runs (~list) – list of SpiceRun
direct_beam_spice_runs (~list or None) – list of direct beam run (i.e., transmission run) in form of SpiceRun
moving_detectors_methods (bool) – flag of sensitivity preparation method: if True, it is with moving detector. otherwise, detector patch
min_count_threshold (float) – minimum threshold of allowed (normalized) counts
max_count_threshold
nexus_dir
mask_file (str, None) – mask file applied to data
masked_pixels (str, None) – set of pixels to mask
beam_center_mask_radius (float) – radius in unit (mm) of beam center to mask for transmission calculation
output_dir (str, None) – output directory, None for default as /HFIR/{MY_BEAM_LINE}/shared/drt_sensitivity/
file_suffix
pixel_calibration_file (str or None) – if it is specified as a pixel calibration, include pixel calibration in the computation
solid_angle_correction (bool) – do solid angle correction
drtsans.mono.gpsans.reduce_spice module¶
- drtsans.mono.gpsans.reduce_spice.reduce_gpsans_nexus(ipts_number: int, exp_number: int, samples: List[Tuple[int, int]], sample_thick: List[float], sample_names: List[str], bkgd: List[Tuple[int, int]], samples_trans: List[Tuple[int, int]], bkgd_trans: List[Tuple[int, int]], block_beam: Tuple[int, int], empty_trans: List[Tuple[int, int]], beam_center: List[Tuple[int, int]], nexus_dir: str, mask_file_name: str, dark_file_name: str, use_log_1d: bool, use_log_2d_binning: bool, common_configuration: Any, q_range: List[None | int] | Tuple[int | None, int | None], use_mask_back_tubes: bool, debug_output: bool = False)[source]¶
Module contents¶
- class drtsans.mono.gpsans.BinningMethod(value)[source]¶
Bases:
Enum
Binning method
- NOWEIGHT = 1¶
- WEIGHTED = 2¶
- class drtsans.mono.gpsans.BinningParams(min, max, bins)¶
Bases:
tuple
- bins¶
Alias for field number 2
- max¶
Alias for field number 1
- min¶
Alias for field number 0
- drtsans.mono.gpsans.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
andEQSANS106026
. 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 usemantid.api.FileFinder
.
- drtsans.mono.gpsans.abspaths(runnumbers, instrument='', ipts='', directory=None, search_archive=True)[source]¶
- Parameters:
- Returns:
Comma separated list of all of the full paths
- Return type:
- drtsans.mono.gpsans.adjust_back_panels_to_effective_position(workspace)[source]¶
As the back panels are shadowed by its neighboring front panels when the incident beam is hitting at an angle, the effective position of the back panels needs to be adjusted to the center of the gap between its two neighboring front panels.
- Parameters:
workspace – intput workspace
@NOTE: this adjustment must be done right before convert to q space
- drtsans.mono.gpsans.allow_overwrite(folder)[source]¶
Changes permissions for all the files and folders in the path to allow write by anyone. It is not recursive. It will do that only for the files/folders the user has permissions to do that
- Parameters:
path (str) – string to the folder in which the file permissions are to be changed
- Return type:
None
- drtsans.mono.gpsans.apply_calibrations(input_workspace, database=None, calibrations=['BARSCAN', 'TUBEWIDTH'], output_workspace=None)[source]¶
Load and apply pixel calibrations to an input workspace.
devs - Jose Borreguero <borreguerojm@ornl.gov>
- Parameters:
input_workspace (str, MatrixWorkspace, IEventWorkspace) – Input workspace whose pixels are to be calibrated.
database (str, None) – Path to JSON file containing metadata for different past calibrations. If
None
, the default database is used. Currently, these are the default files: - BIOSANS, ‘/HFIR/CG3/shared/calibration/pixel_calibration.json’, - EQSANS, ‘/SNS/EQSANS/shared/calibration/pixel_calibration.json’, - GPSANS, ‘/HFIR/CG2/shared/calibration/pixel_calibration.json’calibrations (str, list) – One or more of ‘BARSCAN’ and/or ‘TUBEWIDTH’.
output_workspace (str) – Name of the output workspace with calibrated pixels. If
None
, the pixels of the input workspace will be calibrated.
- Return type:
MatrixWorkspace, IEventsWorkspace
- drtsans.mono.gpsans.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. Iflist
, it is a list of detector ID’s. If None, it is expected that maskbtp is not empty.panel (str) – Either ‘front’ or ‘back’ to mask a whole panel
btp (dict) – Options to Mantid algorithm MaskBTP or MaskAngle. Will be used if
mask=None
- drtsans.mono.gpsans.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:
- drtsans.mono.gpsans.as_intensities(input_workspace, component='detector1', views=['positions', 'heights', 'widths'])[source]¶
Returns one workspace for each pixel property that is calibrated (e.g., pixel height), and the calibration datum is stored as the intensity value for that pixel. Intended to visualize the calibration in MantidPlot’s instrument viewer. Not required for calibration generation or for data reduction.
Generated workspaces are
`input_name_positions`
,`input_name_heights`
, and`input_name_widths`
, where`input_name`
is the name of the input workspace.- Note: Positions for visualization in Mantid’s instrument view are shifted so that the
lowest position (usually a negative number) becomes zero. The reason being that showing the instrument in Mantid will mask negative intensities, and we want to avoid this.
Mantid algorithms used: CreateWorkspace, <https://docs.mantidproject.org/algorithms/CreateWorkspace-v1.html> LoadEmptyInstrument, <https://docs.mantidproject.org/algorithms/LoadEmptyInstrument-v1.html> LoadInstrument, <https://docs.mantidproject.org/algorithms/LoadInstrument-v1.html>
- Parameters:
input_workspace (str, MatrixWorkspace, IEventsWorkspace) – Workspace from which pixel properties are retrieved.
component (str, list) – Name or list of names for the double detector array panels. For BIOSANS we have ‘detector1’, ‘wing_detector’ or ‘midrange_detector’.
views (list) – Generate views for the pixel properties provided.
- Returns:
A namedtuple containing the ~mantid.api.MatrixWorkspace workspaces with fields ‘positions’, ‘positions_mantid’, ‘heights’, and ‘widths’
- Return type:
namedtuple
- drtsans.mono.gpsans.attenuation_factor(input_workspace)[source]¶
This gets the wavelength and attenuator value from the workspace logs then calculates the attenuation factor based on the fitted parameters for each different attenuator based on the equation
\[attenuation factor = A e^{-B \lambda} + C\]The attenuation scale factor and the uncertainty for this is returned.
The attenuator value pulled from the logs is mapped to the attenuator name by:
0: “Undefined” 1: “Close” 2: “Open”, 3: “x3”, 4: “x30”, 5: “x300”, 6: “x2k”, 7: “x10k”, 8: “x100k”
If the attenuator is one of Undefined, Close or Open then a attenuation factor of 1 with uncertainty 0 is returned
- Parameters:
input_workspace (str, MatrixWorkspace) – Input workspace for which to calculate attenuation factor
- Returns:
attenuation_factor, attenuation_factor_uncertainty
- Return type:
- drtsans.mono.gpsans.bin_all(i_qxqy, i_modq, nxbins, nybins, n1dbins=None, n1dbins_per_decade=None, bin1d_type='scalar', log_scale=False, decade_on_center=False, qmin=None, qmax=None, wedge1_qmin=None, wedge1_qmax=None, wedge2_qmin=None, wedge2_qmax=None, qxrange=None, qyrange=None, annular_angle_bin=1.0, wedges: List[Any] | None = None, symmetric_wedges: bool = True, error_weighted=False, n_wavelength_bin=1) Tuple[IQazimuthal, List[IQmod]] [source]¶
Do all 1D and 2D binning for a configuration or detector
- Parameters:
i_qxqy (IQazimuthal) – Object containing 2D unbinned data I(Qx, Qy). It will be used for 2D binned data, and 1D wedge or annular binned data
i_modq (IQmod) – Object containing 1D unbinned data I(|Q|). It will be used for scalar binned data
nxbins (int) – number of bins in the x direction for 2D binning
nybins (int) – number of bins in the y direction for 2D binning
n1dbins (int) – number of bins for the 1d binning.
n1dbins_per_decade (int) – Total number of bins will be this value multiplied by number of decades from X min to X max
bin1d_type (str) – type of binning for 1D data. Possible choices are ‘scalar’, ‘annular’, or ‘wedge’
log_scale (bool) – if True, 1D scalar or wedge binning will be logarithmic. Ignored for anything else
decade_on_center (bool) – Flag to have the min X and max X on bin center; Otherwise, they will be on bin boundary
qmin (float) – Minimum value of the momentum transfer modulus Q
qmax (float) – Maximum value of the momentum transfer modulus Q
wedge1_qmin (float) – Minimum value of the momentum transfer modulus Q for the first wedge when
bin1d_type = 'wedge'
wedge1_qmax (float) – Maximum value of the momentum transfer modulus Q for the first wedge when
bin1d_type = 'wedge'
wedge2_qmin (float) – Minimum value of the momentum transfer modulus Q for the second wedge when
bin1d_type = 'wedge'
wedge2_qmax (float) – Maximum value of the momentum transfer modulus Q for the second wedge when
bin1d_type = 'wedge'
qxrange (~tuple) – qx min and qx max
qyrange (~tuple) – qy min and qy max
annular_angle_bin (float) – width of annular bin in degrrees. Annular binning is linear
wedges (list) – list of tuples (angle_min, angle_max) for the wedges. Both numbers have to be in the [-90,270) range. It will add the wedge offset by 180 degrees dependent on
symmetric_wedges
symmetric_wedges (bool) – It will add the wedge offset by 180 degrees if True
error_weighted (bool) – if True, the binning is done using the Weighted method
n_wavelength_bin (None, int) – None: keep original wavelength vector. int: number of wavelength bins. 1 to sum all
- Returns:
binned IQazimuthal list of binned ~drtsans.dataobjects.IQmod objects. The list has length 1, unless the ‘wedge’ mode is selected, when the length is the number of original wedges
- Return type:
(IQazimuthal, ~list)
- drtsans.mono.gpsans.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.mono.gpsans.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.mono.gpsans.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:
- drtsans.mono.gpsans.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`
. IfFalse
, 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:
- drtsans.mono.gpsans.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. Iflist
, 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`
isFalse
, only a table object is returned. Otherwise a tube is returned where the first component is the table, and the second item is a dictionary with the additional pieces of data.- Return type:
Table, dict
- drtsans.mono.gpsans.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:
- drtsans.mono.gpsans.calculate_transmission(input_sample, input_reference, radius=None, radius_unit='mm', output_workspace=None)[source]¶
- drtsans.mono.gpsans.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,
- drtsans.mono.gpsans.check_iq_for_binning(i_of_q)[source]¶
Check I(Q) for binning.
Binning I(Q) assumes that 1. there is no NaN or Infinity in intensities 2. there is no NaN, Infinity or Zero in intensity errors
- :exceptionRuntimeError
raise exception if input I(Q) does not meet assumption
- Parameters:
i_of_q – ~drtsans.dataobjects.IQmod or IQazimuthal I(Q)
- drtsans.mono.gpsans.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:
- Returns:
List of detector ID’s
- Return type:
- drtsans.mono.gpsans.convert_to_q(ws, mode, resolution_function=<function mono_resolution>, **kwargs)[source]¶
Convert a workspace with units of wavelength into a series of arrays: intensity, error, q (or q components), delta q (or delta q components), and wavelength
Using the scattering angle as \(2\theta\) and azimuthan angle as \(\phi\),the calculaion of momentum transfer is:
‘scalar’ mode:
\[|Q| = \frac{4\pi}{\lambda}\sin\theta\]‘azimuthal’ mode:
\[ \begin{align}\begin{aligned}Q_x=\frac{4\pi}{\lambda}\sin\theta\cos\phi\\Q_y=\frac{4\pi}{\lambda}\sin\theta\sin\phi\end{aligned}\end{align} \]‘crystallographic’ mode:
\[ \begin{align}\begin{aligned}Q_x=\frac{2\pi}{\lambda}\sin(2\theta)\cos\phi\\Q_y=\frac{2\pi}{\lambda}\sin(2\theta)\sin\phi\\Qz_=\frac{2\pi}{\lambda}(\cos(2\theta)-1)\end{aligned}\end{align} \]It calls drtsans.momentum_transfer.convert_to_q
- Parameters:
ws (str, IEventWorkspace, MatrixWorkspace) – Workspace in units of wavelength
mode (str) – Available options are ‘scalar’, ‘azimuthal’, and ‘crystallographic’
resolution_function – Function to calculate resolution
kwargs – Parameters to be passed to the resolution function
- Returns:
A namedtuple with fields for
intensity
error
mod_q (\(|Q|\)) or qx, qy (\(Q_x, Q_y\)) or qx, qy, qz (\(Q_x, Q_y, Q_z\)) (depending on the mode)
delta_q or delta_qx, delta_qy or delta_qx, delta_qy, delta_qz - the resolution along the q components
wavelength
- Return type:
namedtuple
- drtsans.mono.gpsans.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:
- drtsans.mono.gpsans.determine_1d_linear_bins(x_min, x_max, bins)[source]¶
Determine linear bin edges and centers
- drtsans.mono.gpsans.determine_1d_log_bins(x_min, x_max, decade_on_center, n_bins_per_decade=None, n_bins=None)[source]¶
- Parameters:
x_min (float) – minimum value of X in the bins
x_max (float) – maximum value of X in the bins
decade_on_center (bool) – flag that data must be centered on decades
n_bins_per_decade (int, None) – density of points (number of data points per decade)
n_bins (int, None) – total number of points in the output
- drtsans.mono.gpsans.empty_beam_scaling(input_workspace, empty_beam_workspace, beam_radius=None, unit='mm', attenuator_coefficient=1.0, attenuator_error=0.0, output_workspace=None)[source]¶
Normalize input workspace by the intensity impinging on the detector for an empty beam run, taking into account attenuation.
Mantid Algorithms used: Divide, DeleteWorkspace,
- Parameters:
input_workspace (str, MatrixWorkspace, IEventsWorkspace) – Workspace to be normalized
empty_beam_workspace (str, MatrixWorkspace, IEventsWorkspace) – Attenuated intensities collected at the detector with and empty beam.
beam_radius (float) – Radius of the beam at the detector. If None, it will be estimated with the sample and source apertures.
unit (str) – Units for the beam radius, either meters (‘m’) or mili-miters (‘mm’).
attenuator_coefficient (float) – Fraction of the neutrons allowed to pass through the attenuator. Assumed wavelength independent.
attenuator_error (float) – Estimated error for the attenuator coefficient.
output_workspace (str) – Name of the normalized workspace. If
None
, then the name ofinput_workspace
will be used, thus overwritinginput_workspace
.
- Return type:
MatrixWorkspace, IEventsWorkspace
- drtsans.mono.gpsans.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
andEQSANS106026
. It will search your data search path and the data archive using ONCat.This uses mantid.api.FileFinder.
- drtsans.mono.gpsans.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:
- 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:
- drtsans.mono.gpsans.load_all_files(reduction_input, prefix='', load_params=None, path: str | List[str] = None, use_nexus_idf: bool = False, debug_output: bool = False, back_panel_correction: bool = False)[source]¶
load all required files at the beginning, and transform them to histograms
- Parameters:
reduction_input
prefix
load_params
path – Absolute path to one or more directories where to search for the NeXus files
use_nexus_idf (bool) – Flag to use IDF inside NeXus file. True for SPICE data
debug_output (bool) – Flag to save out internal result
back_panel_correction (bool) – Move the z direction of back panel to remove artifacts in azimuthal plots
- drtsans.mono.gpsans.load_and_split(run, sample_to_si_name, si_nominal_distance, data_dir=None, output_workspace=None, output_suffix='', overwrite_instrument=True, pixel_calibration=False, time_interval: float | List[float] | None = None, time_offset: float = 0.0, time_period: float | None = None, log_name=None, log_value_interval=None, sample_to_si_value=None, sample_detector_distance_value=None, reuse_workspace=False, monitors=False, **kwargs)[source]¶
Load an event NeXus file and filter into a WorkspaceGroup depending on the provided filter options. Either a time_interval must be provided or a log_name and log_value_interval.
Metadata added to output workspace includes the
slice
number,number_of_slices
,slice_parameter
,slice_interval
,slice_start
andslice_end
.For EQSANS two WorkspaceGroup’s are return, one for the filtered data and one for filtered monitors
- Parameters:
run (str, IEventWorkspace) – Examples:
CG3_55555
,CG355555
or file path.sample_to_si_name (str) – Meta data name for sample to Silicon window distance
si_nominal_distance (float) – distance between nominal position to silicon window. unit = meter
output_workspace (str) – If not specified it will be
BIOSANS_55555
determined from the supplied value ofrun
.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. IfTrue
, use the latest instrument definition file (IDF) available in Mantid. Ifstr
, then it should be the filepath to the desired IDF.pixel_calibration (bool) – Adjust pixel heights and widths according to bar-scan and tube-width calibrations.
time_interval – Array for lengths of time intervals for splitters. If the array has one value, then all splitters will have same time intervals. If the size of the array is larger than one, then the splitters can have various time interval values.
time_offset – Offset to be added to the start time of the first splitter, in seconds.
time_period – A multiple integer of the time interval. If specified, it indicates that the time slicing is periodic so that events in time intervals separated by one (or more) period should be reduced together.
sample_to_si_value (float or None) – Sample to silicon window distance to overwrite the EPICS value. None for no operation. unit = meter
sample_detector_distance_value (float or None) – Sample to detector distance to overwrite the EPICS value. None for no operation. unit = meter
log_name (string) – Name of the sample log to use to filter. For example, the pulse charge is recorded in ‘ProtonCharge’.
log_value_interval (float) – Delta of log value to be sliced into from min log value and max log value.
reuse_workspace (bool) – When true, return the
output_workspace
if it already existsmonitors (bool) – flag to load monitors
kwargs (dict) – Additional positional arguments for LoadEventNexus.
- Returns:
Reference to the workspace groups containing all the split workspaces
- Return type:
WorkspaceGroup
- drtsans.mono.gpsans.load_calibration(input_workspace, caltype, component='detector1', database=None, output_workspace=None)[source]¶
Load a calibration into a ~drtsans.pixel_calibration.Table object.
devs - Jose Borreguero <borreguerojm@ornl.gov>
- Parameters:
input_workspace (str, MatrixWorkspace, IEventsWorkspace) – Workspace from which calibration session is to be retrieved.
caltype (str) – Either ‘BARSCAN’ or ‘TUBEWIDTH’. A saved calibration can only contain one of these, but not both.
component (str) – Name of one of the double detector array panels. For BIOSANS we have ‘detector1’, ‘wing-detector’ or ‘midrange_detector’
database (str) – Path to database file containing the metadata for the calibrations. If
None
, the default database is used. Currently, these are the default files: - BIOSANS, ‘/HFIR/CG3/shared/calibration/pixel_calibration.json’, - EQSANS, ‘/SNS/EQSANS/shared/calibration/pixel_calibration.json’, - GPSANS, ‘/HFIR/CG2/shared/calibration/pixel_calibration.json’output_workspace (str) – Name of the table workspace containing the calibration session values. If
None
, then a composite name is created using the calibration type, instrument, component, and daystamp. (e.g. “barscan_gpsans_detector1_20200311”)
- Return type:
Table
- drtsans.mono.gpsans.load_dark_current_workspace(dark_current_filename, output_workspace)[source]¶
Loads dark current workspace. Useful to avoid multiple loads from disk.
Mantid algorithms used: LoadEventNexus,
- drtsans.mono.gpsans.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 ofrun
.overwrite_instrument (bool, str) – If not
False
, ignore the instrument embedeed in the Nexus file. IfTrue
, use the latest instrument definition file (IDF) available in Mantid. Ifstr
, 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 existskwargs (dict) – Additional positional arguments for LoadEventNexus.
- Returns:
Reference to the events workspace
- Return type:
- drtsans.mono.gpsans.load_events_and_histogram(run, data_dir=None, output_workspace=None, output_suffix='', overwrite_instrument=True, pixel_calibration=False, reuse_workspace=False, sample_to_si_name=None, si_nominal_distance=None, sample_to_si_value=None, sample_detector_distance_value=None, **kwargs)[source]¶
Load one or more event Nexus file produced by the instruments at HFIR. Convert to wavelength and sums the data.
- Parameters:
run (str, list of runs to load) – Examples:
CG3_55555
,CG355555
, file path,CG3_55555,CG3_55556
output_workspace (str) – If not specified it will be
BIOSANS_55555
determined from the supplied value ofrun
.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. IfTrue
, use the latest instrument definition file (IDF) available in Mantid. Ifstr
, then it should be the filepath to the desired IDF.pixel_calibration (bool) – Adjust pixel heights and widths according to bar-scan and tube-width calibrations.
sample_to_si_name (str) – Meta data name for sample to Silicon window distance
si_nominal_distance (float) – distance between nominal position to silicon window. unit = meter
sample_to_si_value (float or None) – Sample to silicon window distance to overwrite the EPICS value. None for no operation. unit = meter
sample_detector_distance_value (float or None) – Sample to detector distance to overwrite the EPICS value. None for no operation. unit = meter
reuse_workspace (bool) – When true, return the
output_workspace
if it already existskwargs (dict) – Additional positional arguments for LoadEventNexus.
- Return type:
- drtsans.mono.gpsans.load_histogram(filename, output_workspace=None, wavelength=None, wavelength_spread=None, sample_det_cent=None)[source]¶
Loads a SANS data file produce by the HFIR instruments at ORNL. The instrument geometry is also loaded. The center of the detector is placed at (0, 0, sample_det_cent )
- Parameters:
filename (str) – The name of the input xml file to load
output_workspace (str, optional) – The optional name of the output workspace. If
None
is the filename stripped of the extension.wavelength (float) – The wavelength value to use when loading the data file (Angstrom). This value will be used instead of the value found in the data file.
wavelength_spread (float) – wavelength spread value to use when loading the data file (Angstrom). This value will be used instead of the value found in the data file.
sample_det_cent (float) – Sample to detector distance to use (overrides meta data) in mm
- Returns:
A reference for the workspace created.
- Return type:
- drtsans.mono.gpsans.load_iqmod(file, sep=' ', header_type='Pandas')[source]¶
Load an intensity profile into a ~drtsans.dataobjects.IQmod object.
Required file format: The first row must include the names for the file columns. The order of the columns is irrelevant and the names of the columns must be: - ‘intensity’ for profile intensities. This column is required. - ‘error’ for uncertainties in the profile intensities. This column is required. - ‘mod_q’ for values of Q. This column is required. - ‘delta_mod_q’ for uncertainties in the Q values. This column is optional. - ‘wavelength’ This column is optional.
- Example of file contents:
intensity error mod_q 1000.0 89.0 0.001 90.0 8.0 0.01 4.7 0.9 0.1
Usage example:
` from drtsans.mono.gpsans import load_iqmod iq = load_iqmod(file_name) `
- drtsans.mono.gpsans.load_mono(filename, **kwargs)[source]¶
Loads a SANS data file produce by the HFIR instruments at ORNL.
- Parameters:
- Return type:
- drtsans.mono.gpsans.normalize_by_flux(ws, method)[source]¶
Normalize to time or monitor
- Parameters:
input_workspace (MatrixWorkspace)
method (str) – Normalization method: ‘time’ or ‘monitor’
- drtsans.mono.gpsans.normalize_by_monitor(input_workspace, output_workspace=None)[source]¶
Normalize by the monitor value
Mantid algorithms used: :ref: CreateSingleValuedWorkspace <algm-CreateSingleValuedWorkspace-v1> :ref:`Divide <algm-Divide-v1>,
- Parameters:
input_workspace (MatrixWorkspace)
output_workspace (str) – Optional name of the output workspace. Default is to replace the input workspace
- Returns:
the normalized input workspace
- Return type:
- Raises:
RuntimeError – No monitor metadata found in the sample logs of the input workspace
- drtsans.mono.gpsans.normalize_by_thickness(input_workspace, thickness)[source]¶
Normalize input workspace by thickness
- Parameters:
input_workspace (str, MatrixWorkspace)
thickness (float) – Thickness of the sample in centimeters.
- Return type:
- drtsans.mono.gpsans.normalize_by_time(input_workspace, output_workspace=None)[source]¶
Normalize by time Used to normalize dark current
Mantid algorithms used: Divide,
- Parameters:
input_workspace (MatrixWorkspace)
output_workspace (str) – Optional name of the output workspace. Default is to replace the input workspace
- drtsans.mono.gpsans.normalize_dark_current(dark_workspace, output_workspace=None)[source]¶
Divide a dark current workspace by its duration.
Entry ‘normalizing_duration’ is added to the logs of the normalized dark current to annotate what log entry was used to find the duration
Mantid algorithms used: Scale, DeleteWorkspace,
- Parameters:
dark_workspace (str, MatrixWorkspace) – Dark current workspace
output_workspace (str) – Name of the normalized dark workspace. If None, the name of the input workspace dark_workspace is chosen (and the input workspace is overwritten).
- Returns:
Output workspace
- Return type:
MatrixWorkspace
- drtsans.mono.gpsans.plot_IQazimuthal(workspace, filename, backend: str = 'd3', qmin: float | None = None, qmax: float | None = None, wedges: List[Any] | None = None, symmetric_wedges: bool = True, mask_alpha=0.6, imshow_kwargs: Dict = {}, **kwargs)[source]¶
Save a plot of I(Qx, Qy). If qmin is specified, all I(Q) with Q less than qmin will be masked in output plot. If qmax is specified, all I(Q) with Q greater than qmax will be masked in output plot. If wedges are specified, all I(Q) out side of wedges will be masked in output plot.
- Parameters:
workspace (IQazimuthal) – The workspace (i.e., I(Qx, Qy)) to plot. This assumes the data is binned on a constant grid.
filename (str) – The name of the file to save to. For the
MATPLOTLIB
backend, the type of file is determined from the file extensionqmin (float) – minimum 1D Q for plotting selection area
qmax (float) – maximum 1D Q for plotting selection area
wedges (~list or None) – list of tuples (angle_min, angle_max) for the wedges. Select wedges to plot. Both numbers have to be in the [-90,270) range. It will add the wedge offset by 180 degrees dependent on
symmetric_wedges
symmetric_wedges (bool) – Add the wedge offset by 180 degrees if True
mask_alpha (float) – Opacity for for selection area
backend – Which backend to save the file using
imshow_kwargs (~dict) – Optional arguments to
matplotlib.axes.Axes.imshow
e.g.{"norm": LogNorm()}
kwargs (~dict) – Additional key word arguments for
matplotlib.axes.Axes
- drtsans.mono.gpsans.plot_IQmod(workspaces, filename, loglog=True, backend: str = 'd3', errorbar_kwargs={}, **kwargs)[source]¶
Save a plot representative of the supplied workspaces
- Parameters:
workspaces (list, tuple) – A collection of
IQmod
workspaces to plot. If only one is desired, it must still be supplied in alist
ortuple
.filename (str) – The name of the file to save to. For the
MATPLOTLIB
backend, the type of file is determined from the file extensionloglog (bool) – If true will set both axis to logarithmic, otherwise leave them as linear
backend – Which backend to save the file using
errorbar_kwargs (dict) – Optional arguments to
matplotlib.axes.Axes.errorbar
Can be a comma separated list for each workspace e.g.{'label':'main,wing,both', 'color':'r,b,g', 'marker':'o,v,.'}
kwargs (dict) – Additional key word arguments for
matplotlib.axes.Axes
- drtsans.mono.gpsans.plot_detector(input_workspace, filename=None, backend: str = 'd3', axes_mode='tube-pixel', panel_name=None, figure_kwargs={'figsize': (8, 6)}, imshow_kwargs={'norm': <matplotlib.colors.LogNorm object>})[source]¶
Save a 2D plot representative of the supplied workspace
- Parameters:
input_workspace (str, MatrixWorkspace) – The workspace to plot
filename (str) – The name of the file to save to. For the
MATPLOTLIB
backend, the type of file is determined from the file extensionbackend – Which backend to save the file using
axes_mode (str) – Plot intensities versus different axes. Options are: ‘xy’ for plotting versus pixel coordinates; ‘tube-pixel’ for plotting versus tube and pixel index.
panel_name (str) – Name of the double panel detector array. If
None
, plots will be generated for all arrays.figure_kwargs (str) – Optional arguments to matplotlib.pyplot.figure
imshow_kwargs (dict) – Optional arguments to matplotlib.axes.Axes.imshow
- drtsans.mono.gpsans.plot_reduction_output(reduction_output, reduction_input, loglog=True, imshow_kwargs=None, close_figures=False)[source]¶
- drtsans.mono.gpsans.prepare_data(data, pixel_calibration=False, mask_detector=None, detector_offset=0, sample_offset=0, center_x=None, center_y=None, dark_current=None, flux_method=None, monitor_fail_switch=False, mask=None, mask_panel=None, btp={}, solid_angle=True, sensitivity_file_path=None, sensitivity_workspace=None, wave_length=None, wavelength_spread=None, sample_aperture_diameter=None, sample_thickness=None, source_aperture_diameter=None, smearing_pixel_size_x=None, smearing_pixel_size_y=None, output_workspace=None, output_suffix='', **kwargs)[source]¶
Load a GPSANS data file and bring the data to a point where it can be used. This includes applying basic corrections that are always applied regardless of whether the data is background or scattering data.
- Parameters:
data (int, str, IEventWorkspace) – Run number as int or str, file path,
IEventWorkspace
pixel_calibration (bool, str) – Adjust pixel heights and widths according to barscan and tube-width calibrations. Options are (1) No calibration (False), (2) default calibration file (True) (3) user specified calibration file (str)
mask_detector (str) – Name of an instrument component to mask
detector_offset (float) – Additional translation of the detector along Z-axis, in millimeters.
sample_offset (float) – Additional translation of the sample along the Z-axis, in millimeters.
center_x (float) – Move the center of the detector to this X-coordinate. If
None
, the detector will be moved such that the X-coordinate of the intersection point between the neutron beam and the detector array will havex=0
.center_y (float) – Move the center of the detector to this Y-coordinate. If
None
, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will havey=0
.dark_current (int, str, IEventWorkspace) – Run number as int or str, file path,
IEventWorkspace
flux_method (str) – Method for flux normalization. Either ‘monitor’, or ‘time’.
monitor_fail_switch (bool) – Resort to ‘time’ normalization if ‘monitor’ was selected but no monitor counts are available
mask_panel (str) – Either ‘front’ or ‘back’ to mask whole front or back panel.
mask (mask file path, MaskWorkspace, list) – Additional mask to be applied. If list, it is a list of detector ID’s.
btp (dict) – Additional properties to Mantid’s MaskBTP algorithm
solid_angle (bool) – Apply the solid angle correction
sensitivity_file_path (str) – file containing previously calculated sensitivity correction
sensitivity_workspace (str, MatrixWorkspace) – workspace containing previously calculated sensitivity correction. This overrides the sensitivity_filename if both are provided.
wave_length (float, None) – wave length in Angstrom
wavelength_spread (float, None) – wave length spread in Angstrom
sample_aperture_diameter (float, None) – sample aperture diameter in mm
sample_thickness (None, float) – sample thickness in unit cm
source_aperture_diameter (float, None) – source aperture size radius in unit mm
smearing_pixel_size_x (float, None) – pixel size in x direction in unit as meter, only for Q-resolution calculation
smearing_pixel_size_y (float, None) – pixel size in Y direction in unit as meter, only for Q-resolution calculation
output_workspace (str) – Name of the output workspace. If not supplied, will be determined from the supplied value of
data
.output_suffix (str) – If the
output_workspace
is not specified, this is appended to the automatically generated output workspace name.
- Returns:
Reference to the events workspace
- Return type:
- drtsans.mono.gpsans.prepare_data_workspaces(data, center_x=None, center_y=None, dark_current=None, flux_method=None, monitor_fail_switch=False, mask_ws=None, mask_panel=None, mask_btp=None, solid_angle=True, sensitivity_workspace=None, output_workspace_name=None, debug=False)[source]¶
Given a “ raw”data workspace, this function provides the following:
centers the detector
subtracts dark current
normalize by time or monitor
applies masks
corrects for solid angle
corrects for sensitivity
All steps are optional. data, mask_ws, dark_current are either None or histogram workspaces. This function does not load any file.
- Parameters:
data (Workspace2D) – raw workspace (histogram)
center_x (float) – Move the center of the detector to this X-coordinate. If
None
, the detector will be moved such that the X-coordinate of the intersection point between the neutron beam and the detector array will havex=0
.center_y (float) – Move the center of the detector to this Y-coordinate. If
None
, the detector will be moved such that the Y-coordinate of the intersection point between the neutron beam and the detector array will havey=0
.dark_current (Workspace2D) – histogram workspace containing the dark current measurement
flux_method (str) – Method for flux normalization. Either ‘monitor’, or ‘time’.
monitor_fail_switch (bool) – Resort to ‘time’ normalization if ‘monitor’ was selected but no monitor counts are available
mask_ws (Workspace2D) – Mask workspace
mask_panel (str) – Either ‘front’ or ‘back’ to mask whole front or back panel.
mask_btp (dict) – Additional properties to Mantid’s MaskBTP algorithm
solid_angle (bool) – Apply the solid angle correction
sensitivity_workspace (str, MatrixWorkspace) – workspace containing previously calculated sensitivity correction. This overrides the sensitivity_filename if both are provided.
output_workspace_name (str) – The output workspace name. If None will create data.name()+output_suffix
debug (bool) – Flag for debugging output
- Returns:
Reference to the processed workspace
- Return type:
Workspace2D
- drtsans.mono.gpsans.process_single_configuration(sample_ws_raw, sample_trans_ws=None, sample_trans_value=None, bkg_ws_raw=None, bkg_trans_ws=None, bkg_trans_value=None, blocked_ws_raw=None, theta_deppendent_transmission=True, center_x=None, center_y=None, dark_current=None, flux_method=None, monitor_fail_switch=False, mask_ws=None, mask_panel=None, mask_btp=None, solid_angle=True, sensitivity_workspace=None, output_workspace=None, output_suffix='', thickness=1.0, absolute_scale_method='standard', empty_beam_ws=None, beam_radius=None, absolute_scale=1.0, keep_processed_workspaces=True, debug=False)[source]¶
This function provides full data processing for a single experimental configuration, starting from workspaces (no data loading is happening inside this function)
- Parameters:
sample_ws_raw (Workspace2D) – raw data histogram workspace
sample_trans_ws (Workspace2D) – optional histogram workspace for sample transmission
sample_trans_value (float) – optional value for sample transmission
bkg_ws_raw (Workspace2D) – optional raw histogram workspace for background
bkg_trans_ws (Workspace2D) – optional histogram workspace for background transmission
bkg_trans_value (float) – optional value for background transmission
blocked_ws_raw (Workspace2D) – optional histogram workspace for blocked beam
theta_deppendent_transmission (bool) – flag to apply angle dependent transmission
center_x (float) – x center for the beam
center_y (float) – y center for the beam
dark_current (Workspace2D) – dark current workspace
flux_method (str) – normalization by time or monitor
monitor_fail_switch (bool) – resort to ‘time’ normalization if ‘monitor’ was selected but no monitor counts are available
mask_ws (Workspace2D) – user defined mask
mask_panel (str) – mask fron or back panel
mask_btp (dict) – optional bank, tube, pixel to mask
solid_angle (bool) – flag to apply solid angle
sensitivity_workspace (Workspace2D) – workspace containing sensitivity
output_workspace (str) – output workspace name
output_suffix (str) – suffix for output workspace
thickness (float) – sample thickness (cm)
absolute_scale_method (str) – method to do absolute scaling (standard or direct_beam)
empty_beam_ws (Workspace2D) – empty beam workspace for absolute scaling
beam_radius (float) – beam radius for absolute scaling
absolute_scale (float) – absolute scaling value for standard method
keep_processed_workspaces (bool) – flag to keep the processed blocked beam and background workspaces
debug (bool) – flag to do some debugging output
- Returns:
Reference to the processed workspace
- Return type:
Workspace2D
- drtsans.mono.gpsans.reduce_single_configuration(loaded_ws, reduction_input, prefix='', skip_nan=True, debug_output=False)[source]¶
- drtsans.mono.gpsans.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_particularvalidate (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:
- drtsans.mono.gpsans.registered_workspace(source)[source]¶
Find out if the source is a workspace registered in the Analysis Data Service.
- drtsans.mono.gpsans.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 apertureunit (str) – return aperture in requested length unit, either ‘m’ or ‘mm’
- Return type:
- drtsans.mono.gpsans.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:
- drtsans.mono.gpsans.save_iqmod(iq, file, sep=' ', float_format='%.6E', skip_nan=True, header_type='MantidAscii')[source]¶
Write the ~drtsans.dataobjects.IQmod object into an ASCII file.
Current output columns (Line 0: ) intensity error mod_q Expected (Line 0: ) mod_q intensity error mod_q_error
- Parameters:
iq (IQmod) – Profile to be saved
file (str) – Path to output file
sep (str) – String of length 1. Field delimiter for the output file.
float_format (str) – Format string for floating point numbers.
skip_nan (bool) – If true, any data point where intensity is NAN will not be written to file
header (text) – Determine the header type to make 1D data compatible with panda or Mantid possible values: HeaderType.MANTID_ASCII.value HeaderType.PANDAS.value
- drtsans.mono.gpsans.search_sample_detector_distance_meta_name(source, specified_meta_name)[source]¶
Search meta data (sample logs) for sample detector distance
- Parameters:
source (PyObject) – Instrument object, MatrixWorkspace, workspace name, file name, run number.
specified_meta_name (str, None) – Only search for the given string in the source’s meta data (logs). Do not use default log keys
- Returns:
item = (str, float, str) meta data name, sample detector distance value, unit
- Return type:
~list
- drtsans.mono.gpsans.search_source_sample_distance_meta_name(source, specified_meta_name)[source]¶
Search meta data (sample logs) for source-sample distance
- Parameters:
source (PyObject) – Instrument object, MatrixWorkspace, workspace name, file name, run number.
specified_meta_name (str, None) – Only search for the given string in the source’s meta data (logs). Do not use default log keys
- Returns:
item = (str, float, str) meta data name, sample detector distance value, unit
- Return type:
~list
- drtsans.mono.gpsans.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.mono.gpsans.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:
- drtsans.mono.gpsans.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:
- drtsans.mono.gpsans.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 apertureunit (str) – return aperture in requested length unit, either ‘m’ or ‘mm’
- Return type:
- drtsans.mono.gpsans.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:
- Returns:
distance between source and sample, in selected units
- Return type:
- drtsans.mono.gpsans.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.
- drtsans.mono.gpsans.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 ofinput_workspace
will be used, thus overwritinginput_workspace
.
- Return type:
- drtsans.mono.gpsans.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:
- Raises:
ValueError – If either the arguments are incorrect ((i) profiles not in order or increasing Q or (ii) the number of overlaps not congruent with the number of profiles or (iii) overlaps is not a list of numbers or list of lists/tuples) or a stitching scaling factor <= 0 is calculated.
- drtsans.mono.gpsans.subtract_dark_current(data_workspace, dark, output_workspace=None)[source]¶
Subtract normalized dark from data, taking into account the duration of both the data and dark runs.
normalized_data = data - (data_duration / dark_duration) * dark
Mantid algorithms used: Scale, Minus DeleteWorkspace
- Parameters:
data_workspace (MatrixWorkspace) – Sample scattering with intensities versus wavelength.
dark (int, str, MatrixWorkspace) – run number, file path, workspace name, or
MatrixWorkspace
for dark current.output_workspace (str) – Name of the output workspace. If None, the name of the input workspace data_workspace is chosen (and the input workspace is overwritten).
- Return type:
MatrixWorkspace
- drtsans.mono.gpsans.sum_data(data_list, output_workspace, sum_logs=('duration', 'timer', 'monitor', 'monitor1'))[source]¶
Merge data set together, summing the listed logs
- Parameters:
- Return type:
Workspace2D
- drtsans.mono.gpsans.transform_to_wavelength(input_workspace, output_workspace=None)[source]¶
Transforms the event files with fake time of flight from the SANS instruments at HFIR into histograms in wavelength.
Mantid Algorithms used: HFIRSANS2Wavelength,
- Parameters:
input_workspace (str, IEventWorkspace) – Events workspace in time-of-flight.
output_workspace (str) – Name of the output workspace. If
None
, the name of the input_workspace will be used, thus overwriting the input workspace.
- Return type:
- drtsans.mono.gpsans.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. IfFalse
, substitute the current z-coordinate with the new value.
- drtsans.mono.gpsans.translate_sample_by_z(workspace, z)[source]¶
Shift the position of the sample by the desired amount
- Parameters:
workspace (MatrixWorkspace) – Input workspace containing instrument file
z (float) – Translation to be applied in meters. Positive values are downstream.
- drtsans.mono.gpsans.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:
- Return type: