def generate_ts_pdf(run_number, focus_file_path, merge_banks=False, q_lims=None, cal_file_name=None, sample_details=None, delta_r=None, delta_q=None, pdf_type="G(r)", lorch_filter=None, freq_params=None, debug=False): focused_ws = _obtain_focused_run(run_number, focus_file_path) focused_ws = mantid.ConvertUnits(InputWorkspace=focused_ws, Target="MomentumTransfer", EMode='Elastic') raw_ws = mantid.Load(Filename='POLARIS'+str(run_number)+'.nxs') sample_geometry = common.generate_sample_geometry(sample_details) sample_material = common.generate_sample_material(sample_details) self_scattering_correction = mantid.TotScatCalculateSelfScattering( InputWorkspace=raw_ws, CalFileName=cal_file_name, SampleGeometry=sample_geometry, SampleMaterial=sample_material, CrystalDensity=sample_details.material_object.crystal_density) ws_group_list = [] for i in range(self_scattering_correction.getNumberHistograms()): ws_name = 'correction_' + str(i) mantid.ExtractSpectra(InputWorkspace=self_scattering_correction, OutputWorkspace=ws_name, WorkspaceIndexList=[i]) ws_group_list.append(ws_name) self_scattering_correction = mantid.GroupWorkspaces(InputWorkspaces=ws_group_list) self_scattering_correction = mantid.RebinToWorkspace(WorkspaceToRebin=self_scattering_correction, WorkspaceToMatch=focused_ws) focused_ws = mantid.Subtract(LHSWorkspace=focused_ws, RHSWorkspace=self_scattering_correction) if delta_q: focused_ws = mantid.Rebin(InputWorkspace=focused_ws, Params=delta_q) if merge_banks: q_min, q_max = _load_qlims(q_lims) merged_ws = mantid.MatchAndMergeWorkspaces(InputWorkspaces=focused_ws, XMin=q_min, XMax=q_max, CalculateScale=False) fast_fourier_filter(merged_ws, freq_params=freq_params) pdf_output = mantid.PDFFourierTransform(Inputworkspace="merged_ws", InputSofQType="S(Q)-1", PDFType=pdf_type, Filter=lorch_filter, DeltaR=delta_r, rho0=sample_details.material_object.crystal_density) else: for ws in focused_ws: fast_fourier_filter(ws, freq_params=freq_params) pdf_output = mantid.PDFFourierTransform(Inputworkspace='focused_ws', InputSofQType="S(Q)-1", PDFType=pdf_type, Filter=lorch_filter, DeltaR=delta_r, rho0=sample_details.material_object.crystal_density) pdf_output = mantid.RebinToWorkspace(WorkspaceToRebin=pdf_output, WorkspaceToMatch=pdf_output[4], PreserveEvents=True) if not debug: common.remove_intermediate_workspace('self_scattering_correction') # Rename output ws if 'merged_ws' in locals(): mantid.RenameWorkspace(InputWorkspace='merged_ws', OutputWorkspace=run_number + '_merged_Q') mantid.RenameWorkspace(InputWorkspace='focused_ws', OutputWorkspace=run_number+'_focused_Q') if isinstance(focused_ws, WorkspaceGroup): for i in range(len(focused_ws)): mantid.RenameWorkspace(InputWorkspace=focused_ws[i], OutputWorkspace=run_number+'_focused_Q_'+str(i+1)) mantid.RenameWorkspace(InputWorkspace='pdf_output', OutputWorkspace=run_number+'_pdf_R') if isinstance(pdf_output, WorkspaceGroup): for i in range(len(pdf_output)): mantid.RenameWorkspace(InputWorkspace=pdf_output[i], OutputWorkspace=run_number+'_pdf_R_'+str(i+1)) return pdf_output
def _multiple_load(self, data_file, workspace, property_manager, property_manager_name): instrument = '' if property_manager.existsProperty('InstrumentName'): property_manager.existsProperty('InstrumentName') instrument = property_manager.getProperty('InstrumentName').value else: property_manager.existsProperty('InstrumentName') output_str = '' if isinstance(data_file, str): if AnalysisDataService.doesExist(data_file): data_file = [data_file] else: data_file = find_data(data_file, instrument=instrument, allow_multiple=True) if isinstance(data_file, list): for i in range(len(data_file)): if i == 0: output_str += self._load_data(data_file[i], workspace, property_manager, property_manager_name) continue output_str += self._load_data(data_file[i], '__tmp_wksp', property_manager, property_manager_name) api.RebinToWorkspace(WorkspaceToRebin='__tmp_wksp', WorkspaceToMatch=workspace, OutputWorkspace='__tmp_wksp') api.Plus(LHSWorkspace=workspace, RHSWorkspace='__tmp_wksp', OutputWorkspace=workspace) if AnalysisDataService.doesExist('__tmp_wksp'): AnalysisDataService.remove('__tmp_wksp') else: output_str += 'Loaded %s\n' % data_file output_str += self._load_data(data_file, workspace, property_manager, property_manager_name) return output_str
def _calibData(self, sam_ws, mon_ws): sapi.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask) sapi.ModeratorTzeroLinear(InputWorkspace=sam_ws, OutputWorkspace=sam_ws) sapi.LoadParameterFile(Workspace=sam_ws, Filename=pjoin(DEFAULT_CONFIG_DIR, self._reflection["parameter_file"])) sapi.ConvertUnits(InputWorkspace=sam_ws, OutputWorkspace=sam_ws, Target='Wavelength', EMode='Indirect') if self._MonNorm: sapi.ModeratorTzeroLinear(InputWorkspace=mon_ws, OutputWorkspace=mon_ws) sapi.Rebin(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Params='10') sapi.ConvertUnits(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Target='Wavelength') sapi.OneMinusExponentialCor(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, C='0.20749999999999999', C1='0.001276') sapi.Scale(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Factor='1e-06') sapi.RebinToWorkspace(WorkspaceToRebin=sam_ws, WorkspaceToMatch=mon_ws, OutputWorkspace=sam_ws) sapi.Divide(LHSWorkspace=sam_ws, RHSWorkspace=mon_ws, OutputWorkspace=sam_ws)
def save_combined_panel(self, run, panel): panel_combination = {5: 6, 4: 7, 3: 8, 2: 9, 1: 10} input_ws1 = "w{0}-{1}foc".format(run, panel) input_ws2 = "w{0}-{1}foc".format(run, panel_combination.get(panel)) combined = "{0}{1}-{2}_{3}foc{4}".format("{0}", run, panel, panel_combination.get(panel), "{1}") combined_save = combined.format("", "{}") combined_ws = combined.format("w", "") simple.RebinToWorkspace(WorkspaceToRebin=input_ws2, WorkspaceToMatch=input_ws1, OutputWorkspace=input_ws2, PreserveEvents='0') simple.Plus(LHSWorkspace=input_ws1, RHSWorkspace=input_ws2, OutputWorkspace=combined_ws) simple.ConvertUnits(InputWorkspace=combined_ws, OutputWorkspace=combined_ws + "-d", Target="dSpacing", EMode="Elastic") simple.SaveGSS(combined_ws, os.path.join(self.user_directory, combined_save.format("raw.gss")), Append=False, Bank=1) simple.SaveFocusedXYE( combined_ws, os.path.join(self.user_directory, combined_save.format("raw.dat"))) simple.SaveNexusProcessed( combined_ws, os.path.join(self.user_directory, combined_save.format("raw.nxs")))
def _calibData(self, sam_ws, mon_ws): api.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask) #MaskedWorkspace='BASIS_MASK') api.ModeratorTzeroLinear(InputWorkspace=sam_ws,\ OutputWorkspace=sam_ws) api.LoadParameterFile(Workspace=sam_ws, Filename=config.getInstrumentDirectory() + 'BASIS_silicon_111_Parameters.xml') api.ConvertUnits(InputWorkspace=sam_ws, OutputWorkspace=sam_ws, Target='Wavelength', EMode='Indirect') if not self._noMonNorm: api.ModeratorTzeroLinear(InputWorkspace=mon_ws,\ OutputWorkspace=mon_ws) api.Rebin(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Params='10') api.ConvertUnits(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Target='Wavelength') api.OneMinusExponentialCor(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, C='0.20749999999999999', C1='0.001276') api.Scale(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Factor='9.9999999999999995e-07') api.RebinToWorkspace(WorkspaceToRebin=sam_ws, WorkspaceToMatch=mon_ws, OutputWorkspace=sam_ws) api.Divide(LHSWorkspace=sam_ws, RHSWorkspace=mon_ws, OutputWorkspace=sam_ws)
def _run_focus(input_workspace, tof_output_name, vanadium_integration_ws, vanadium_curves_ws, df_kwarg, full_calib, region_calib): simple.NormaliseByCurrent(InputWorkspace=input_workspace, OutputWorkspace=input_workspace) input_workspace /= vanadium_integration_ws simple.ReplaceSpecialValues(InputWorkspace=input_workspace, OutputWorkspace=input_workspace, NaNValue=0, InfinityValue=0) simple.ApplyDiffCal(InstrumentWorkspace=input_workspace, CalibrationWorkspace=full_calib) ws_d = simple.ConvertUnits(InputWorkspace=input_workspace, Target='dSpacing') focused_sample = simple.DiffractionFocussing(InputWorkspace=ws_d, **df_kwarg) curves_rebinned = simple.RebinToWorkspace(WorkspaceToRebin=vanadium_curves_ws, WorkspaceToMatch=focused_sample) normalised = simple.Divide(LHSWorkspace=focused_sample, RHSWorkspace=curves_rebinned, AllowDifferentNumberSpectra=True) simple.ApplyDiffCal(InstrumentWorkspace=normalised, CalibrationWorkspace=region_calib) dspacing_output_name = tof_output_name + "_dSpacing" simple.CloneWorkspace(InputWorkspace=normalised, OutputWorkspace=dspacing_output_name) simple.ConvertUnits(InputWorkspace=normalised, OutputWorkspace=tof_output_name, Target='TOF') simple.DeleteWorkspace(curves_rebinned) simple.DeleteWorkspace(focused_sample) simple.DeleteWorkspace(normalised) simple.DeleteWorkspace(ws_d)
def apply_vanadium_absorb_corrections(van_ws, run_details, absorb_ws=None): if absorb_ws is None: absorb_ws = mantid.Load(Filename=run_details.vanadium_absorption_path) van_original_units = van_ws.getAxis(0).getUnit().unitID() absorb_units = absorb_ws.getAxis(0).getUnit().unitID() if van_original_units != absorb_units: van_ws = mantid.ConvertUnits(InputWorkspace=van_ws, Target=absorb_units, OutputWorkspace=van_ws) absorb_ws = mantid.RebinToWorkspace(WorkspaceToRebin=absorb_ws, WorkspaceToMatch=van_ws, OutputWorkspace=absorb_ws) van_ws = mantid.Divide(LHSWorkspace=van_ws, RHSWorkspace=absorb_ws, OutputWorkspace=van_ws) if van_original_units != absorb_units: van_ws = mantid.ConvertUnits(InputWorkspace=van_ws, Target=van_original_units, OutputWorkspace=van_ws) common.remove_intermediate_workspace(absorb_ws) return van_ws
def _divide_one_spectrum_by_spline(spectrum, spline): rebinned_spline = mantid.RebinToWorkspace(WorkspaceToRebin=spline, WorkspaceToMatch=spectrum, StoreInADS=False) divided = mantid.Divide(LHSWorkspace=spectrum, RHSWorkspace=rebinned_spline, OutputWorkspace=spectrum) return divided
def generate_ts_pdf(run_number, focus_file_path, merge_banks=False, q_lims=None, cal_file_name=None, sample_details=None, output_binning=None, pdf_type="G(r)", freq_params=None): focused_ws = _obtain_focused_run(run_number, focus_file_path) focused_ws = mantid.ConvertUnits(InputWorkspace=focused_ws, Target="MomentumTransfer", EMode='Elastic') raw_ws = mantid.Load(Filename='POLARIS'+str(run_number)+'.nxs') sample_geometry = common.generate_sample_geometry(sample_details) sample_material = common.generate_sample_material(sample_details) self_scattering_correction = mantid.TotScatCalculateSelfScattering(InputWorkspace=raw_ws, CalFileName=cal_file_name, SampleGeometry=sample_geometry, SampleMaterial=sample_material) ws_group_list = [] for i in range(self_scattering_correction.getNumberHistograms()): ws_name = 'correction_' + str(i) mantid.ExtractSpectra(InputWorkspace=self_scattering_correction, OutputWorkspace=ws_name, WorkspaceIndexList=[i]) ws_group_list.append(ws_name) self_scattering_correction = mantid.GroupWorkspaces(InputWorkspaces=ws_group_list) self_scattering_correction = mantid.RebinToWorkspace(WorkspaceToRebin=self_scattering_correction, WorkspaceToMatch=focused_ws) focused_ws = mantid.Subtract(LHSWorkspace=focused_ws, RHSWorkspace=self_scattering_correction) if merge_banks: q_min, q_max = _load_qlims(q_lims) merged_ws = mantid.MatchAndMergeWorkspaces(InputWorkspaces=focused_ws, XMin=q_min, XMax=q_max, CalculateScale=False) fast_fourier_filter(merged_ws, freq_params) pdf_output = mantid.PDFFourierTransform(Inputworkspace="merged_ws", InputSofQType="S(Q)-1", PDFType=pdf_type, Filter=True) else: for ws in focused_ws: fast_fourier_filter(ws, freq_params) pdf_output = mantid.PDFFourierTransform(Inputworkspace='focused_ws', InputSofQType="S(Q)-1", PDFType=pdf_type, Filter=True) pdf_output = mantid.RebinToWorkspace(WorkspaceToRebin=pdf_output, WorkspaceToMatch=pdf_output[4], PreserveEvents=True) common.remove_intermediate_workspace('self_scattering_correction') if output_binning is not None: try: pdf_output = mantid.Rebin(InputWorkspace=pdf_output, Params=output_binning) except RuntimeError: return pdf_output return pdf_output
def generate_ts_pdf(run_number, focus_file_path, merge_banks=False): focused_ws = _obtain_focused_run(run_number, focus_file_path) pdf_output = mantid.ConvertUnits(InputWorkspace=focused_ws.getName(), Target="MomentumTransfer") if merge_banks: raise RuntimeError("Merging banks is currently not supported") pdf_output = mantid.PDFFourierTransform(Inputworkspace=pdf_output, InputSofQType="S(Q)", PDFType="G(r)", Filter=True) pdf_output = mantid.RebinToWorkspace(WorkspaceToRebin=pdf_output, WorkspaceToMatch=pdf_output[4], PreserveEvents=True) return pdf_output
def _subtract(self): """ Do a simple container subtraction (when no corrections are given). """ logger.information('Rebining container to ensure Minus') s_api.RebinToWorkspace(WorkspaceToRebin=self._can_ws_name, WorkspaceToMatch=self._sample_ws_wavelength, OutputWorkspace=self._can_ws_name) logger.information('Using simple container subtraction') # Rebin can s_api.RebinToWorkspace( WorkspaceToRebin=self._scaled_container_wavelength, WorkspaceToMatch=self._sample_ws_wavelength, OutputWorkspace=self._scaled_container_wavelength) s_api.Minus(LHSWorkspace=self._sample_ws_wavelength, RHSWorkspace=self._scaled_container_wavelength, OutputWorkspace=self._output_ws_name)
def _divide_by_vanadium_splines(spectra_list, spline_file_path): vanadium_ws_list = mantid.LoadNexus(Filename=spline_file_path) output_list = [] for data_ws, van_ws in zip(spectra_list, vanadium_ws_list[1:]): vanadium_ws = mantid.RebinToWorkspace(WorkspaceToRebin=van_ws, WorkspaceToMatch=data_ws) output_ws = mantid.Divide(LHSWorkspace=data_ws, RHSWorkspace=vanadium_ws, OutputWorkspace=data_ws) output_list.append(output_ws) common.remove_intermediate_workspace(vanadium_ws) return output_list
def attenuate_workspace(attenuation_file_path, ws_to_correct): original_units = ws_to_correct.getAxis(0).getUnit().unitID() wc_attenuated = mantid.PearlMCAbsorption(attenuation_file_path) wc_attenuated = mantid.ConvertToHistogram(InputWorkspace=wc_attenuated, OutputWorkspace=wc_attenuated) ws_to_correct = mantid.ConvertUnits(InputWorkspace=ws_to_correct, OutputWorkspace=ws_to_correct, Target=wc_attenuated.getAxis(0).getUnit().unitID()) wc_attenuated = mantid.RebinToWorkspace(WorkspaceToRebin=wc_attenuated, WorkspaceToMatch=ws_to_correct, OutputWorkspace=wc_attenuated) pearl_attenuated_ws = mantid.Divide(LHSWorkspace=ws_to_correct, RHSWorkspace=wc_attenuated) common.remove_intermediate_workspace(workspaces=wc_attenuated) pearl_attenuated_ws = mantid.ConvertUnits(InputWorkspace=pearl_attenuated_ws, OutputWorkspace=pearl_attenuated_ws, Target=original_units) return pearl_attenuated_ws
def _run_attenuate_workspace(self, input_workspace): if self._old_atten_file is None: # For old API support attenuation_path = self._attenuation_full_path else: attenuation_path = self._old_atten_file wc_attenuated = mantid.PearlMCAbsorption(attenuation_path) wc_attenuated = mantid.ConvertToHistogram(InputWorkspace=wc_attenuated, OutputWorkspace=wc_attenuated) wc_attenuated = mantid.RebinToWorkspace(WorkspaceToRebin=wc_attenuated, WorkspaceToMatch=input_workspace, OutputWorkspace=wc_attenuated) pearl_attenuated_ws = mantid.Divide(LHSWorkspace=input_workspace, RHSWorkspace=wc_attenuated) common.remove_intermediate_workspace(workspace_name=wc_attenuated) return pearl_attenuated_ws
def _normalize_one_spectrum(single_spectrum_ws, spline, instrument): rebinned_spline = mantid.RebinToWorkspace( WorkspaceToRebin=spline, WorkspaceToMatch=single_spectrum_ws, StoreInADS=False) divided = mantid.Divide(LHSWorkspace=single_spectrum_ws, RHSWorkspace=rebinned_spline, StoreInADS=False) if instrument.get_instrument_prefix() == "GEM": values_replaced = mantid.ReplaceSpecialValues(InputWorkspace=divided, NaNValue=0, StoreInADS=False) # crop based off max between 1000 and 2000 tof as the vanadium peak on Gem will always occur here complete = _crop_spline_to_percent_of_max(rebinned_spline, values_replaced, single_spectrum_ws, 1000, 2000) else: complete = mantid.ReplaceSpecialValues( InputWorkspace=divided, NaNValue=0, OutputWorkspace=single_spectrum_ws) if instrument.perform_abs_vanadium_norm(): vanadium_material = spline.sample().getMaterial() v_number_density = vanadium_material.numberDensityEffective v_cross_section = vanadium_material.totalScatterXSection() vanadium_shape = spline.sample().getShape() # number density in Angstroms-3, volume in m3. Don't bother with 1E30 factor because will cancel num_v_atoms = vanadium_shape.volume() * v_number_density sample_material = single_spectrum_ws.sample().getMaterial() sample_number_density = sample_material.numberDensityEffective sample_shape = spline.sample().getShape() num_sample_atoms = sample_shape.volume() * sample_number_density abs_norm_factor = v_cross_section * num_v_atoms / \ (num_sample_atoms * 4 * math.pi) logger.notice( "Performing absolute normalisation, multiplying by factor=" + str(abs_norm_factor)) # avoid "Variable invalidated, data has been deleted" error when debugging output_ws_name = single_spectrum_ws.name() abs_norm_factor_ws = mantid.CreateSingleValuedWorkspace( DataValue=abs_norm_factor, OutputWorkspace="__abs_norm_factor_ws") complete = mantid.Multiply(LHSWorkspace=complete, RHSWorkspace=abs_norm_factor_ws, OutputWorkspace=output_ws_name) return complete
def _subtract(self, minuend_workspace, subtrahend_workspace): """ Do a simple container subtraction (when no corrections are given). """ logger.information('Using simple container subtraction') if self._rebin_container_ws: logger.information('Rebining container to ensure Minus') subtrahend_workspace = s_api.RebinToWorkspace(WorkspaceToRebin=subtrahend_workspace, WorkspaceToMatch=minuend_workspace, OutputWorkspace="__rebinned", StoreInADS=False) return minuend_workspace - subtrahend_workspace
def _divide_one_spectrum_by_spline(spectrum, spline, instrument): rebinned_spline = mantid.RebinToWorkspace(WorkspaceToRebin=spline, WorkspaceToMatch=spectrum, StoreInADS=False) if instrument.get_instrument_prefix() == "GEM": divided = mantid.Divide(LHSWorkspace=spectrum, RHSWorkspace=rebinned_spline, OutputWorkspace=spectrum, StoreInADS=False) complete = mantid.ReplaceSpecialValues(InputWorkspace=divided, NaNValue=0, StoreInADS=False) # crop based off max between 1000 and 2000 tof as the vanadium peak on Gem will always occur here return _crop_spline_to_percent_of_max(rebinned_spline, complete, spectrum, 1000, 2000) divided = mantid.Divide(LHSWorkspace=spectrum, RHSWorkspace=rebinned_spline, StoreInADS=False) complete = mantid.ReplaceSpecialValues(InputWorkspace=divided, NaNValue=0, OutputWorkspace=spectrum) return complete
def _correct_sample_can(self): """ Correct for sample and container. """ logger.information('Correcting sample and container') corrected_can_ws = '__corrected_can' factor_types = ['_ass'] if self._use_can: factor_types.extend(['_acc', '_acsc', '_assc']) corr_unit = s_api.mtd[self._corrections + '_ass'].getAxis(0).getUnit().unitID() for f_type in factor_types: self._convert_units_wavelength(corr_unit, self._corrections + f_type, self._corrections + f_type, "Wavelength") if self._rebin_container_ws: s_api.RebinToWorkspace( WorkspaceToRebin=self._scaled_container_wavelength, WorkspaceToMatch=self._corrections + '_acc', OutputWorkspace=self._scaled_container_wavelength) # Acc s_api.Divide(LHSWorkspace=self._scaled_container_wavelength, RHSWorkspace=self._corrections + '_acc', OutputWorkspace=corrected_can_ws) # Acsc s_api.Multiply(LHSWorkspace=corrected_can_ws, RHSWorkspace=self._corrections + '_acsc', OutputWorkspace=corrected_can_ws) s_api.Minus(LHSWorkspace=self._sample_ws_wavelength, RHSWorkspace=corrected_can_ws, OutputWorkspace=self._output_ws_name) # Assc s_api.Divide(LHSWorkspace=self._output_ws_name, RHSWorkspace=self._corrections + '_assc', OutputWorkspace=self._output_ws_name) for f_type in factor_types: self._convert_units_wavelength(corr_unit, self._corrections + f_type, self._corrections + f_type, corr_unit) s_api.DeleteWorkspace(corrected_can_ws)
def apply_vanadium_absorb_corrections(van_ws, run_details, absorb_ws=None): def generate_det_id_list(ws): det_id_list = [] for i in range(0, ws.getNumberHistograms()): try: det_ids = ws.getSpectrum(i).getDetectorIDs() except RuntimeError: pass else: for det_id in det_ids: det_id_list.append(det_id) return det_id_list if absorb_ws is None: absorb_ws = mantid.Load(Filename=run_details.vanadium_absorption_path) van_original_units = van_ws.getAxis(0).getUnit().unitID() absorb_units = absorb_ws.getAxis(0).getUnit().unitID() if van_original_units != absorb_units: van_ws = mantid.ConvertUnits(InputWorkspace=van_ws, Target=absorb_units, OutputWorkspace=van_ws) # PEARL sometimes do special runs with different detector cards so extract common spectra before doing # RebinToWorkspace to ensure histogram by histogram by rebin abs_det_id_list = generate_det_id_list(absorb_ws) van_det_id_list = generate_det_id_list(van_ws) common_det_ids = [det_id for det_id in abs_det_id_list if det_id in van_det_id_list] if not common_det_ids: raise RuntimeError("No common detectors in Vanadium and sample workspaces") MSG_STEM = "Vanadium workspace and absorption workspaces have different spectra. " if common_det_ids != van_det_id_list: logger.warning(MSG_STEM + "Removing unmatched spectra from the Vanadium workspace") van_ws = mantid.ExtractSpectra(InputWorkspace=van_ws, DetectorList=common_det_ids) if common_det_ids != abs_det_id_list: logger.warning(MSG_STEM + "Removing unmatched spectra from the absorption workspace") absorb_ws = mantid.ExtractSpectra(InputWorkspace=absorb_ws, DetectorList=common_det_ids) absorb_ws = mantid.RebinToWorkspace(WorkspaceToRebin=absorb_ws, WorkspaceToMatch=van_ws, OutputWorkspace=absorb_ws) van_ws = mantid.Divide(LHSWorkspace=van_ws, RHSWorkspace=absorb_ws, OutputWorkspace=van_ws, AllowDifferentNumberSpectra=True) if van_original_units != absorb_units: van_ws = mantid.ConvertUnits(InputWorkspace=van_ws, Target=van_original_units, OutputWorkspace=van_ws) common.remove_intermediate_workspace(absorb_ws) return van_ws
def _divide_by_curves(self, ws, curves): """ Expects a workspace in ToF units. All operations are done in-place (the workspace is input/output). For every bank-curve pair, divides the corresponding spectra in the workspace by the (simulated) fitted curve. The division is done in d-spacing (the input workspace is converted to d-spacing inside this method, but results are converted back to ToF before returning from this method). The curves workspace is expected in d-spacing units (since it comes from fitting a sum of spectra for a bank or group of detectors). This method is capable of dealing with workspaces with range and bin size different from the range and bin size of the curves. It will rebin the curves workspace to match the input 'ws' workspace (using the algorithm RebinToWorkspace). @param ws :: workspace with (sample) spectra to divide by curves fitted to Vanadium spectra @param curves :: dictionary of fitting workspaces (in d-spacing), one per bank. The keys are the bank identifier and the values are their fitting workspaces. The fitting workspaces are expected as returned by the algorithm 'Fit': 3 spectra: original data, simulated data with fit, difference between original and simulated data. """ # Note that this division could use the algorithm 'Divide' # This is simple and more efficient than using divide workspace, which requires # cropping separate workspaces, dividing them separately, then appending them # with AppendSpectra, etc. ws = EnggUtils.convert_to_d_spacing(self, ws) for b in curves: # process all the spectra (indices) in one bank fitted_curve = curves[b] idxs = EnggUtils.get_ws_indices_for_bank(ws, b) if not idxs: pass # This RebinToWorkspace is required here: normal runs will have narrower range of X values, # and possibly different bin size, as compared to (long) Vanadium runs. Same applies to short # Ceria runs (for Calibrate -non-full) and even long Ceria runs (for Calibrate-Full). rebinned_fit_curve = mantid.RebinToWorkspace( WorkspaceToRebin=fitted_curve, WorkspaceToMatch=ws, StoreInADS=False) for i in idxs: # take values of the second spectrum of the workspace (fit simulation - fitted curve) ws.setY(i, np.divide(ws.dataY(i), rebinned_fit_curve.readY(1))) # finally, convert back to ToF EnggUtils.convert_to_TOF(self, ws)
def _calibrate_data(self, run_set, sam_ws): sapi.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask) rpf = self._elucidate_reflection_parameter_file(sam_ws) sapi.LoadParameterFile(Workspace=sam_ws, Filename=rpf) sapi.ModeratorTzeroLinear(InputWorkspace=sam_ws, OutputWorkspace=sam_ws) sapi.ConvertUnits(InputWorkspace=sam_ws, OutputWorkspace=sam_ws, Target='Wavelength', EMode='Indirect') if self._flux_normalization_type is not None: flux_ws = self._generate_flux_spectrum(run_set, sam_ws) sapi.RebinToWorkspace(WorkspaceToRebin=sam_ws, WorkspaceToMatch=flux_ws, OutputWorkspace=sam_ws) sapi.Divide(LHSWorkspace=sam_ws, RHSWorkspace=flux_ws, OutputWorkspace=sam_ws)
def _divide_one_spectrum_by_spline(spectrum, spline, instrument): rebinned_spline = mantid.RebinToWorkspace(WorkspaceToRebin=spline, WorkspaceToMatch=spectrum, StoreInADS=False) if instrument.get_instrument_prefix() == "GEM": divided = mantid.Divide(LHSWorkspace=spectrum, RHSWorkspace=rebinned_spline, OutputWorkspace=spectrum, StoreInADS=False) return _crop_spline_to_percent_of_max(rebinned_spline, divided, spectrum) divided = mantid.Divide(LHSWorkspace=spectrum, RHSWorkspace=rebinned_spline, OutputWorkspace=spectrum) return divided
def _correct_sample_can(self, sample_workspace, container_workspace, factor_workspaces): """ Correct for sample and container. """ logger.information('Correcting sample and container') factor_workspaces_wavelength = {factor: self._convert_units_wavelength(workspace) for factor, workspace in factor_workspaces.items()} if self._rebin_container_ws: container_workspace = s_api.RebinToWorkspace(WorkspaceToRebin=container_workspace, WorkspaceToMatch=factor_workspaces_wavelength['acc'], OutputWorkspace="rebinned", StoreInADS=False) return self._corrections_approximation(sample_workspace, container_workspace, factor_workspaces_wavelength)
def calculate(self, reducer, wave_wksps=[]): """ Multiplies all the wavelength scalings into one workspace and all the detector dependent scalings into another workspace that can be used by ConvertToQ. It is important that the wavelength correction workspaces have a know distribution/non-distribution state @param reducer: settings used for this reduction @param wave_wksps: additional wavelength dependent correction workspaces to include """ for step in self._wave_steps: if step.output_wksp: wave_wksps.append(step.output_wksp) wave_adj = None for wksp in wave_wksps: # before the workspaces can be combined they all need to match api.RebinToWorkspace(WorkspaceToRebin=wksp, WorkspaceToMatch=reducer.output_wksp, OutputWorkspace=self.TMP_WORKSPACE_NAME) if not wave_adj: # first time around this loop wave_adj = self.WAVE_CORR_NAME api.RenameWorkspace(InputWorkspace=self.TMP_WORKSPACE_NAME, OutputWorkspace=wave_adj) else: api.Multiply(LHSWorkspace=self.TMP_WORKSPACE_NAME, RHSWorkspace=wave_adj, OutputWorkspace=wave_adj) # read pixel correction file # note the python code below is an attempt to emulate function overloading # If a derived class overwrite self._load and self._load_params then # a custom specific loading can be achieved pixel_adj = '' if self._pixel_file: pixel_adj = self.PIXEL_CORR_NAME load_com = self._load + '(Filename="' + self._pixel_file + '",OutputWorkspace="' + pixel_adj + '"' if self._load_params: load_com += ',' + self._load_params load_com += ')' eval(load_com) if AnalysisDataService.doesExist(self.TMP_WORKSPACE_NAME): AnalysisDataService.remove(self.TMP_WORKSPACE_NAME) return wave_adj, pixel_adj
def generate_ts_pdf(run_number, focus_file_path, merge_banks=False, q_lims=None): focused_ws = _obtain_focused_run(run_number, focus_file_path) if merge_banks: pdf_output = _generate_grouped_ts_pdf(focused_ws, q_lims) else: focused_ws = mantid.ConvertUnits(InputWorkspace=focused_ws.name(), Target="MomentumTransfer") pdf_output = mantid.PDFFourierTransform(Inputworkspace=focused_ws, InputSofQType="S(Q)", PDFType="G(r)", Filter=True) pdf_output = mantid.RebinToWorkspace(WorkspaceToRebin=pdf_output, WorkspaceToMatch=pdf_output[4], PreserveEvents=True) common.remove_intermediate_workspace('focused_ws') return pdf_output
def apply_vanadium_corrections(self, cyclevana, i, focused_ws): simple.LoadNexusProcessed(Filename=self.get_vanadium(i, cyclevana), OutputWorkspace="vana") simple.RebinToWorkspace(WorkspaceToRebin="vana", WorkspaceToMatch=focused_ws, OutputWorkspace="vana") simple.Divide(LHSWorkspace=focused_ws, RHSWorkspace="vana", OutputWorkspace=focused_ws) simple.DeleteWorkspace("vana") simple.ConvertUnits(InputWorkspace=focused_ws, OutputWorkspace=focused_ws, Target="TOF", EMode="Elastic") simple.ReplaceSpecialValues(InputWorkspace=focused_ws, OutputWorkspace=focused_ws, NaNValue=0.0, NaNError=0.0, InfinityValue=0.0, InfinityError=0.0)
def prepare_plot_data(self): """ Bin events to be used for plotting and in-app calculations """ workspace = api.mtd[self._event_workspace] if self.xtofdata is None: t_0 = time.time() binning_ws = api.CreateWorkspace( DataX=self.tof_edges, DataY=np.zeros(len(self.tof_edges) - 1)) data_rebinned = api.RebinToWorkspace(WorkspaceToRebin=workspace, WorkspaceToMatch=binning_ws) Ixyt = getIxyt(data_rebinned) # Create projections for the 2D datasets Ixy = Ixyt.sum(axis=2) Ixt = Ixyt.sum(axis=1) # Store the data self.data = Ixyt.astype(float) # 3D dataset self.xydata = Ixy.transpose().astype(float) # 2D dataset self.xtofdata = Ixt.astype(float) # 2D dataset logging.info("Plot data generated: %s sec", time.time() - t_0)
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 _apply_transmission(self, workspace, trans_workspace): """ Apply transmission correction @param workspace: workspace to apply correction to @param trans_workspace: workspace name for of the transmission """ # Make sure the binning is compatible api.RebinToWorkspace(WorkspaceToRebin=trans_workspace, WorkspaceToMatch=workspace, OutputWorkspace=trans_workspace+'_rebin', PreserveEvents=False) # Apply angle-dependent transmission correction using the zero-angle transmission theta_dependent = self.getProperty("ThetaDependent").value api.ApplyTransmissionCorrection(InputWorkspace=workspace, TransmissionWorkspace=trans_workspace+'_rebin', OutputWorkspace=workspace, ThetaDependent=theta_dependent) if AnalysisDataService.doesExist(trans_workspace+'_rebin'): AnalysisDataService.remove(trans_workspace+'_rebin')
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)