def _resample_calibration( self, current_workspace, mask_name, x_min, x_max, ): """Perform resample on calibration""" cal = self.getProperty("CalibrationWorkspace").value target = self.getProperty("Target").value e_fixed = self.getProperty("EFixed").value number_bins = self.getProperty("NumberBins").value _ws_cal = ExtractUnmaskedSpectra( InputWorkspace=cal, MaskWorkspace=mask_name, EnableLogging=False ) if isinstance(mtd["_ws_cal"], IEventWorkspace): _ws_cal = Integration(InputWorkspace=_ws_cal, EnableLogging=False) CopyInstrumentParameters( InputWorkspace=current_workspace, OutputWorkspace=_ws_cal, EnableLogging=False, ) _ws_cal = ConvertSpectrumAxis( InputWorkspace=_ws_cal, Target=target, EFixed=e_fixed, EnableLogging=False, ) _ws_cal = Transpose(InputWorkspace=_ws_cal, EnableLogging=False) return ResampleX( InputWorkspace=_ws_cal, XMin=x_min, XMax=x_max, NumberBins=number_bins, EnableLogging=False, )
def GetIncidentSpectrumFromMonitor(Filename, OutputWorkspace="IncidentWorkspace", IncidentIndex=0, TransmissionIndex=1, Binning=".1,6000,2.9", BinType="ResampleX"): # ------------------------------------------------- # Joerg's read_bm.pro code # Loop workspaces to get each incident spectrum monitor = 'monitor' LoadNexusMonitors(Filename=Filename, OutputWorkspace=monitor) ConvertUnits(InputWorkspace=monitor, OutputWorkspace=monitor, Target='Wavelength', EMode='Elastic') lambdaMin, lambdaBinning, lambdaMax = [ float(x) for x in Binning.split(',') ] for x in [lambdaMin, lambdaBinning, lambdaMax]: print(x, type(x)) if BinType == 'ResampleX': ResampleX( InputWorkspace=monitor, OutputWorkspace=monitor, XMin=[lambdaMin], # TODO change ResampleX XMax=[lambdaMax], NumberBins=abs(int(lambdaBinning)), LogBinning=(int(lambdaBinning) < 0), PreserveEvents=True) elif BinType == 'Rebin': Rebin(InputWorkspace=monitor, OutputWorkspace=monitor, Params=[lambdaMin, lambdaBinning, lambdaMax], PreserveEvents=True) ConvertToPointData(InputWorkspace=monitor, OutputWorkspace=monitor) lam = mtd[monitor].readX(IncidentIndex) # wavelength in A bm = mtd[monitor].readY(IncidentIndex) # neutron counts / microsecond p = 0.000794807 # Pressure thickness = .1 # 1 mm = .1 cm abs_xs_3He = 5333.0 # barns for lambda == 1.798 A p_to_rho = 2.43e-5 # pressure to rho (atoms/angstroms^3) # p is set to give efficiency of 1.03 10^-5 at 1.8 A e0 = abs_xs_3He * lam / 1.798 * p_to_rho * p * thickness print('Efficiency:', 1. - np.exp(-e0)) bmeff = bm / (1. - np.exp(-e0)) # neutron counts / microsecond print(bmeff) # bmeff = bmeff / constants.micro # neutron counts / second CreateWorkspace(DataX=lam, DataY=bmeff, OutputWorkspace=OutputWorkspace, UnitX='Wavelength') mtd[OutputWorkspace].setYUnit('Counts') return mtd[OutputWorkspace]
def convert_to_2theta(ws_name, num_bins=1000): """ """ # duplicate for vanadium vanadium = CloneWorkspace(InputWorkspace=ws_name, OutputWorkspace='vanadium') # transfer to 2theta for data ConvertSpectrumAxis(InputWorkspace=ws_name, OutputWorkspace=ws_name, Target='Theta') Transpose(InputWorkspace=ws_name, OutputWorkspace=ws_name) ResampleX(InputWorkspace=ws_name, OutputWorkspace=ws_name, NumberBins=num_bins, PreserveEvents=False) # vanadium: set to 1 for now time_van_start = time.time() for iws in range(vanadium.getNumberHistograms()): vanadium.dataY(iws)[0] = 1. time_van_stop = time.time() ConvertSpectrumAxis(InputWorkspace='vanadium', OutputWorkspace='vanadium', Target='Theta') Transpose(InputWorkspace='vanadium', OutputWorkspace='vanadium') ResampleX(InputWorkspace='vanadium', OutputWorkspace='vanadium', NumberBins=num_bins, PreserveEvents=False) norm_ws_name = ws_name + '_normalized' Divide(LHSWorkspace=ws_name, RHSWorkspace='vanadium', OutputWorkspace=norm_ws_name) print('Create vanadium workspace : {} seconds'.format(time_van_stop - time_van_start)) return norm_ws_name
def _to_spectrum_axis_resample(self, workspace_in, workspace_out, mask, instrument_donor, x_min, x_max): # common part of converting axis self._to_spectrum_axis(workspace_in, workspace_out, mask, instrument_donor) # rebin the data number_bins = self.getProperty("NumberBins").value return ResampleX( InputWorkspace=workspace_out, OutputWorkspace=workspace_out, XMin=x_min, XMax=x_max, NumberBins=number_bins, EnableLogging=False, )
def reduce_to_2theta(hb2b_builder, pixel_matrix, hb2b_data_ws_name, counts_array, mask_vec, mask_ws_name, num_bins=1000): """ Reduce to 2theta with Masks :param hb2b_builder: :param pixel_matrix: :param hb2b_data_ws_name: :param counts_array: :param mask_vec: :param num_bins: :return: """ # reduce by PyRS if False: pyrs_raw_ws = mtd[pyrs_raw_name] vec_counts = pyrs_raw_ws.readY(0) else: vec_counts = counts_array.astype('float64') # mask if mask_vec is not None: print(mask_vec.dtype) vec_counts.astype('float64') mask_vec.astype('float64') vec_counts *= mask_vec # reduce bin_edgets, histogram = hb2b_builder.reduce_to_2theta_histogram( pixel_matrix, vec_counts, num_bins) # create workspace pyrs_reduced_name = '{}_pyrs_reduced'.format(hb2b_data_ws_name) CreateWorkspace(DataX=bin_edgets, DataY=histogram, NSpec=1, OutputWorkspace=pyrs_reduced_name) SaveNexusProcessed(InputWorkspace=pyrs_reduced_name, Filename='{}.nxs'.format(pyrs_reduced_name), Title='PyRS reduced: {}'.format(hb2b_data_ws_name)) if True: # Mantid # transfer to 2theta for data two_theta_ws_name = '{}_2theta'.format(hb2b_data_ws_name) # Mask if mask_ws_name: # Multiply by masking workspace masked_ws_name = '{}_masked'.format(hb2b_data_ws_name) Multiply(LHSWorkspace=hb2b_data_ws_name, RHSWorkspace=mask_ws_name, OutputWorkspace=masked_ws_name, ClearRHSWorkspace=False) hb2b_data_ws_name = masked_ws_name SaveNexusProcessed(InputWorkspace=hb2b_data_ws_name, Filename='{}_raw.nxs'.format(hb2b_data_ws_name)) # END-IF # # this is for test only! # ConvertSpectrumAxis(InputWorkspace=hb2b_data_ws_name, OutputWorkspace=two_theta_ws_name, Target='Theta', # OrderAxis=False) # Transpose(InputWorkspace=two_theta_ws_name, OutputWorkspace=two_theta_ws_name) # two_theta_ws = mtd[two_theta_ws_name] # for i in range(10): # print ('{}: x = {}, y = {}'.format(i, two_theta_ws.readX(0)[i], two_theta_ws.readY(0)[i])) # for i in range(10010, 10020): # print ('{}: x = {}, y = {}'.format(i, two_theta_ws.readX(0)[i], two_theta_ws.readY(0)[i])) ConvertSpectrumAxis(InputWorkspace=hb2b_data_ws_name, OutputWorkspace=two_theta_ws_name, Target='Theta') Transpose(InputWorkspace=two_theta_ws_name, OutputWorkspace=two_theta_ws_name) # final: mantid_reduced_name = '{}_mtd_reduced'.format(hb2b_data_ws_name) ResampleX(InputWorkspace=two_theta_ws_name, OutputWorkspace=mantid_reduced_name, NumberBins=num_bins, PreserveEvents=False) mantid_ws = mtd[mantid_reduced_name] SaveNexusProcessed( InputWorkspace=mantid_reduced_name, Filename='{}.nxs'.format(mantid_reduced_name), Title='Mantid reduced: {}'.format(hb2b_data_ws_name)) plt.plot(mantid_ws.readX(0), mantid_ws.readY(0), color='blue', mark='o') # END-IF plt.plot(bin_edgets[:-1], histogram, color='red') plt.show() return
def PyExec(self): data = self.getProperty("InputWorkspace").value cal = self.getProperty("CalibrationWorkspace").value bkg = self.getProperty("BackgroundWorkspace").value mask = self.getProperty("MaskWorkspace").value target = self.getProperty("Target").value eFixed = self.getProperty("EFixed").value xMin = self.getProperty("XMin").value xMax = self.getProperty("XMax").value numberBins = self.getProperty("NumberBins").value normaliseBy = self.getProperty("NormaliseBy").value maskAngle = self.getProperty("MaskAngle").value outWS = self.getPropertyValue("OutputWorkspace") data_scale = 1 cal_scale = 1 bkg_scale = 1 if normaliseBy == "Monitor": data_scale = data.run().getProtonCharge() elif normaliseBy == "Time": data_scale = data.run().getLogData('duration').value ExtractMask(data, OutputWorkspace='__mask_tmp', EnableLogging=False) if maskAngle != Property.EMPTY_DBL: MaskAngle(Workspace='__mask_tmp', MinAngle=maskAngle, Angle='Phi', EnableLogging=False) if mask is not None: BinaryOperateMasks(InputWorkspace1='__mask_tmp', InputWorkspace2=mask, OperationType='OR', OutputWorkspace='__mask_tmp', EnableLogging=False) ExtractUnmaskedSpectra(InputWorkspace=data, MaskWorkspace='__mask_tmp', OutputWorkspace='__data_tmp', EnableLogging=False) if isinstance(mtd['__data_tmp'], IEventWorkspace): Integration(InputWorkspace='__data_tmp', OutputWorkspace='__data_tmp', EnableLogging=False) ConvertSpectrumAxis(InputWorkspace='__data_tmp', Target=target, EFixed=eFixed, OutputWorkspace=outWS, EnableLogging=False) Transpose(InputWorkspace=outWS, OutputWorkspace=outWS, EnableLogging=False) ResampleX(InputWorkspace=outWS, OutputWorkspace=outWS, XMin=xMin, XMax=xMax, NumberBins=numberBins, EnableLogging=False) if cal is not None: ExtractUnmaskedSpectra(InputWorkspace=cal, MaskWorkspace='__mask_tmp', OutputWorkspace='__cal_tmp', EnableLogging=False) if isinstance(mtd['__cal_tmp'], IEventWorkspace): Integration(InputWorkspace='__cal_tmp', OutputWorkspace='__cal_tmp', EnableLogging=False) CopyInstrumentParameters(data, '__cal_tmp', EnableLogging=False) ConvertSpectrumAxis(InputWorkspace='__cal_tmp', Target=target, EFixed=eFixed, OutputWorkspace='__cal_tmp', EnableLogging=False) Transpose(InputWorkspace='__cal_tmp', OutputWorkspace='__cal_tmp', EnableLogging=False) ResampleX(InputWorkspace='__cal_tmp', OutputWorkspace='__cal_tmp', XMin=xMin, XMax=xMax, NumberBins=numberBins, EnableLogging=False) Divide(LHSWorkspace=outWS, RHSWorkspace='__cal_tmp', OutputWorkspace=outWS, EnableLogging=False) if normaliseBy == "Monitor": cal_scale = cal.run().getProtonCharge() elif normaliseBy == "Time": cal_scale = cal.run().getLogData('duration').value Scale(InputWorkspace=outWS, OutputWorkspace=outWS, Factor=cal_scale / data_scale, EnableLogging=False) if bkg is not None: ExtractUnmaskedSpectra(InputWorkspace=bkg, MaskWorkspace='__mask_tmp', OutputWorkspace='__bkg_tmp', EnableLogging=False) if isinstance(mtd['__bkg_tmp'], IEventWorkspace): Integration(InputWorkspace='__bkg_tmp', OutputWorkspace='__bkg_tmp', EnableLogging=False) CopyInstrumentParameters(data, '__bkg_tmp', EnableLogging=False) ConvertSpectrumAxis(InputWorkspace='__bkg_tmp', Target=target, EFixed=eFixed, OutputWorkspace='__bkg_tmp', EnableLogging=False) Transpose(InputWorkspace='__bkg_tmp', OutputWorkspace='__bkg_tmp', EnableLogging=False) ResampleX(InputWorkspace='__bkg_tmp', OutputWorkspace='__bkg_tmp', XMin=xMin, XMax=xMax, NumberBins=numberBins, EnableLogging=False) if cal is not None: Divide(LHSWorkspace='__bkg_tmp', RHSWorkspace='__cal_tmp', OutputWorkspace='__bkg_tmp', EnableLogging=False) if normaliseBy == "Monitor": bkg_scale = bkg.run().getProtonCharge() elif normaliseBy == "Time": bkg_scale = bkg.run().getLogData('duration').value Scale(InputWorkspace='__bkg_tmp', OutputWorkspace='__bkg_tmp', Factor=cal_scale / bkg_scale, EnableLogging=False) Scale(InputWorkspace='__bkg_tmp', OutputWorkspace='__bkg_tmp', Factor=self.getProperty('BackgroundScale').value, EnableLogging=False) Minus(LHSWorkspace=outWS, RHSWorkspace='__bkg_tmp', OutputWorkspace=outWS, EnableLogging=False) self.setProperty("OutputWorkspace", outWS) # remove temp workspaces [ DeleteWorkspace(ws, EnableLogging=False) for ws in self.temp_workspace_list if mtd.doesExist(ws) ]
def _resample_background( self, current_background, current_workspace, make_name, x_min, x_max, resmapled_calibration, ): """Perform resample on given background""" cal = self.getProperty("CalibrationWorkspace").value target = self.getProperty("Target").value e_fixed = self.getProperty("EFixed").value number_bins = self.getProperty("NumberBins").value _ws_bkg = ExtractUnmaskedSpectra( InputWorkspace=current_background, MaskWorkspace=make_name, EnableLogging=False, ) if isinstance(mtd["_ws_bkg"], IEventWorkspace): _ws_bkg = Integration(InputWorkspace=_ws_bkg, EnableLogging=False) CopyInstrumentParameters( InputWorkspace=current_workspace, OutputWorkspace=_ws_bkg, EnableLogging=False, ) _ws_bkg = ConvertSpectrumAxis( InputWorkspace=_ws_bkg, Target=target, EFixed=e_fixed, EnableLogging=False, ) _ws_bkg = Transpose(InputWorkspace=_ws_bkg, EnableLogging=False) _ws_bkg_resampled = ResampleX( InputWorkspace=_ws_bkg, XMin=x_min, XMax=x_max, NumberBins=number_bins, EnableLogging=False, ) if cal is not None: _ws_bkg_resampled = Divide( LHSWorkspace=_ws_bkg_resampled, RHSWorkspace=resmapled_calibration, EnableLogging=False, ) _ws_bkg_resampled = Scale( InputWorkspace=_ws_bkg_resampled, Factor=self._get_scale(cal) / self._get_scale(current_background), EnableLogging=False, ) _ws_bkg_resampled = Scale( InputWorkspace=_ws_bkg_resampled, Factor=self.getProperty("BackgroundScale").value, EnableLogging=False, ) return _ws_bkg_resampled
def PyExec(self): data = self.getProperty("InputWorkspace").value # [1~n] bkg = self.getProperty("BackgroundWorkspace").value # [1~n] cal = self.getProperty("CalibrationWorkspace").value # [1] xMin = self.getProperty("XMin").value xMax = self.getProperty("XMax").value numberBins = self.getProperty("NumberBins").value outWS = self.getPropertyValue("OutputWorkspace") # NOTE: # StringArrayProperty cannot be optional, so the background can only be passed in as a string # or a list, which will be manually unpacked here if bkg != "": bkg = [ AnalysisDataService.retrieve(me) for me in map(str.strip, bkg.split(",")) ] # NOTE: # xMin and xMax are initialized as empty numpy.array (np.array([])). _xMin, _xMax = self._locate_global_xlimit() xMin = _xMin if xMin.size == 0 else xMin xMax = _xMax if xMax.size == 0 else xMax # BEGIN_FOR: prcess_spectra for n, _wsn in enumerate(data): _mskn = f"__mask_{n}" # calculated in previous loop _ws = AnalysisDataService.retrieve(_wsn) # resample spectra _ws_resampled = ResampleX( InputWorkspace=f"__ws_{n}", XMin=xMin, XMax=xMax, NumberBins=numberBins, EnableLogging=False, ) # calibration if cal is not None: _ws_cal_resampled = self._resample_calibration(_ws, _mskn, xMin, xMax) _ws_resampled = Divide( LHSWorkspace=_ws_resampled, RHSWorkspace=_ws_cal_resampled, EnableLogging=False, ) else: _ws_cal_resampled = None _ws_resampled = Scale( InputWorkspace=_ws_resampled, Factor=self._get_scale(cal) / self._get_scale(_ws), EnableLogging=False, ) # background if bkg != "": bgn = bkg[n] if isinstance(bkg, list) else bkg _ws_bkg_resampled = self._resample_background( bgn, _ws, _mskn, xMin, xMax, _ws_cal_resampled ) _ws_resampled = Minus( LHSWorkspace=_ws_resampled, RHSWorkspace=_ws_bkg_resampled, EnableLogging=False, ) # conjoin if n < 1: CloneWorkspace( InputWorkspace=_ws_resampled, OutputWorkspace="__ws_conjoined", EnableLogging=False, ) else: ConjoinWorkspaces( InputWorkspace1="__ws_conjoined", InputWorkspace2=_ws_resampled, CheckOverlapping=False, EnableLogging=False, ) # END_FOR: prcess_spectra # Step_3: sum all spectra # ref: https://docs.mantidproject.org/nightly/algorithms/SumSpectra-v1.html if cal is not None: SumSpectra( InputWorkspace="__ws_conjoined", OutputWorkspace=outWS, WeightedSum=True, MultiplyBySpectra=False, EnableLogging=False, ) else: SumSpectra( InputWorkspace="__ws_conjoined", OutputWorkspace=outWS, WeightedSum=True, MultiplyBySpectra=True, EnableLogging=False, ) self.setProperty("OutputWorkspace", outWS) # Step_4: remove temp workspaces [ DeleteWorkspace(ws, EnableLogging=False) for ws in self.temp_workspace_list if mtd.doesExist(ws) ]
def PyExec(self): data = self._expand_groups() bkg = self.getProperty( "BackgroundWorkspace").valueAsStr # same background for all cal = self.getProperty( "CalibrationWorkspace").value # same calibration for all numberBins = self.getProperty("NumberBins").value outWS = self.getPropertyValue("OutputWorkspace") summing = self.getProperty("Sum").value # [Yes or No] # convert all of the input workspaces into spectrum of "target" units (generally angle) data, masks = self._convert_data(data) # determine x-range xMin, xMax = self._locate_global_xlimit(data) # BEGIN_FOR: prcess_spectra for n, (_wsn, _mskn) in enumerate(zip(data, masks)): # resample spectra ResampleX( InputWorkspace=_wsn, OutputWorkspace=_wsn, XMin=xMin, XMax=xMax, NumberBins=numberBins, EnableLogging=False, ) # calibration if cal is not None: _ws_cal_resampled = self._resample_calibration( _wsn, _mskn, xMin, xMax) Divide( LHSWorkspace=_wsn, RHSWorkspace=_ws_cal_resampled, OutputWorkspace=_wsn, EnableLogging=False, ) else: _ws_cal_resampled = None Scale( InputWorkspace=_wsn, OutputWorkspace=_wsn, Factor=self._get_scale(cal) / self._get_scale(_wsn), EnableLogging=False, ) # background if bkg: _ws_bkg_resampled = self._resample_background( bkg, _wsn, _mskn, xMin, xMax, _ws_cal_resampled) Minus( LHSWorkspace=_wsn, RHSWorkspace=_ws_bkg_resampled, OutputWorkspace=_wsn, EnableLogging=False, ) if summing: # conjoin if n < 1: RenameWorkspace( InputWorkspace=_wsn, OutputWorkspace="__ws_conjoined", EnableLogging=False, ) else: # this adds to `InputWorkspace1` ConjoinWorkspaces( InputWorkspace1="__ws_conjoined", InputWorkspace2=_wsn, CheckOverlapping=False, EnableLogging=False, ) # END_FOR: prcess_spectra # Step_3: sum all spectra # ref: https://docs.mantidproject.org/nightly/algorithms/SumSpectra-v1.html if summing: if cal is not None: outWS = SumSpectra( InputWorkspace="__ws_conjoined", OutputWorkspace=outWS, WeightedSum=True, MultiplyBySpectra=not bool(cal), EnableLogging=False, ) else: outWS = SumSpectra( InputWorkspace="__ws_conjoined", OutputWorkspace=outWS, WeightedSum=True, MultiplyBySpectra=True, EnableLogging=False, ) else: if len(data) == 1: outWS = RenameWorkspace(InputWorkspace=data[0], OutputWorkspace=outWS) else: outWS = GroupWorkspaces(InputWorkspaces=data, OutputWorkspace=outWS) self.setProperty("OutputWorkspace", outWS) # Step_4: remove temp workspaces [ DeleteWorkspace(ws, EnableLogging=False) for ws in self.temp_workspace_list if mtd.doesExist(ws) ]