def performOperation(self): lhs_valid, rhs_valid, err_msg = self.validateInputs() if err_msg != str(): return lhs_valid, rhs_valid, err_msg lhs_ws, rhs_ws = self._scale_input_workspaces() try: if self._operation == '+': if self._md_lhs or self._md_rhs: PlusMD(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, OutputWorkspace=self._output_ws) else: Plus(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, OutputWorkspace=self._output_ws) elif self._operation == '-': if self._md_lhs or self._md_rhs: MinusMD(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, OutputWorkspace=self._output_ws) else: Minus(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, OutputWorkspace=self._output_ws) elif self._operation == '*': if self._md_lhs or self._md_rhs: MultiplyMD(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, OutputWorkspace=self._output_ws) else: Multiply(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, OutputWorkspace=self._output_ws) elif self._operation == 'WM': if self._md_lhs or self._md_rhs: WeightedMeanMD(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, OutputWorkspace=self._output_ws) else: WeightedMean(InputWorkspace1=lhs_ws, InputWorkspace2=rhs_ws, OutputWorkspace=self._output_ws) else: if self._md_lhs or self._md_rhs: DivideMD(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, OutputWorkspace=self._output_ws) else: Divide(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, OutputWorkspace=self._output_ws) except (RuntimeError, ValueError) as err: return False, False, str(err) else: self._regularize_output_names(self._output_ws) finally: DeleteWorkspaces(WorkspaceList=[lhs_ws, rhs_ws]) return True, True, ""
def __normalization(self, data, vanadium, load_files): if vanadium: norm_data = ReplicateMD(ShapeWorkspace=data, DataWorkspace=vanadium) norm_data = DivideMD(LHSWorkspace=data, RHSWorkspace=norm_data) elif load_files: norm_data = data else: norm_data = CloneMDWorkspace(data) if self.getProperty("ScaleByMotorStep").value and self.getProperty( "OutputType").value != "Detector": run = data.getExperimentInfo(0).run() scan_log = 'omega' if np.isclose(run.getTimeAveragedStd('phi'), 0.0) else 'phi' scan_axis = run[scan_log].value scan_step = (scan_axis[-1] - scan_axis[0]) / (scan_axis.size - 1) norm_data *= scan_step normaliseBy = self.getProperty("NormaliseBy").value monitors = np.asarray( data.getExperimentInfo(0).run().getProperty('monitor').value) times = np.asarray( data.getExperimentInfo(0).run().getProperty('time').value) if load_files and vanadium: DeleteWorkspace(data) if normaliseBy == "Monitor": scale = monitors elif normaliseBy == "Time": scale = times else: return norm_data if vanadium: if normaliseBy == "Monitor": scale /= vanadium.getExperimentInfo(0).run().getProperty( 'monitor').value[0] elif normaliseBy == "Time": scale /= vanadium.getExperimentInfo(0).run().getProperty( 'time').value[0] norm_data.setSignalArray(norm_data.getSignalArray() / scale) norm_data.setErrorSquaredArray(norm_data.getErrorSquaredArray() / scale**2) return norm_data
def normalize( self, data: IMDHistoWorkspace, norm: IMDHistoWorkspace, normalize_by: str, ) -> IMDHistoWorkspace: """ Normalize the given data with given Va normalization workspace """ # prep norm_replicated = ReplicateMD(ShapeWorkspace=data, DataWorkspace=norm) data = DivideMD(LHSWorkspace=data, RHSWorkspace=norm_replicated) # reduce memory footprint DeleteWorkspace(norm_replicated) # find the scale if normalize_by == 'counts': scale = norm.getSignalArray().mean() self.getLogger().information('scale counts = {}'.format( int(scale))) elif normalize_by == 'monitor': scale = np.array( data.getExperimentInfo(0).run().getProperty( 'monitor_count').value) scale /= norm.getExperimentInfo(0).run().getProperty( 'monitor_count').value[0] self.getLogger().information('scale monitor = {}'.format(scale)) elif normalize_by == 'time': scale = np.array( data.getExperimentInfo(0).run().getProperty('duration').value) scale /= norm.getExperimentInfo(0).run().getProperty( 'duration').value[0] self.getLogger().information('van time = {}'.format(scale)) elif normalize_by == 'none': scale = 1 else: raise RuntimeError( f'Unknown normalization method: {normalize_by}!') # exec data.setSignalArray(data.getSignalArray() / scale) data.setErrorSquaredArray(data.getErrorSquaredArray() / scale**2) # return return data
def _determine_single_crystal_diffraction(self): """ All work related to the determination of the diffraction pattern """ a, b, c = self.getProperty('LatticeSizes').value alpha, beta, gamma = self.getProperty('LatticeAngles').value u = self.getProperty('VectorU').value v = self.getProperty('VectorV').value uproj = self.getProperty('Uproj').value vproj = self.getProperty('Vproj').value wproj = self.getProperty('Wproj').value n_bins = self.getProperty('NBins').value self._n_bins = (n_bins, n_bins, 1) axis0 = '{},0,1,0,1'.format(self.getProperty('PsiAngleLog').value) axis1 = '{},0,1,0,1'.format(self.getProperty('PsiOffset').value) # Options for SetUB independent of run ub_args = dict(a=a, b=b, c=c, alpha=alpha, beta=beta, gamma=gamma, u=u, v=v) min_values = None # Options for algorithm ConvertToMD independent of run convert_to_md_kwargs = dict(QDimensions='Q3D', dEAnalysisMode='Elastic', Q3DFrames='HKL', QConversionScales='HKL', Uproj=uproj, Vproj=vproj, Wproj=wproj) md_norm_scd_kwargs = None # Options for algorithm MDNormSCD # Find solid angle and flux if self._vanadium_files: kwargs = dict(Filename='+'.join(self._vanadium_files), MaskFile=self.getProperty("MaskFile").value, MomentumMin=self._momentum_range[0], MomentumMax=self._momentum_range[1]) _t_solid_angle, _t_int_flux = \ MDNormSCDPreprocessIncoherent(**kwargs) else: _t_solid_angle = self.nominal_solid_angle('_t_solid_angle') _t_int_flux = self.nominal_integrated_flux('_t_int_flux') # Process a sample at a time run_numbers = self._getRuns(self.getProperty("RunNumbers").value, doIndiv=True) run_numbers = list(itertools.chain.from_iterable(run_numbers)) diffraction_reporter = Progress(self, start=0.0, end=1.0, nreports=len(run_numbers)) for i_run, run in enumerate(run_numbers): _t_sample = self._mask_t0_crop(run, '_t_sample') # Set Goniometer and UB matrix SetGoniometer(_t_sample, Axis0=axis0, Axis1=axis1) SetUB(_t_sample, **ub_args) if self._bkg: self._bkg.run().getGoniometer().\ setR(_t_sample.run().getGoniometer().getR()) SetUB(self._bkg, **ub_args) # Determine limits for momentum transfer in HKL space. Needs to be # done only once. We use the first run. if min_values is None: kwargs = dict(QDimensions='Q3D', dEAnalysisMode='Elastic', Q3DFrames='HKL') min_values, max_values = ConvertToMDMinMaxGlobal( _t_sample, **kwargs) convert_to_md_kwargs.update({ 'MinValues': min_values, 'MaxValues': max_values }) # Convert to MD _t_md = ConvertToMD(_t_sample, OutputWorkspace='_t_md', **convert_to_md_kwargs) if self._bkg: _t_bkg_md = ConvertToMD(self._bkg, OutputWorkspace='_t_bkg_md', **convert_to_md_kwargs) # Determine aligned dimensions. Need to be done only once if md_norm_scd_kwargs is None: aligned = list() for i_dim in range(3): kwargs = { 'name': _t_md.getDimension(i_dim).name, 'min': min_values[i_dim], 'max': max_values[i_dim], 'n_bins': self._n_bins[i_dim] } aligned.append( '{name},{min},{max},{n_bins}'.format(**kwargs)) md_norm_scd_kwargs = dict(AlignedDim0=aligned[0], AlignedDim1=aligned[1], AlignedDim2=aligned[2], FluxWorkspace=_t_int_flux, SolidAngleWorkspace=_t_solid_angle, SkipSafetyCheck=True) # Normalize sample by solid angle and integrated flux; # Accumulate runs into the temporary workspaces MDNormSCD(_t_md, OutputWorkspace='_t_data', OutputNormalizationWorkspace='_t_norm', TemporaryDataWorkspace='_t_data' if mtd.doesExist('_t_data') else None, TemporaryNormalizationWorkspace='_t_norm' if mtd.doesExist('_t_norm') else None, **md_norm_scd_kwargs) if self._bkg: MDNormSCD(_t_bkg_md, OutputWorkspace='_t_bkg_data', OutputNormalizationWorkspace='_t_bkg_norm', TemporaryDataWorkspace='_t_bkg_data' if mtd.doesExist('_t_bkg_data') else None, TemporaryNormalizationWorkspace='_t_bkg_norm' if mtd.doesExist('_t_bkg_norm') else None, **md_norm_scd_kwargs) message = 'Processing sample {} of {}'.\ format(i_run+1, len(run_numbers)) diffraction_reporter.report(message) self._temps.workspaces.append('PreprocessedDetectorsWS') # to remove # Iteration over the sample runs is done. # Division by vanadium, subtract background, and rename workspaces name = self.getPropertyValue("OutputWorkspace") _t_data = DivideMD(LHSWorkspace='_t_data', RHSWorkspace='_t_norm') if self._bkg: _t_bkg_data = DivideMD(LHSWorkspace='_t_bkg_data', RHSWorkspace='_t_bkg_norm') _t_scale = CreateSingleValuedWorkspace(DataValue=self._bkg_scale) _t_bkg_data = MultiplyMD(_t_bkg_data, _t_scale) ws = MinusMD(_t_data, _t_bkg_data) RenameWorkspace(_t_data, OutputWorkspace=name + '_dat') RenameWorkspace(_t_bkg_data, OutputWorkspace=name + '_bkg') else: ws = _t_data RenameWorkspace(ws, OutputWorkspace=name) self.setProperty("OutputWorkspace", ws) diffraction_reporter.report(len(run_numbers), 'Done')
def PyExec(self): # remove possible old temp workspaces [ DeleteWorkspace(ws) for ws in self.temp_workspace_list if mtd.doesExist(ws) ] _background = bool(self.getProperty("Background").value) _load_inst = bool(self.getProperty("LoadInstrument").value) _detcal = bool(self.getProperty("DetCal").value) _masking = bool(self.getProperty("MaskFile").value) _outWS_name = self.getPropertyValue("OutputWorkspace") UBList = self._generate_UBList() dim0_min, dim0_max, dim0_bins = self.getProperty('BinningDim0').value dim1_min, dim1_max, dim1_bins = self.getProperty('BinningDim1').value dim2_min, dim2_max, dim2_bins = self.getProperty('BinningDim2').value MinValues = "{},{},{}".format(dim0_min, dim1_min, dim2_min) MaxValues = "{},{},{}".format(dim0_max, dim1_max, dim2_max) AlignedDim0 = ",{},{},{}".format(dim0_min, dim0_max, int(dim0_bins)) AlignedDim1 = ",{},{},{}".format(dim1_min, dim1_max, int(dim1_bins)) AlignedDim2 = ",{},{},{}".format(dim2_min, dim2_max, int(dim2_bins)) LoadNexus(Filename=self.getProperty("SolidAngle").value, OutputWorkspace='__sa') LoadNexus(Filename=self.getProperty("Flux").value, OutputWorkspace='__flux') if _masking: LoadMask(Instrument=mtd['__sa'].getInstrument().getName(), InputFile=self.getProperty("MaskFile").value, OutputWorkspace='__mask') MaskDetectors(Workspace='__sa', MaskedWorkspace='__mask') DeleteWorkspace('__mask') XMin = mtd['__sa'].getXDimension().getMinimum() XMax = mtd['__sa'].getXDimension().getMaximum() if _background: Load(Filename=self.getProperty("Background").value, OutputWorkspace='__bkg', FilterByTofMin=self.getProperty("FilterByTofMin").value, FilterByTofMax=self.getProperty("FilterByTofMax").value) if _load_inst: LoadInstrument( Workspace='__bkg', Filename=self.getProperty("LoadInstrument").value, RewriteSpectraMap=False) if _detcal: LoadIsawDetCal(InputWorkspace='__bkg', Filename=self.getProperty("DetCal").value) MaskDetectors(Workspace='__bkg', MaskedWorkspace='__sa') ConvertUnits(InputWorkspace='__bkg', OutputWorkspace='__bkg', Target='Momentum') CropWorkspace(InputWorkspace='__bkg', OutputWorkspace='__bkg', XMin=XMin, XMax=XMax) progress = Progress( self, 0.0, 1.0, len(UBList) * len(self.getProperty("Filename").value)) for run in self.getProperty("Filename").value: logger.notice("Working on " + run) Load(Filename=run, OutputWorkspace='__run', FilterByTofMin=self.getProperty("FilterByTofMin").value, FilterByTofMax=self.getProperty("FilterByTofMax").value) if _load_inst: LoadInstrument( Workspace='__run', Filename=self.getProperty("LoadInstrument").value, RewriteSpectraMap=False) if _detcal: LoadIsawDetCal(InputWorkspace='__run', Filename=self.getProperty("DetCal").value) MaskDetectors(Workspace='__run', MaskedWorkspace='__sa') ConvertUnits(InputWorkspace='__run', OutputWorkspace='__run', Target='Momentum') CropWorkspace(InputWorkspace='__run', OutputWorkspace='__run', XMin=XMin, XMax=XMax) if self.getProperty('SetGoniometer').value: SetGoniometer( Workspace='__run', Goniometers=self.getProperty('Goniometers').value, Axis0=self.getProperty('Axis0').value, Axis1=self.getProperty('Axis1').value, Axis2=self.getProperty('Axis2').value) # Set background Goniometer to be the same as data if _background: mtd['__bkg'].run().getGoniometer().setR( mtd['__run'].run().getGoniometer().getR()) for ub in UBList: SetUB(Workspace='__run', UB=ub) ConvertToMD(InputWorkspace='__run', OutputWorkspace='__md', QDimensions='Q3D', dEAnalysisMode='Elastic', Q3DFrames='HKL', QConversionScales='HKL', Uproj=self.getProperty('Uproj').value, Vproj=self.getProperty('Vproj').value, Wproj=self.getProperty('wproj').value, MinValues=MinValues, MaxValues=MaxValues) MDNormSCD( InputWorkspace=mtd['__md'], FluxWorkspace='__flux', SolidAngleWorkspace='__sa', OutputWorkspace='__data', SkipSafetyCheck=True, TemporaryDataWorkspace='__data' if mtd.doesExist('__data') else None, OutputNormalizationWorkspace='__norm', TemporaryNormalizationWorkspace='__norm' if mtd.doesExist('__norm') else None, AlignedDim0=mtd['__md'].getDimension(0).name + AlignedDim0, AlignedDim1=mtd['__md'].getDimension(1).name + AlignedDim1, AlignedDim2=mtd['__md'].getDimension(2).name + AlignedDim2) DeleteWorkspace('__md') if _background: SetUB(Workspace='__bkg', UB=ub) ConvertToMD(InputWorkspace='__bkg', OutputWorkspace='__bkg_md', QDimensions='Q3D', dEAnalysisMode='Elastic', Q3DFrames='HKL', QConversionScales='HKL', Uproj=self.getProperty('Uproj').value, Vproj=self.getProperty('Vproj').value, Wproj=self.getProperty('Wproj').value, MinValues=MinValues, MaxValues=MaxValues) MDNormSCD( InputWorkspace='__bkg_md', FluxWorkspace='__flux', SolidAngleWorkspace='__sa', SkipSafetyCheck=True, OutputWorkspace='__bkg_data', TemporaryDataWorkspace='__bkg_data' if mtd.doesExist('__bkg_data') else None, OutputNormalizationWorkspace='__bkg_norm', TemporaryNormalizationWorkspace='__bkg_norm' if mtd.doesExist('__bkg_norm') else None, AlignedDim0=mtd['__bkg_md'].getDimension(0).name + AlignedDim0, AlignedDim1=mtd['__bkg_md'].getDimension(1).name + AlignedDim1, AlignedDim2=mtd['__bkg_md'].getDimension(2).name + AlignedDim2) DeleteWorkspace('__bkg_md') progress.report() DeleteWorkspace('__run') if _background: # outWS = data / norm - bkg_data / bkg_norm * BackgroundScale DivideMD(LHSWorkspace='__data', RHSWorkspace='__norm', OutputWorkspace=_outWS_name + '_normalizedData') DivideMD(LHSWorkspace='__bkg_data', RHSWorkspace='__bkg_norm', OutputWorkspace=_outWS_name + '_normalizedBackground') CreateSingleValuedWorkspace( OutputWorkspace='__scale', DataValue=self.getProperty('BackgroundScale').value) MultiplyMD(LHSWorkspace=_outWS_name + '_normalizedBackground', RHSWorkspace='__scale', OutputWorkspace='__scaled_background') DeleteWorkspace('__scale') MinusMD(LHSWorkspace=_outWS_name + '_normalizedData', RHSWorkspace='__scaled_background', OutputWorkspace=_outWS_name) if self.getProperty('KeepTemporaryWorkspaces').value: RenameWorkspaces(InputWorkspaces=[ '__data', '__norm', '__bkg_data', '__bkg_norm' ], WorkspaceNames=[ _outWS_name + '_data', _outWS_name + '_normalization', _outWS_name + '_background_data', _outWS_name + '_background_normalization' ]) else: # outWS = data / norm DivideMD(LHSWorkspace='__data', RHSWorkspace='__norm', OutputWorkspace=_outWS_name) if self.getProperty('KeepTemporaryWorkspaces').value: RenameWorkspaces(InputWorkspaces=['__data', '__norm'], WorkspaceNames=[ _outWS_name + '_data', _outWS_name + '_normalization' ]) self.setProperty("OutputWorkspace", mtd[_outWS_name]) # remove temp workspaces [ DeleteWorkspace(ws) for ws in self.temp_workspace_list if mtd.doesExist(ws) ]
def PyExec(self): load_van = not self.getProperty("VanadiumFile").isDefault load_files = not self.getProperty("Filename").isDefault has_van = not self.getProperty("VanadiumWorkspace").isDefault or load_van if load_files: datafiles = self.getProperty("Filename").value else: datafiles = list(map(str.strip, self.getProperty("InputWorkspaces").value.split(","))) prog = Progress(self, 0.0, 1.0, len(datafiles) + 1) vanadiumfile = self.getProperty("VanadiumFile").value vanws = self.getProperty("VanadiumWorkspace").value height = self.getProperty("DetectorHeightOffset").value distance = self.getProperty("DetectorDistanceOffset").value method = self.getProperty("OutputAsMDEventWorkspace").value wslist = [] if method: minvals = self.getProperty("MinValues").value maxvals = self.getProperty("MaxValues").value merge = self.getProperty("MergeInputs").value else: bin0 = self.getProperty("BinningDim0").value bin1 = self.getProperty("BinningDim1").value bin2 = self.getProperty("BinningDim2").value out_ws = self.getPropertyValue("OutputWorkspace") out_ws_name = out_ws if load_van: vanws = LoadMD(vanadiumfile, StoreInADS=False) has_multiple = len(datafiles) > 1 for in_file in datafiles: if load_files: scan = LoadMD(in_file, LoadHistory=False, OutputWorkspace="__scan") else: scan = mtd[in_file] # Make sure the workspace has experiment info, otherwise SetGoniometer will add some, causing issues. if scan.getNumExperimentInfo() == 0: raise RuntimeError("No experiment info was found in '{}'".format(in_file)) prog.report() self.log().information("Processing '{}'".format(in_file)) SetGoniometer(Workspace=scan, Axis0='omega,0,1,0,-1', Axis1='chi,0,0,1,-1', Axis2='phi,0,1,0,-1', Average=False) # If processing multiple files, append the base name to the given output name if has_multiple: if load_files: out_ws_name = out_ws + "_" + os.path.basename(in_file).strip(',.nxs') else: out_ws_name = out_ws + "_" + in_file wslist.append(out_ws_name) exp_info = scan.getExperimentInfo(0) self.__move_components(exp_info, height, distance) # Get the wavelength from experiment info if it exists, or fallback on property value wavelength = self.__get_wavelength(exp_info) # set the run number to be the same as scan number, this will be used for peaks if not exp_info.run().hasProperty('run_number') and exp_info.run().hasProperty('scan'): try: exp_info.mutableRun().addProperty('run_number', int(exp_info.run().getProperty('scan').value), True) except ValueError: # scan must not be a int pass # Use ConvertHFIRSCDtoQ (and normalize van), or use ConvertWANDSCtoQ which handles normalization itself if method: if has_van: van_norm = ReplicateMD(ShapeWorkspace=scan, DataWorkspace=vanws, StoreInADS=False) van_norm = DivideMD(LHSWorkspace=scan, RHSWorkspace=van_norm, StoreInADS=False) ConvertHFIRSCDtoMDE(InputWorkspace=van_norm, Wavelength=wavelength, MinValues=minvals, MaxValues=maxvals, OutputWorkspace=out_ws_name) DeleteWorkspace(van_norm) else: ConvertHFIRSCDtoMDE(InputWorkspace=scan, Wavelength=wavelength, MinValues=minvals, MaxValues=maxvals, OutputWorkspace=out_ws_name) else: # Convert to Q space and normalize with from the vanadium if has_van: ConvertWANDSCDtoQ(InputWorkspace=scan, NormalisationWorkspace=vanws, Frame='Q_sample', Wavelength=wavelength, NormaliseBy='Monitor', BinningDim0=bin0, BinningDim1=bin1, BinningDim2=bin2, OutputWorkspace=out_ws_name) else: ConvertWANDSCDtoQ(InputWorkspace=scan, Frame='Q_sample', Wavelength=wavelength, NormaliseBy='Monitor', BinningDim0=bin0, BinningDim1=bin1, BinningDim2=bin2, OutputWorkspace=out_ws_name) if load_files: DeleteWorkspace(scan) if has_multiple: out_ws_name = out_ws if method and merge: MergeMD(InputWorkspaces=wslist, OutputWorkspace=out_ws_name) DeleteWorkspaces(wslist) else: GroupWorkspaces(InputWorkspaces=wslist, OutputWorkspace=out_ws_name) # Don't delete workspaces if they were passed in if load_van: DeleteWorkspace(vanws) self.setProperty("OutputWorkspace", out_ws_name)
'/HFIR/HB2C/IPTS-7776/shared/rwp/PNOe/HB2C_{}_MDE.nxs'.format(run) for run in range(4756, 6557, 1) ]: LoadMD(Filename=filename, LoadHistory=False, OutputWorkspace='md') convertQSampleToHKL('md', norm=van, UB=ub, Extents=[-7.01, 7.01, -7.01, 7.01, -2.01, 2.01], Bins=[701, 701, 201], OutputWorkspace='hkl', Append=True) SaveMD('hkl', '/HFIR/HB2C/IPTS-7776/shared/rwp/PNO_data_MDH_0.2.nxs') SaveMD('hkl_norm', '/HFIR/HB2C/IPTS-7776/shared/rwp/PNO_norm_MDH_0.2.nxs') norm_data = DivideMD('hkl', 'hkl_norm') # Symmerty CloneMDWorkspace('hkl', OutputWorkspace='hkl_sym') CloneMDWorkspace('hkl_norm', OutputWorkspace='hkl_norm_sym') data_signal = mtd['hkl'].getSignalArray() norm_signal = mtd['hkl_norm'].getSignalArray() data_signal_new = data_signal + data_signal[::-1, ::-1, ::1] # 180 norm_signal_new = norm_signal + norm_signal[::-1, ::-1, ::1] # 180 data_signal_new = data_signal + np.transpose( data_signal, (1, 0, 2))[::-1, ::1, ::1] + data_signal[::-1, ::-1, ::1] + np.transpose(