def convert(self, wavelength_min, wavelength_max, detector_workspace_indexes, monitor_workspace_index, correct_monitor=False, bg_min=None, bg_max=None): """ Run the conversion Arguments: workspace_ids: Start and end ranges. Ids to be considered as workspaces. Nested list syntax supported wavelength_min: min wavelength in x for monitor workspace wavelength_max: max wavelength in x for detector workspace detector_workspace_indexes: Tuple of workspace indexes (or tuple of tuple min, max ranges to keep) monitor_workspace_index: The index of the monitor workspace correct_monitor: Flag indicating that monitors should have a flat background correction applied bg_min: x min background in wavelength bg_max: x max background in wavelength Returns: _monitor_ws: A workspace of monitors """ # Sanity check inputs. if wavelength_min >= wavelength_max: raise ValueError("Wavelength_min must be < wavelength_max min: %s, max: %s" % (wavelength_min, wavelength_max)) if correct_monitor and not all((bg_min, bg_max)): raise ValueError("Either provide ALL, monitors_to_correct, bg_min, bg_max or none of them") if all((bg_min, bg_max)) and bg_min >= bg_max: raise ValueError("Background min must be < Background max") sum = ConvertToWavelength.sum_workspaces(self.__ws_list) sum_wavelength= msi.ConvertUnits(InputWorkspace=sum, Target="Wavelength", AlignBins='1') logger.debug("Monitor detector index %s" % str(monitor_workspace_index)) # Crop out the monitor workspace _monitor_ws = msi.CropWorkspace(InputWorkspace=sum_wavelength, StartWorkspaceIndex=monitor_workspace_index,EndWorkspaceIndex=monitor_workspace_index) # Crop out the detector workspace then chop out the x-ranges of interest. _detector_ws = ConvertToWavelength.crop_range(sum_wavelength, detector_workspace_indexes) _detector_ws = msi.CropWorkspace(InputWorkspace=_detector_ws, XMin=wavelength_min, XMax=wavelength_max) # Apply a flat background if correct_monitor and all((bg_min, bg_max)): _monitor_ws = msi.CalculateFlatBackground(InputWorkspace=_monitor_ws,WorkspaceIndexList=0,StartX=bg_min, EndX=bg_max) msi.DeleteWorkspace(Workspace=sum_wavelength.name()) return (_monitor_ws, _detector_ws)
def _crop_single_ws_in_tof(ws_to_rebin, x_max, x_min): """ Implementation of cropping the single workspace in TOF. First converts to TOF, crops then converts back to the original unit. :param ws_to_rebin: The workspace to crop :param x_max: (Optional) The minimum TOF values to crop to :param x_min: (Optional) The maximum TOF values to crop to :return: The cropped workspace with the original units """ previous_units = ws_to_rebin.getAxis(0).getUnit().unitID() if previous_units != "TOF": ws_to_rebin = mantid.ConvertUnits(InputWorkspace=ws_to_rebin, Target="TOF", OutputWorkspace=ws_to_rebin) if x_min > x_max: raise ValueError("XMin is larger than XMax. (" + str(x_min) + " > " + str(x_max) + ")") if x_max <= 1 and x_min <= 1: # If <= 1, cropping by fractions, not absolutes x_axis = ws_to_rebin.dataX(0) x_min = x_axis[0] * (1 + x_min) x_max = x_axis[-1] * x_max cropped_ws = mantid.CropWorkspace(InputWorkspace=ws_to_rebin, OutputWorkspace=ws_to_rebin, XMin=x_min, XMax=x_max) if previous_units != "TOF": cropped_ws = mantid.ConvertUnits(InputWorkspace=cropped_ws, Target=previous_units, OutputWorkspace=cropped_ws) return cropped_ws
def ProcessVana(rnum, cycle): # Preparation of the V/Nd sphere run for SX normalization mantid.LoadRaw(Filename='/archive/NDXWISH/Instrument/data/cycle_' + cycle + '/WISH000' + str(rnum) + '.raw', OutputWorkspace='Vana', LoadMonitors='Separate') mantid.CropWorkspace(InputWorkspace='Vana', OutputWorkspace='Vana', XMin=6000, XMax=99000) mantid.NormaliseByCurrent(InputWorkspace='Vana', OutputWorkspace='Vana') mantid.ConvertUnits(InputWorkspace='Vana', OutputWorkspace='Vana', Target='Wavelength') # create Abs Correction for V shape = '''<sphere id="V-sphere"> <centre x="0.0" y="0.0" z="0.0" /> <radius val="0.0025"/> </sphere>''' mantid.CreateSampleShape('Vana', shape) mantid.SetSampleMaterial('Vana', SampleNumberDensity=0.0719, ScatteringXSection=5.197, AttenuationXSection=4.739, ChemicalFormula='V0.95 Nb0.05') mantid.AbsorptionCorrection(InputWorkspace='Vana', OutputWorkspace='Abs_corr', ElementSize=0.5) # SphericalAbsorption(InputWorkspace='WISH00038428', OutputWorkspace='Abs_corr_sphere', SphericalSampleRadius=0.25) # correct Vanadium run for absorption mantid.Divide(LHSWorkspace='Vana', RHSWorkspace='Abs_corr', OutputWorkspace='Vana_Abs') mantid.DeleteWorkspace('Vana') mantid.DeleteWorkspace('Abs_corr') # Smoot data with redius 3 mantid.SmoothNeighbours(InputWorkspace='Vana_Abs', OutputWorkspace='Vana_smoot', Radius=3) mantid.DeleteWorkspace('Vana_Abs') # SmoothData38428 mantid.SmoothData(InputWorkspace='Vana_smoot', OutputWorkspace='Vana_smoot1', NPoints=300) mantid.DeleteWorkspace('Vana_smoot')
def normalise_ws_current(ws_to_correct, monitor_ws, spline_coeff, lambda_values, integration_range, ex_regions): processed_monitor_ws = mantid.ConvertUnits(InputWorkspace=monitor_ws, Target="Wavelength") processed_monitor_ws = mantid.CropWorkspace(InputWorkspace=processed_monitor_ws, XMin=lambda_values[0], XMax=lambda_values[-1]) for reg in range(0, 4): processed_monitor_ws = mantid.MaskBins(InputWorkspace=processed_monitor_ws, XMin=ex_regions[0, reg], XMax=ex_regions[1, reg]) splined_monitor_ws = mantid.SplineBackground(InputWorkspace=processed_monitor_ws, WorkspaceIndex=0, NCoeff=spline_coeff) normalised_ws = mantid.ConvertUnits(InputWorkspace=ws_to_correct, Target="Wavelength", OutputWorkspace=ws_to_correct) normalised_ws = mantid.NormaliseToMonitor(InputWorkspace=normalised_ws, MonitorWorkspace=splined_monitor_ws, IntegrationRangeMin=integration_range[0], IntegrationRangeMax=integration_range[-1], OutputWorkspace=normalised_ws) normalised_ws = mantid.ConvertUnits(InputWorkspace=normalised_ws, Target="TOF", OutputWorkspace=normalised_ws) common.remove_intermediate_workspace(processed_monitor_ws) common.remove_intermediate_workspace(splined_monitor_ws) return normalised_ws
def execute(self, reducer, workspace): """ Trips leading and trailing Nan values from workspace @param reducer: unused @param workspace: the workspace to convert """ result_ws = mtd[workspace] if result_ws.getNumberHistograms() != 1: #Strip zeros is only possible on 1D workspaces return y_vals = result_ws.readY(0) length = len(y_vals) # Find the first non-zero value start = 0 for i in range(0, length): if not self._isNan(y_vals[i]): start = i break # Now find the last non-zero value stop = 0 length -= 1 for j in range(length, 0,-1): if not self._isNan(y_vals[j]): stop = j break # Find the appropriate X values and call CropWorkspace x_vals = result_ws.readX(0) startX = x_vals[start] # Make sure we're inside the bin that we want to crop endX = 1.001*x_vals[stop + 1] api.CropWorkspace(InputWorkspace=workspace, OutputWorkspace=workspace, XMin=startX, XMax=endX)
def PhaseQuad(self, inputs): """ do the phaseQuad algorithm groups data into a single set """ cloned_workspace = mantid.CloneWorkspace( InputWorkspace=inputs["InputWorkspace"], StoreInADS=False) mantid.MaskDetectors(Workspace=cloned_workspace, DetectorList=inputs['MaskedDetectors'], StoreInADS=False) mantid.CropWorkspace(InputWorkspace=cloned_workspace, XMin=inputs['FirstGoodData'], XMax=inputs['LastGoodData'], OutputWorkspace='cropped_workspace_pre_phasequad') self.alg = mantid.AlgorithmManager.create("PhaseQuad") self.alg.initialize() self.alg.setRethrows(True) self.alg.setProperty("InputWorkspace", 'cropped_workspace_pre_phasequad') self.alg.setProperty("PhaseTable", "PhaseTable") self.alg.setProperty("OutputWorkspace", "__phaseQuad__") self.alg.execute() mantid.DeleteWorkspace("cropped_workspace_pre_phasequad") self.alg = None
def crop_range(cls, ws, rng): """ Given a range of workspace indexes to keep (rng), Crop the workspace such that these are kept. Arguments: ws : Workspace to crop spectrum from rng : Tuple of range tuples. syntax may be (start, stop) or ((start0, stop0), (start1, stop1), ...) returns a new copy of the workspace with spectra cropped out. """ _in_rng = msi.CloneWorkspace(ws) if not isinstance(rng, tuple): raise ValueError("Elements must be tuples.") def is_actual_range(rng): return len(rng) == 2 and isinstance(rng[0], int) and isinstance( rng[1], int) if is_actual_range(rng): start, stop = rng[0], rng[1] _in_rng = msi.CropWorkspace(InputWorkspace=_in_rng, StartWorkspaceIndex=start, EndWorkspaceIndex=stop) else: for subrng in rng: _in_rng = ConvertToWavelength.crop_range(ws, subrng) return _in_rng
def _focus_mode_trans(output_file_paths, attenuation_filepath, calibrated_spectra): summed_ws = mantid.MergeRuns(InputWorkspaces=calibrated_spectra[:9]) xList = summed_ws.readX(0) summed_ws = mantid.CropWorkspace(InputWorkspace=summed_ws, XMin=xList[1], Xmax=xList[-2]) summed_ws = mantid.Scale(InputWorkspace=summed_ws, Factor=0.111111111111111) if attenuation_filepath: summed_ws = _attenuate_workspace( output_file_paths=output_file_paths, attenuated_ws=summed_ws, attenuation_filepath=attenuation_filepath) summed_ws = mantid.ConvertUnits(InputWorkspace=summed_ws, Target="TOF") mantid.SaveGSS(InputWorkspace=summed_ws, Filename=output_file_paths["gss_filename"], Append=False, Bank=1) mantid.SaveFocusedXYE(InputWorkspace=summed_ws, Filename=output_file_paths["tof_xye_filename"], Append=False, IncludeHeader=False) summed_ws = mantid.ConvertUnits(InputWorkspace=summed_ws, Target="dSpacing") # Rename to user friendly name: summed_ws_name = output_file_paths["output_name"] + "_mods1-9" summed_ws = mantid.RenameWorkspace(InputWorkspace=summed_ws, OutputWorkspace=summed_ws_name) mantid.SaveFocusedXYE(InputWorkspace=summed_ws, Filename=output_file_paths["dspacing_xye_filename"], Append=False, IncludeHeader=False) mantid.SaveNexus(InputWorkspace=summed_ws, Filename=output_file_paths["nxs_filename"], Append=False) output_list = [summed_ws] for i in range(0, 9): workspace_name = output_file_paths["output_name"] + "_mod" + str(i + 1) to_save = mantid.ConvertUnits(InputWorkspace=calibrated_spectra[i], Target="dSpacing", OutputWorkspace=workspace_name) output_list.append(to_save) mantid.SaveNexus(Filename=output_file_paths["nxs_filename"], InputWorkspace=to_save, Append=True) return output_list
def calc_calibration_without_vanadium(focused_ws, index, instrument): focus_spectrum = mantid.ExtractSingleSpectrum(InputWorkspace=focused_ws, WorkspaceIndex=index) focus_spectrum = mantid.ConvertUnits(InputWorkspace=focus_spectrum, Target="TOF") focus_spectrum = mantid.Rebin(InputWorkspace=focus_spectrum, Params=instrument.tof_binning) focus_calibrated = mantid.CropWorkspace(InputWorkspace=focus_spectrum, XMin=0.1) return focus_calibrated
def split_to_single_bank(self, gss_ws_name): """ Split a multiple-bank GSAS workspace to a set of single-spectrum MatrixWorkspace Parameters ---------- gss_ws_name Returns ------- Name of grouped workspace and list """ # check assert isinstance(gss_ws_name, str) assert AnalysisDataService.doesExist(gss_ws_name) # get workspace gss_ws = AnalysisDataService.retrieve(gss_ws_name) ws_list = list() angle_list = list() if gss_ws.getNumberHistograms() == 1: # input is already a single-spectrum workspace ws_list.append(gss_ws_name) else: num_spec = gss_ws.getNumberHistograms() for i_ws in range(num_spec): # split this one to a single workspace out_ws_name = '%s_bank%d' % (gss_ws_name, i_ws + 1) # also can use ExtractSpectra() simpleapi.CropWorkspace(InputWorkspace=gss_ws_name, OutputWorkspace=out_ws_name, StartWorkspaceIndex=i_ws, EndWorkspaceIndex=i_ws) assert AnalysisDataService.doesExist(out_ws_name) ws_list.append(out_ws_name) # END-FOR # END-IF # calculate bank angles for ws_name in ws_list: bank_angle = calculate_bank_angle(ws_name) angle_list.append(bank_angle) # group all the workspace ws_group_name = gss_ws_name + '_group' simpleapi.GroupWorkspaces(InputWorkspaces=ws_list, OutputWorkspace=ws_group_name) self._braggDataDict[ws_group_name] = (gss_ws_name, ws_list) return ws_group_name, ws_list, angle_list
def load_and_crop_data(runs, spectra, ip_file, diff_mode='single', fit_mode='spectra', rebin_params=None): """ @param runs The string giving the runs to load @param spectra A list of spectra to load @param ip_file A string denoting the IP file @param diff_mode Either 'double' or 'single' @param fit_mode If bank then the loading is changed to summing each bank to a separate spectrum @param rebin_params Rebin parameter string to rebin data by (no rebin if None) """ instrument = VESUVIO() load_banks = (fit_mode == 'bank') output_name = _create_tof_workspace_suffix(runs, spectra) if load_banks: sum_spectra = True if spectra == "forward": bank_ranges = instrument.forward_banks elif spectra == "backward": bank_ranges = instrument.backward_banks else: raise ValueError("Fitting by bank requires selecting either 'forward' or 'backward' " "for the spectra to load") bank_ranges = ["{0}-{1}".format(x, y) for x, y in bank_ranges] spectra = ";".join(bank_ranges) else: sum_spectra = False if spectra == "forward": spectra = "{0}-{1}".format(*instrument.forward_spectra) elif spectra == "backward": spectra = "{0}-{1}".format(*instrument.backward_spectra) if diff_mode == "double": diff_mode = "DoubleDifference" else: diff_mode = "SingleDifference" kwargs = {"Filename": runs, "Mode": diff_mode, "InstrumentParFile": ip_file, "SpectrumList": spectra, "SumSpectra": sum_spectra, "OutputWorkspace": output_name} full_range = ms.LoadVesuvio(**kwargs) tof_data = ms.CropWorkspace(InputWorkspace=full_range, XMin=instrument.tof_range[0], XMax=instrument.tof_range[1], OutputWorkspace=output_name) if rebin_params is not None: tof_data = ms.Rebin(InputWorkspace=tof_data, OutputWorkspace=output_name, Params=rebin_params) return tof_data
def PyExec(self): """ Main execution body """ inputws = self.getProperty("InputWorkspace").value run = inputws.getRun() channel_width = float(run.getLogData('channel_width').value) full_channels = float(run.getLogData('full_channels').value) tof1 = float(run.getLogData('TOF1').value) outputws = api.CropWorkspace(inputws, XMin=0., XMax=full_channels*channel_width + tof1, StoreInADS=False) self.setProperty("OutputWorkspace", outputws)
def save_gda(d_spacing_group, output_path, gsas_calib_filename, grouping_scheme,raise_warning): if raise_warning: raise RuntimeWarning("Could not save gda file, as GSAS calibration file was not found. " "It should be present at " + gsas_calib_filename) return input_ws = mantid.CropWorkspace(InputWorkspace=d_spacing_group, XMax=10, StoreInADS=False) mantid.SaveGDA(InputWorkspace=input_ws, GSASParamFile=gsas_calib_filename, GroupingScheme=grouping_scheme, OutputFilename=output_path)
def Norm_data(rnum, cycle): # Load and normalize SX data mantid.LoadRaw( Filename='/archive/Instruments$/NDXWISH/Instrument/data/cycle_' + cycle + '/WISH000' + str(rnum) + '.raw', OutputWorkspace='WISH000' + str(rnum), LoadMonitors='Separate') # ConvertToEventWorkspace(InputWorkspace='WISH000'+str(rnum), OutputWorkspace='WISH000'+str(rnum)) mantid.CropWorkspace(InputWorkspace='WISH000' + str(rnum), OutputWorkspace='WISH000' + str(i), XMin=6000, XMax=99000) mantid.ConvertUnits(InputWorkspace='WISH000' + str(rnum), OutputWorkspace='WISH000' + str(rnum), Target='Wavelength') mantid.NormaliseByCurrent(InputWorkspace='WISH000' + str(rnum), OutputWorkspace='WISH000' + str(rnum)) # normalize By vanadium PredictPeaks mantid.CropWorkspace(InputWorkspace='WISH000' + str(rnum), OutputWorkspace='WISH000' + str(rnum), XMin=0.75, XMax=9.3) mantid.RebinToWorkspace(WorkspaceToRebin='Vana_smoot1', WorkspaceToMatch='WISH000' + str(rnum), OutputWorkspace='Vana_smoot1') mantid.Divide(LHSWorkspace='WISH000' + str(rnum), RHSWorkspace='Vana_smoot1', OutputWorkspace='WISH000' + str(rnum)) # remove spike in the data above 1e15 and -1e15 mantid.ReplaceSpecialValues(InputWorkspace='WISH000' + str(rnum), OutputWorkspace='WISH000' + str(rnum), NaNValue=0, InfinityValue=0, BigNumberThreshold=1e15, SmallNumberThreshold=-1e15) # Convert to Diffraction MD and Lorentz Correction mantid.ConvertToDiffractionMDWorkspace( InputWorkspace='WISH000' + str(rnum), OutputWorkspace='WISH000' + str(rnum) + '_MD', LorentzCorrection=True)
def _crop_spline_to_percent_of_max(spline, input_ws, output_workspace): spline_spectrum = spline.readY(0) y_val = numpy.amax(spline_spectrum) y_val = y_val / 100 x_list = input_ws.readX(0) small_spline_indecies = numpy.nonzero(spline_spectrum > y_val)[0] x_max = x_list[small_spline_indecies[-1]] x_min = x_list[small_spline_indecies[0]] output = mantid.CropWorkspace(inputWorkspace=input_ws, XMin=x_min, XMax=x_max, OutputWorkspace=output_workspace) return output
def extract_ws_spectra(ws_to_split): """ Extracts individual spectra from the workspace into a list of workspaces. Each workspace will contain one of the spectra from the workspace and will have the form of "<ws_name>_<spectrum number>". :param ws_to_split: The workspace to split into individual workspaces :return: A list of extracted workspaces - one per spectra in the original workspace """ num_spectra = ws_to_split.getNumberHistograms() spectra_bank_list = [] for i in range(0, num_spectra): output_name = ws_to_split.getName() + "-" + str(i + 1) # Have to use crop workspace as extract single spectrum struggles with the variable bin widths spectra_bank_list.append(mantid.CropWorkspace(InputWorkspace=ws_to_split, OutputWorkspace=output_name, StartWorkspaceIndex=i, EndWorkspaceIndex=i)) return spectra_bank_list
def PyExec(self): import mantid.simpleapi as ms self.log().warning( 'FindReflectometryLines algorithm version 1 has been deprecated and will be removed in a future release.' ) in_ws = self.getPropertyValue("InputWorkspace") min_wavelength = self.getPropertyValue("StartWavelength") keep_workspaces = self.getPropertyValue("KeepIntermediateWorkspaces") # Crop off lower wavelengths where the signal is also lower. cropped_ws = ms.CropWorkspace(InputWorkspace=in_ws, XMin=float(min_wavelength)) # Integrate over the higher wavelengths after cropping. summed_ws = ms.Integration(InputWorkspace=cropped_ws) # Loop through each histogram, and fetch out each intensity value from the single bin to generate a list of all values. n_histograms = summed_ws.getNumberHistograms() y_data = np.empty([n_histograms]) for i in range(0, n_histograms): intensity = summed_ws.readY(i)[0] y_data[i] = intensity #Remove the background y_data = self.__remove_background(y_data) #Find the peaks peak_index_list = self.__find_peak_spectrum_numbers(y_data, summed_ws) #Reverse the order so that it goes from high spec number to low spec number peak_index_list.reverse() n_peaks_found = len(peak_index_list) output_ws = WorkspaceFactory.createTable("TableWorkspace") output_ws.addColumn("int", "Reflected Spectrum Number") if n_peaks_found > 2: raise PeakFindingException("Found more than two peaks.") elif n_peaks_found == 0: raise PeakFindingException("No peaks found") elif n_peaks_found == 1: output_ws.addRow(peak_index_list) elif n_peaks_found == 2: output_ws.addColumn("int", "Transmission Spectrum Number") output_ws.addRow(peak_index_list) if int(keep_workspaces) == 0: ms.DeleteWorkspace(Workspace=cropped_ws) ms.DeleteWorkspace(Workspace=summed_ws) self.setProperty("OutputWorkspace", output_ws)
def read_event_nexus(self, number, output, panel): simple.RenameWorkspace("{}_monitors".format(output), "w{}_monitors".format(number)) simple.Rebin(InputWorkspace=output, OutputWorkspace=output, Params='6000,-0.00063,110000') simple.ConvertToMatrixWorkspace(output, output) spectra_min, spectra_max = self.return_panel.get(panel) simple.CropWorkspace(InputWorkspace=output, OutputWorkspace=output, StartWorkspaceIndex=spectra_min - 6, EndWorkspaceIndex=spectra_max - 6) simple.MaskBins(InputWorkspace=output, OutputWorkspace=output, XMin=99900, XMax=106000)
def _crop_spline_to_percent_of_max(spline, input_ws, output_workspace, min_value, max_value): spline_spectrum = spline.readY(0) if not spline_spectrum.any(): return mantid.CloneWorkspace(inputWorkspace=input_ws, OutputWorkspace=output_workspace) x_list = input_ws.readX(0) min_index = x_list.searchsorted(min_value) max_index = x_list.searchsorted(max_value) sliced_spline_spectrum = spline_spectrum[min_index:max_index:1] y_val = numpy.amax(sliced_spline_spectrum) y_val = y_val / 100 small_spline_indecies = numpy.nonzero(spline_spectrum > y_val)[0] x_max = x_list[small_spline_indecies[-1]] x_min = x_list[small_spline_indecies[0]] output = mantid.CropWorkspace(inputWorkspace=input_ws, XMin=x_min, XMax=x_max, OutputWorkspace=output_workspace) return output
def _crop_single_ws_in_tof(ws_to_rebin, x_max, x_min): """ Implementation of cropping the single workspace in TOF. First converts to TOF, crops then converts back to the original unit. :param ws_to_rebin: The workspace to crop :param x_max: (Optional) The minimum TOF values to crop to :param x_min: (Optional) The maximum TOF values to crop to :return: The cropped workspace with the original units """ previous_units = ws_to_rebin.getAxis(0).getUnit().unitID() if previous_units != "TOF": ws_to_rebin = mantid.ConvertUnits(InputWorkspace=ws_to_rebin, Target="TOF", OutputWorkspace=ws_to_rebin) cropped_ws = mantid.CropWorkspace(InputWorkspace=ws_to_rebin, OutputWorkspace=ws_to_rebin, XMin=x_min, XMax=x_max) if previous_units != "TOF": cropped_ws = mantid.ConvertUnits(InputWorkspace=cropped_ws, Target=previous_units, OutputWorkspace=cropped_ws) return cropped_ws
def normalise_ws_current(ws_to_correct, monitor_ws, spline_coeff, lambda_values, integration_range): processed_monitor_ws = mantid.ConvertUnits(InputWorkspace=monitor_ws, Target="Wavelength") processed_monitor_ws = mantid.CropWorkspace( InputWorkspace=processed_monitor_ws, XMin=lambda_values[0], XMax=lambda_values[-1]) # TODO move these masks to the adv. config file ex_regions = numpy.zeros((2, 4)) ex_regions[:, 0] = [3.45, 3.7] ex_regions[:, 1] = [2.96, 3.2] ex_regions[:, 2] = [2.1, 2.26] ex_regions[:, 3] = [1.73, 1.98] for reg in range(0, 4): processed_monitor_ws = mantid.MaskBins( InputWorkspace=processed_monitor_ws, XMin=ex_regions[0, reg], XMax=ex_regions[1, reg]) splined_monitor_ws = mantid.SplineBackground( InputWorkspace=processed_monitor_ws, WorkspaceIndex=0, NCoeff=spline_coeff) normalised_ws = mantid.ConvertUnits(InputWorkspace=ws_to_correct, Target="Wavelength", OutputWorkspace=ws_to_correct) normalised_ws = mantid.NormaliseToMonitor( InputWorkspace=normalised_ws, MonitorWorkspace=splined_monitor_ws, IntegrationRangeMin=integration_range[0], IntegrationRangeMax=integration_range[-1], OutputWorkspace=normalised_ws) normalised_ws = mantid.ConvertUnits(InputWorkspace=normalised_ws, Target="TOF", OutputWorkspace=normalised_ws) common.remove_intermediate_workspace(processed_monitor_ws) common.remove_intermediate_workspace(splined_monitor_ws) return normalised_ws
def make_workspace(coord: str, emode: str = 'Elastic', efixed: Optional[sc.Variable] = None) -> 'sapi.Workspace': ws = sapi.CreateSampleWorkspace(XMin=1000, NumBanks=1, StoreInADS=False) # Crop out spectra index 0 as has two_theta=0, gives inf d-spacing ws = sapi.CropWorkspace(ws, StartWorkspaceIndex=1, StoreInADS=False) ws = sapi.ConvertUnits(InputWorkspace=ws, Target=mantid_coord(coord), EMode=emode, EFixed=efixed.value if efixed is not None else None, StoreInADS=False) # start in origin units ws.mutableRun().addProperty( 'deltaE-mode', kernel.StringPropertyWithValue('deltaE-mode', emode), '', True) if efixed is not None: ws.mutableRun().addProperty( 'Ei', kernel.FloatPropertyWithValue('Ei', efixed.value), str(efixed.unit), False) return ws
def focus_onepanel(self, work, focus, panel): cal = "WISH_diff{}" if cal.format("_cal") not in simple.mtd: simple.LoadDiffCal(filename=self.get_cal(), InstrumentName="WISH", WorkspaceName=cal.format("")) simple.AlignDetectors(InputWorkspace=work, OutputWorkspace=work, CalibrationWorkspace=cal.format("_cal")) simple.DiffractionFocussing(InputWorkspace=work, OutputWorkspace=focus, GroupingWorkspace=cal.format("_group")) if self.deleteWorkspace: simple.DeleteWorkspace(work) if panel == 5 or panel == 6: simple.CropWorkspace(InputWorkspace=focus, OutputWorkspace=focus, XMin=0.3) return focus
def _sum_groups_of_three_ws(calibrated_spectra, output_file_names): output_list = [] for i in range(3): ws_name = output_file_names["output_name"] + "_mods{}-{}".format( i * 3 + 1, (i + 1) * 3) summed_spectra = mantid.MergeRuns( InputWorkspaces=calibrated_spectra[i * 3:(i + 1) * 3], OutputWorkspace=ws_name) xList = summed_spectra.readX(0) summed_spectra = mantid.CropWorkspace(InputWorkspace=summed_spectra, XMin=xList[1], Xmax=xList[-2]) scaled = mantid.Scale(InputWorkspace=summed_spectra, Factor=1. / 3, OutputWorkspace=ws_name) output_list.append(scaled) return output_list
def _run_get_monitor(self, run_number, input_dir, spline_terms): load_monitor_ws = common._load_monitor(run_number, input_dir=input_dir, instrument=self) get_monitor_ws = mantid.ConvertUnits(InputWorkspace=load_monitor_ws, Target="Wavelength") common.remove_intermediate_workspace(load_monitor_ws) lmin, lmax = self._get_lambda_range() get_monitor_ws = mantid.CropWorkspace(InputWorkspace=get_monitor_ws, XMin=lmin, XMax=lmax) ex_regions = numpy.zeros((2, 4)) ex_regions[:, 0] = [3.45, 3.7] ex_regions[:, 1] = [2.96, 3.2] ex_regions[:, 2] = [2.1, 2.26] ex_regions[:, 3] = [1.73, 1.98] # ConvertToDistribution(works) for reg in range(0, 4): get_monitor_ws = mantid.MaskBins(InputWorkspace=get_monitor_ws, XMin=ex_regions[0, reg], XMax=ex_regions[1, reg]) monitor_ws = mantid.SplineBackground(InputWorkspace=get_monitor_ws, WorkspaceIndex=0, NCoeff=spline_terms) common.remove_intermediate_workspace(get_monitor_ws) return monitor_ws
def _apply_vanadium_norm(sample_ws_foc, van_ws_foc): # divide by curves - automatically corrects for solid angle, det efficiency and lambda dep. flux sample_ws_foc = mantid.CropWorkspace(InputWorkspace=sample_ws_foc, OutputWorkspace=sample_ws_foc.name(), XMin=0.45) van_ws_foc_rb = mantid.RebinToWorkspace( WorkspaceToRebin=van_ws_foc, WorkspaceToMatch=sample_ws_foc, OutputWorkspace=VAN_CURVE_REBINNED_NAME) # copy so as not to lose data sample_ws_foc = mantid.Divide(LHSWorkspace=sample_ws_foc, RHSWorkspace=van_ws_foc_rb, OutputWorkspace=sample_ws_foc.name(), AllowDifferentNumberSpectra=False) sample_ws_foc = mantid.ReplaceSpecialValues( InputWorkspace=sample_ws_foc, OutputWorkspace=sample_ws_foc.name(), NaNValue=0, NaNError=0.0, InfinityValue=0, InfinityError=0.0) return sample_ws_foc
def focus_onepanel(self, work, focus, panel): cal = "WISH_diff{}" if cal.format("_cal") not in simple.mtd: simple.LoadDiffCal(filename=self.get_cal(), InstrumentName="WISH", WorkspaceName=cal.format("")) simple.AlignAndFocusPowder(InputWorkspace=work, OutputWorkspace=focus, GroupingWorkspace=cal.format("_group"), CalibrationWorkspace=cal.format("_cal"), Dspacing=True, params="-0.00063") simple.ConvertUnits(InputWorkspace=focus, OutputWorkspace=focus, Target="dSpacing") if self.deleteWorkspace: simple.DeleteWorkspace(work) if panel == 5 or panel == 6: simple.CropWorkspace(InputWorkspace=focus, OutputWorkspace=focus, XMin=0.3) return focus
def calc_calibration_with_vanadium(focused_ws, index, vanadium_ws, instrument): data_ws = mantid.ExtractSingleSpectrum(InputWorkspace=focused_ws, WorkspaceIndex=index) data_ws = mantid.ConvertUnits(InputWorkspace=data_ws, Target="TOF") data_ws = mantid.Rebin(InputWorkspace=data_ws, Params=instrument._get_focus_tof_binning()) data_processed = "van_processed" + str( index) # Workaround for Mantid overwriting the WS in a loop mantid.Divide(LHSWorkspace=data_ws, RHSWorkspace=vanadium_ws, OutputWorkspace=data_processed) mantid.CropWorkspace(InputWorkspace=data_processed, XMin=0.1, OutputWorkspace=data_processed) mantid.Scale(InputWorkspace=data_processed, Factor=10, OutputWorkspace=data_processed) remove_intermediate_workspace(data_ws) return data_processed
def PyExec(self): workflow_prog = Progress(self, start=0.0, end=0.3, nreports=4) workflow_prog.report('Setting up algorithm') self._setup() input_ws = mtd[self._sample] min_spectrum_index = input_ws.getIndexFromSpectrumNumber( int(self._spectra_range[0])) max_spectrum_index = input_ws.getIndexFromSpectrumNumber( int(self._spectra_range[1])) # Crop to the required spectra range workflow_prog.report('Cropping Workspace') cropped_input = ms.CropWorkspace( InputWorkspace=input_ws, OutputWorkspace='__symm', StartWorkspaceIndex=min_spectrum_index, EndWorkspaceIndex=max_spectrum_index) # Find the smallest data array in the first spectra len_x = len(cropped_input.readX(0)) len_y = len(cropped_input.readY(0)) len_e = len(cropped_input.readE(0)) sample_array_len = min(len_x, len_y, len_e) sample_x = cropped_input.readX(0) # Get slice bounds of array try: workflow_prog.report('Calculating array points') self._calculate_array_points(sample_x, sample_array_len) except Exception as exc: raise RuntimeError( 'Failed to calculate array slice boundaries: %s' % exc.message) max_sample_index = sample_array_len - 1 centre_range_len = self._positive_min_index + self._negative_min_index positive_diff_range_len = max_sample_index - self._positive_max_index output_cut_index = max_sample_index - self._positive_min_index - positive_diff_range_len - 1 new_array_len = 2 * max_sample_index - centre_range_len - 2 * positive_diff_range_len - 1 logger.information('Sample array length = %d' % sample_array_len) logger.information( 'Positive X min at i=%d, x=%f' % (self._positive_min_index, sample_x[self._positive_min_index])) logger.information( 'Negative X min at i=%d, x=%f' % (self._negative_min_index, sample_x[self._negative_min_index])) logger.information( 'Positive X max at i=%d, x=%f' % (self._positive_max_index, sample_x[self._positive_max_index])) logger.information('New array length = %d' % new_array_len) logger.information('Output array LR split index = %d' % output_cut_index) # Create an empty workspace with enough storage for the new data workflow_prog.report('Creating OutputWorkspace') out_ws = WorkspaceFactory.Instance().create( cropped_input, cropped_input.getNumberHistograms(), int(new_array_len), int(new_array_len)) # For each spectrum copy positive values to the negative pop_prog = Progress(self, start=0.3, end=0.95, nreports=out_ws.getNumberHistograms()) for idx in range(out_ws.getNumberHistograms()): pop_prog.report('Populating data in workspace %i' % idx) # Strip any additional array cells x_in = cropped_input.readX(idx)[:sample_array_len] y_in = cropped_input.readY(idx)[:sample_array_len] e_in = cropped_input.readE(idx)[:sample_array_len] # Get some zeroed data to overwrite with copies from sample x_out = np.zeros(new_array_len) y_out = np.zeros(new_array_len) e_out = np.zeros(new_array_len) # Left hand side (reflected) x_out[:output_cut_index] = -x_in[self._positive_max_index - 1:self._positive_min_index:-1] y_out[:output_cut_index] = y_in[self._positive_max_index - 1:self._positive_min_index:-1] e_out[:output_cut_index] = e_in[self._positive_max_index - 1:self._positive_min_index:-1] # Right hand side (copied) x_out[output_cut_index:] = x_in[self._negative_min_index:self. _positive_max_index] y_out[output_cut_index:] = y_in[self._negative_min_index:self. _positive_max_index] e_out[output_cut_index:] = e_in[self._negative_min_index:self. _positive_max_index] # Set output spectrum data out_ws.setX(idx, x_out) out_ws.setY(idx, y_out) out_ws.setE(idx, e_out) logger.information('Symmetrise spectrum %d' % idx) end_prog = Progress(self, start=0.95, end=1.0, nreports=3) end_prog.report('Deleting temp workspaces') ms.DeleteWorkspace(cropped_input) if self._props_output_workspace != '': end_prog.report('Generating property table') self._generate_props_table() self.setProperty('OutputWorkspace', out_ws) end_prog.report('Algorithm Complete')
def _load_and_sum_runs(self, spectra): """Load the input set of runs & sum them if there is more than one. @param spectra :: The list of spectra to load @returns a tuple of length 2 containing (main_detector_ws, monitor_ws) """ isis = config.getFacility("ISIS") inst_prefix = isis.instrument("VESUVIO").shortName() runs = self._get_runs() self.summed_ws, self.summed_mon = "__loadraw_evs", "__loadraw_evs_monitors" for index, run in enumerate(runs): run = inst_prefix + str(run) self._raise_error_period_scatter(run, self._back_scattering) if index == 0: out_name, out_mon = SUMMED_WS, SUMMED_MON else: out_name, out_mon = SUMMED_WS + 'tmp', SUMMED_MON + 'tmp' # Load data raw_filepath = FileFinder.findRuns(run)[0] ms.LoadRaw(Filename=raw_filepath, SpectrumList=spectra, OutputWorkspace=out_name, LoadMonitors='Exclude', EnableLogging=_LOGGING_) ms.LoadRaw(Filename=raw_filepath, SpectrumList=self._mon_spectra, OutputWorkspace=out_mon, EnableLogging=_LOGGING_) # Sum if index > 0: ms.Plus(LHSWorkspace=SUMMED_WS, RHSWorkspace=out_name, OutputWorkspace=SUMMED_WS, EnableLogging=_LOGGING_) ms.Plus(LHSWorkspace=SUMMED_MON, RHSWorkspace=out_mon, OutputWorkspace=SUMMED_MON, EnableLogging=_LOGGING_) ms.DeleteWorkspace(out_name, EnableLogging=_LOGGING_) ms.DeleteWorkspace(out_mon, EnableLogging=_LOGGING_) # Check to see if extra data needs to be loaded to normalise in data x_max = self._tof_max if self._foil_out_norm_end > self._tof_max: x_max = self._foil_out_norm_end self._crop_required = True ms.CropWorkspace(Inputworkspace= SUMMED_WS, OutputWorkspace=SUMMED_WS, XMax=x_max, EnableLogging=_LOGGING_) ms.CropWorkspace(Inputworkspace= SUMMED_MON, OutputWorkspace=SUMMED_MON, XMax=self._mon_tof_max, EnableLogging=_LOGGING_) summed_data, summed_mon = mtd[SUMMED_WS], mtd[SUMMED_MON] self._load_diff_mode_parameters(summed_data) return summed_data, summed_mon