def _run_number_changed(self): """ Handling event if run number is changed... If it is a valid run number, the load the meta data """ from datetime import datetime # 1. Form the file newrunnumberstr = self._content.run_number_edit.text() instrument = self._instrument_name eventnxsname = "%s_%s_event.nxs" % (instrument, newrunnumberstr) msg = str("Load event nexus file %s" % (eventnxsname)) self._content.info_text_browser.setText(msg) # 2. Load file metawsname = "%s_%s_meta" % (instrument, newrunnumberstr) try: metaws = api.Load(Filename=str(eventnxsname), OutputWorkspace=str(metawsname), MetaDataOnly=True) except ValueError: metaws = None # 3. Update the log name combo box if metaws is None: self._content.info_text_browser.setText(\ str("Error! Failed to load data file %s. Current working directory is %s. " % (eventnxsname, os.getcwd()))) else: self._metaws = metaws # a) Clear self._content.log_name_combo.clear() # b) Get properties wsrun = metaws.getRun() ps = wsrun.getProperties() properties = [] for p in ps: if p.__class__.__name__ == "FloatTimeSeriesProperty": if p.size() > 1: properties.append(p.name) print p.name, p.size() # ENDFOR p properties = sorted(properties) # c) Add for p in properties: self._content.log_name_combo.addItem(p) # ENDIFELSE """ now = datetime.now() print "New Run Number = %s. @ %s" % (newrunnumberstr, str(now)) if newrunnumberstr == "": self._content.log_name_combo.clear() else: self._content.log_name_combo.addItem(newrunnumberstr) """ return
def load_van_curves_file(curves_van): """ load the vanadium curves file passed in @param curves_van:: the path to the integrated vanadium file """ van_curves_ws = simple.Load(curves_van, OutputWorkspace="curves_van") return van_curves_ws
def load_L2_from_nxs(path): "load L2 computed using mantid and saved as nxs" from mantid import simpleapi as msa L2_calib = msa.Load(path) L2_calib = msa.SortTableWorkspace(L2_calib, Columns='detid') L2 = np.array(L2_calib.column('L2')) L2_detID = np.array(L2_calib.column('detid')) nodata = np.array(L2_calib.column('nodata'), dtype=bool) return L2
def load_van_integration_file(ints_van): """ load the vanadium integration file passed in @param ints_van:: the path to the integrated vanadium file """ van_integrated_ws = simple.Load(ints_van, OutputWorkspace="int_van") return van_integrated_ws
def create_calibration_cropped_file(ceria_run, van_run, curve_van, int_van, calibration_directory, calibration_general, use_spectrum_number, crop_name, spec_nos): """ create and save a cropped calibration file @param ceria_run :: run number for the ceria used @param van_run :: the run number of the vanadium to use @param curve_van :: name of the vanadium curves workspace @param int_van :: name of the integrated vanadium workspace @param calibration_directory :: the user specific calibration directory to save to @param calibration_general :: the general calibration dirrecory @param use_spectrum_number :: whether or not to crop using spectrum numbers or banks @param crop_name :: name of the output workspace @param spec_nos :: the value to crop on, either a spectra number, or a bank """ van_curves_ws, van_integrated_ws = load_van_files(curve_van, int_van) ceria_ws = simple.Load(Filename="ENGINX" + ceria_run, OutputWorkspace="eng_calib") # check which cropping method to use if use_spectrum_number: param_tbl_name = crop_name if crop_name is not None else "cropped" # run the calibration cropping on spectrum number output = simple.EnggCalibrate(InputWorkspace=ceria_ws, VanIntegrationWorkspace=van_integrated_ws, VanCurvesWorkspace=van_curves_ws, SpectrumNumbers=str(spec_nos), FittedPeaks=param_tbl_name, OutputParametersTableName=param_tbl_name) # get the values needed for saving out the .prm files difc = [output.DIFC] tzero = [output.TZERO] difa = [output.DIFA] save_calibration(ceria_run, van_run, calibration_directory, calibration_general, "all_banks", [param_tbl_name], tzero, difc, difa) save_calibration(ceria_run, van_run, calibration_directory, calibration_general, "bank_{}".format(param_tbl_name), [param_tbl_name], tzero, difc, difa) else: # work out which bank number to crop on, then calibrate if spec_nos.lower() == "north": param_tbl_name = "engg_calibration_bank_1" bank = 1 else: param_tbl_name = "engg_calibration_bank_2" bank = 2 output = simple.EnggCalibrate(InputWorkspace=ceria_ws, VanIntegrationWorkspace=van_integrated_ws, VanCurvesWorkspace=van_curves_ws, Bank=str(bank), FittedPeaks=param_tbl_name, OutputParametersTableName=param_tbl_name) # get the values needed for saving out the .prm files difc = [output.DIFC] tzero = [output.TZERO] difa = [output.DIFA] save_calibration(ceria_run, van_run, calibration_directory, calibration_general, "all_banks", [spec_nos], tzero, difc, difa) save_calibration(ceria_run, van_run, calibration_directory, calibration_general, "bank_{}".format(spec_nos), [spec_nos], tzero, difc, difa) # create the table workspace containing the parameters create_params_table(difc, tzero, difa) create_difc_zero_workspace(difc, tzero, spec_nos, param_tbl_name)
def _loadFile(self, filename): """ Load file or run File will be loaded to a workspace shown in MantidPlot """ config = ConfigService # Check input file name and output workspace name if filename.isdigit() is True: # Construct a file name from run number runnumber = int(filename) if runnumber <= 0: error_msg = "Run number cannot be less or equal to zero. User gives %s. " % ( filename) Logger("Filter_Events").error(error_msg) return None else: ishort = config.getInstrument(self._instrument).shortName() filename = "%s_%s" % (ishort, filename) wsname = filename + "_event" elif filename.count(".") > 0: # A proper file name wsname = os.path.splitext(os.path.split(filename)[1])[0] elif filename.count("_") == 1: # A short one as instrument_runnumber iname = filename.split("_")[0] str_runnumber = filename.split("_")[1] if str_runnumber.isdigit() is True and int(str_runnumber) > 0: # Acccepted format ishort = config.getInstrument(iname).shortName() wsname = "%s_%s_event" % (ishort, str_runnumber) else: # Non-supported error_msg = "File name / run number in such format %s is not supported. " % ( filename) Logger("Filter_Events").error(error_msg) return None else: # Unsupported format error_msg = "File name / run number in such format %s is not supported. " % ( filename) Logger("Filter_Events").error(error_msg) return None # Load try: ws = api.Load(Filename=filename, OutputWorkspace=wsname) except RuntimeError as e: ws = None return str(e) return ws
def _compare_ws(reference_file_name, results): ref_ws = mantid.Load(Filename=reference_file_name) is_valid = len(results) > 0 for (ws, ref) in zip(results, ref_ws): if not mantid.CompareWorkspaces(Workspace1=ws, Workspace2=ref): is_valid = False print("{} was not equal to {}".format(ws.getName(), ref.getName())) return is_valid
def run_vanadium_calibration(): vanadium_run = 98532 # Choose arbitrary run in the cycle 17_1 pdf_inst_obj = setup_inst_object(mode="PDF") # Run create vanadium twice to ensure we get two different output splines / files pdf_inst_obj.create_vanadium(first_cycle_run_no=vanadium_run, do_absorb_corrections=True, multiple_scattering=False) # Check the spline looks good and was saved if not os.path.exists(spline_path): raise RuntimeError( "Could not find output spline at the following path: " + spline_path) splined_ws = mantid.Load(Filename=spline_path) unsplined_ws = mantid.Load(Filename=unsplined_van_path) return splined_ws, unsplined_ws
def _get_current_mode_dictionary(run_number_string, inst_settings): mapping_dict = get_cal_mapping_dict(run_number_string, inst_settings.cal_mapping_path) if inst_settings.mode is None: ws = mantid.Load('POLARIS'+run_number_string+'.nxs') mode, cropping_vals = _determine_chopper_mode(ws) inst_settings.mode = mode inst_settings.focused_cropping_values = cropping_vals mantid.DeleteWorkspace(ws) # Get the current mode "Rietveld" or "PDF" run numbers return common.cal_map_dictionary_key_helper(mapping_dict, inst_settings.mode)
def CalibrateWish(RunNumber, PanelNumber): ''' :param RunNumber: is the run number of the calibration. :param PanelNumber: is a string of two-digit number of the panel being calibrated ''' # == Set parameters for calibration == previousDefaultInstrument = mantid.config['default.instrument'] mantid.config['default.instrument'] = "WISH" filename = str(RunNumber) CalibratedComponent = 'WISH/panel' + PanelNumber # Get calibration raw file and integrate it print("Loading", filename) rawCalibInstWS = mantid.Load(filename) # 'raw' in 'rawCalibInstWS' means unintegrated. CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=1, RangeUpper=20000) mantid.DeleteWorkspace(rawCalibInstWS) print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate") # Give y-positions of slit points (gotten for converting first tube's slit point to Y) # WISH instrument has a particularity. It is composed by a group of upper tubes and lower tubes, # they are disposed 3 milimiters in difference one among the other lower_tube = numpy.array([-0.41, -0.31, -0.21, -0.11, -0.02, 0.09, 0.18, 0.28, 0.39]) upper_tube = numpy.array(lower_tube + 0.003) funcForm = 9 * [1] # 9 gaussian peaks print("Created objects needed for calibration.") # Get the calibration and put it into the calibration table # calibrate the lower tubes calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, lower_tube, funcForm, rangeList=list(range(0, 76)), outputPeak=True) # calibrate the upper tubes calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, upper_tube, funcForm, rangeList=list(range(76, 152)), calibTable=calibrationTable, # give the calibration table to append data outputPeak=peakTable # give peak table to append data ) print("Got calibration (new positions of detectors)") # Apply the calibration mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable) print("Applied calibration") # == Save workspace == # uncomment these lines to save the workspace # nexusName = "TubeCalibDemoWish" + PanelNumber + "Result.nxs" # mantid.SaveNexusProcessed(CalibInstWS, 'TubeCalibDemoWishResult.nxs', "Result of Running TubeCalibWishMerlin_Simple.py") # print("saved calibrated workspace (CalibInstWS) into Nexus file", nexusName) # == Reset dafault instrument == mantid.config['default.instrument'] = previousDefaultInstrument
def _compare_ws(reference_file_name, results): ref_ws = mantid.Load(Filename=reference_file_name) is_valid = True if len(results) > 0 else False for ws, ref in zip(results, ref_ws): if not (mantid.CompareWorkspaces(Workspace1=ws, Workspace2=ref)): is_valid = False print(ws.getName() + " was not equal to: " + ref.getName()) return is_valid
def load_L2_from_nxs(self, path): "load L2 computed using mantid and saved as nxs" L2_calib = msa.Load(path) L2_calib = msa.SortTableWorkspace(L2_calib, Columns='detid') L2 = np.array(L2_calib.column('L2')) L2_detID = np.array(L2_calib.column('detid')) assert np.all(self.detIDs == L2_detID) nodata = np.array(L2_calib.column('nodata'), dtype=bool) self.L2 = L2 self.L2_mask = nodata return L2, nodata
def get_solid_angle_corrections(self, vanadium, run_details): if not self._inst_settings.do_solid_angle: return name = "sac" + common.generate_splined_name(vanadium, []) path = run_details.van_paths try: solid_angle = mantid.Load(Filename=os.path.join(path,name)) return solid_angle except ValueError: raise RuntimeError("Could not find " + os.path.join(path, name)+" please run create_vanadium with " "\"do_solid_angle_corrections=True\"")
def loadingStep(filename): filename = str(filename) rangeLower = 2000 # Integrate counts in each spectra from rangeLower to rangeUpper rangeUpper = 10000 # # Get calibration raw file and integrate it rawCalibInstWS = mantid.Load(filename) # 'raw' in 'rawCalibInstWS' means unintegrated. print("Integrating Workspace") CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper) mantid.DeleteWorkspace(rawCalibInstWS) print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate") return CalibInstWS
def setUp(self): mantid.Load(Filename=self.INPUT_FILE_NAME, OutputWorkspace=self.INPUT_WS_NAME) run_algorithm(self.ALG_NAME, InputWorkspace=self.INPUT_WS_NAME, GSASParamFile=self.GSAS_PARAM_FILE, OutputFilename=self.OUTPUT_FILE_NAME, GroupingScheme=[1, 1, 2, 3]) with open(self.OUTPUT_FILE_NAME) as output_file: self.file_contents = output_file.read().split("\n") mantid.mtd.remove(self.INPUT_WS_NAME) os.remove(self.OUTPUT_FILE_NAME)
def _load(self, run_numbers, data_name): """ Load data and monitors for run numbers and monitors. Algorithm 'Load' can aggregate many runs into a single workspace, but it is not able to do so with the monitor workspaces. :param run_numbers: run numbers for data event files :param data_name: output name for data workspace. The name for the workspace holding the monitor data will be data_name+'_monitors' :return: None """ # Find out the files for each run load_algorithm = api.AlgorithmManager.createUnmanaged("Load") load_algorithm.initialize() load_algorithm.setPropertyValue('Filename', str(run_numbers)) files = (load_algorithm.getProperty('Filename').value)[0] if not isinstance(files, list): # run_numbers represents one file only sapi.Load(Filename=files, LoadMonitors=True, OutputWorkspace=data_name) else: sapi.Load(Filename=files[0], LoadMonitors=True, OutputWorkspace=data_name) monitor_name = data_name + '_monitors' for file in files[1:]: sapi.Load(Filename=file, LoadMonitors=True, OutputWorkspace=data_name + '_tmp') sapi.Plus(LHSWorkspace=data_name, RHSWorkspace=data_name + '_tmp', OutputWorkspace=data_name) sapi.Plus(LHSWorkspace=monitor_name, RHSWorkspace=data_name + '_tmp_monitors', OutputWorkspace=monitor_name) sapi.DeleteWorkspace(data_name + '_tmp') if sapi.mtd[data_name].getInstrument().getName() not in ('ARCS'): raise NotImplementedError( "This algorithm works only for ARCS instrument")
def do_reduction(calibration): # load data data = ms.Load("HRP39180.RAW") # copy parameters from calibration to data ms.CopyInstrumentParameters(calibration, data) # Now move component on data workspace using a relative move, where that component was a detector in the calibrated workspace ms.MoveInstrumentComponent(data, DetectorID=1100, X=0.0, Y=0.0, Z=5.0, RelativePosition=True) return data.getDetector(0).getPos()
def run_vanadium_calibration(): vanadium_run = 66031 # Choose arbitrary run from cycle 16_5 inst_obj = setup_inst_object() inst_obj.create_vanadium(first_cycle_run_no=vanadium_run, do_absorb_corrections=True, multiple_scattering=False, window="10-110") # Check the spline looks good and was saved if not os.path.exists(spline_path): raise RuntimeError("Could not find output spline at the following path: {}".format(spline_path)) splined_ws = mantid.Load(Filename=spline_path) return splined_ws
def get_fitting_neutron_data(fname, prob): """ Load the X-Y-E data from a file and put the values into a fitting problem definition object. @param fname :: file name to load (using mantid loaders) @param prob :: problem definition to populate with X-Y-E data. """ import mantid.simpleapi as msapi wks = msapi.Load(fname) prob.data_pattern_in = wks.readX(0) prob.data_pattern_out = wks.readY(0) prob.data_pattern_obs_errors = wks.readE(0) prob.ref_residual_sum_sq = 0
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 _load_run_and_convert_to_dSpacing(filepath, instrument, full_calib): runno = path_handling.get_run_number_from_path(filepath, instrument) ws = mantid.Load(Filename=filepath, OutputWorkspace=str(runno)) if ws.getRun().getProtonCharge() > 0: ws = mantid.NormaliseByCurrent(InputWorkspace=ws, OutputWorkspace=ws.name()) else: logger.warning(f"Run {ws.name()} has invalid proton charge.") mantid.DeleteWorkspace(ws) return None mantid.ApplyDiffCal(InstrumentWorkspace=ws, CalibrationWorkspace=full_calib) ws = mantid.ConvertUnits(InputWorkspace=ws, OutputWorkspace=ws.name(), Target='dSpacing') return ws
def apply_vanadium_absorb_corrections(van_ws, run_details): 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) van_ws = mantid.RebinToWorkspace(WorkspaceToRebin=van_ws, WorkspaceToMatch=absorb_ws, OutputWorkspace=van_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 create_calibration_files(ceria_run, van_run, curve_van, int_van, calibration_directory, calibration_general): """ create the calibration files for an uncropped run @param ceria_run :: the run number of the ceria @param van_run :: the run number of the vanadium @param curve_van :: the vanadium curves workspace @param int_van :: the integrated vanadium workspace @param calibration_directory :: the user specific calibration directory to save to @param calibration_general :: the general calibration directory """ van_curves_ws, van_integrated_ws = load_van_files(curve_van, int_van) ceria_ws = simple.Load(Filename="ENGINX" + ceria_run, OutputWorkspace="eng_calib") difcs = [] tzeros = [] difa = [] banks = 3 bank_names = ["North", "South"] # loop through the banks, calibrating both for i in range(1, banks): param_tbl_name = "engg_calibration_bank_{}".format(i) output = simple.EnggCalibrate( InputWorkspace=ceria_ws, VanIntegrationWorkspace=van_integrated_ws, VanCurvesWorkspace=van_curves_ws, Bank=str(i), FittedPeaks=param_tbl_name, OutputParametersTableName=param_tbl_name) # add the needed outputs to a list difcs.append(output.DIFC) tzeros.append(output.TZERO) difa.append(output.DIFA) # save out the ones needed for this loop save_calibration(ceria_run, van_run, calibration_directory, calibration_general, "bank_{}".format(bank_names[i - 1]), [bank_names[i - 1]], [tzeros[i - 1]], [difcs[i - 1]]) # save out the total version, then create the table of params save_calibration(ceria_run, van_run, calibration_directory, calibration_general, "all_banks", bank_names, tzeros, difcs) create_params_table(difcs, tzeros, difa) create_difc_zero_workspace(difcs, tzeros, "", None)
def __init__(self, data_file, workspace_name=None): self.errors = [] if HAS_MANTID: try: if workspace_name is None: self.data_ws = "__raw_data_file" else: self.data_ws = str(workspace_name) try: api.LoadEventNexus(Filename=data_file, OutputWorkspace=workspace_name) except: self.errors.append("Error loading data file as Nexus event file:\n%s" % sys.exc_info()[1]) api.Load(Filename=data_file, OutputWorkspace=workspace_name) self.errors = [] except: self.data_ws = None self.errors.append("Error loading data file:\n%s" % sys.exc_info()[1])
def populate_Ei_data(sim_out, nxs): import ast, os props = ast.literal_eval(open(os.path.join(sim_out, 'props.json')).read()) Ei, unit = props['average energy'].split(); assert unit=='meV' t0, unit = props['emission time'].split(); assert unit=='microsecond' setEnergyRequest(nxs, float(Ei)) from mantid import simpleapi as msa if sys.version_info<(3,0) and isinstance(nxs, unicode): nxs = nxs.encode('utf-8') ws = msa.Load(nxs) msa.AddSampleLog(ws, LogName='mcvine-Ei', LogText=str(Ei), LogType='Number') msa.AddSampleLog(ws, LogName='mcvine-t0', LogText=str(t0), LogType='Number') (fd, filename) = tempfile.mkstemp(); os.close(fd) msa.SaveNexus(ws, filename) from ...ARCS.applications.nxs import mv mv(filename, nxs) return
def run_vanadium_calibration(): vanadium_run = 98507 # Choose arbitrary run in the cycle 17_1 inst_obj = setup_inst_object(mode="tt70") # Run create vanadium twice to ensure we get two different output splines / files inst_obj.create_vanadium(run_in_cycle=vanadium_run, do_absorb_corrections=True) # Check the spline looks good and was saved if not os.path.exists(spline_path): raise RuntimeError( "Could not find output spline at the following path: " + spline_path) splined_ws = mantid.Load(Filename=spline_path) return splined_ws
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 pre_process(focus_run, params, time_period): """ pre_process the run passed in, usign the rebin parameters passed in @param focus_run :: the run to focus @param params :: the rebin parameters @param time_period :: the time period for rebin by pulse @return: pre-processed workspace """ # rebin based on pulse if a time period is sent in, otherwise just do a normal rebin wsname = "engg_preproc_input_ws" simple.Load(Filename=focus_run, OutputWorkspace=wsname) if time_period is not None: return rebin_pulse(params, wsname, time_period) else: return rebin_time(params, wsname)
def runTest(self): import mantid.simpleapi as ms def do_reduction(calibration): # load data data = ms.Load("HRP39180.RAW") # copy parameters from calibration to data ms.CopyInstrumentParameters(calibration, data) # Now move component on data workspace using a relative move, where that component was a detector in the calibrated workspace ms.MoveInstrumentComponent(data, DetectorID=1100,X=0.0,Y=0.0,Z=5.0,RelativePosition=True) return data.getDetector(0).getPos() #### # load calibration calibration = ms.Load("HRP38094Calib") self.det_pos_first_run = do_reduction(calibration) # again not reloading of calibration self.det_pos_second_run = do_reduction(calibration)
def to_workspace(cls, candidate, ws_prefix="_"): _workspace = None if isinstance(candidate, str): candidate = ConvertToWavelength.get_first_of_coadd_ws(candidate) if isinstance(candidate, mantid.api.Workspace): _workspace = candidate elif isinstance(candidate, str): if mantid.api.AnalysisDataService.doesExist(candidate.strip()): _workspace = mantid.api.AnalysisDataService.retrieve(candidate.strip()) elif mantid.api.AnalysisDataService.doesExist(ws_prefix + str(candidate.strip())): _workspace = mantid.api.AnalysisDataService.retrieve(ws_prefix + str(candidate.strip())) else: ws_name = ws_prefix + str(candidate.strip()) msi.Load(Filename=candidate, OutputWorkspace=ws_name) _workspace = mantid.api.AnalysisDataService.retrieve(ws_name) else: raise ValueError("Unknown source item %s" % candidate) return _workspace