def _rebin(self, input_ws, output_ws, params): rebin_alg = self.createChildAlgorithm("Rebin", enableLogging=False) rebin_alg.setProperty("InputWorkspace", input_ws) rebin_alg.setProperty("OutputWorkspace", output_ws) rebin_alg.setProperty("Params", params) rebin_alg.execute() mtd.addOrReplace(output_ws, rebin_alg.getProperty("OutputWorkspace").value)
def _divide(self, lhs_ws, rhs_ws, output_ws): divide_alg = self.createChildAlgorithm("Divide", enableLogging=False) divide_alg.setProperty("LHSWorkspace", lhs_ws) divide_alg.setProperty("RHSWorkspace", rhs_ws) divide_alg.setProperty("OutputWorkspace", output_ws) divide_alg.execute() mtd.addOrReplace(output_ws, divide_alg.getProperty("OutputWorkspace").value)
def _convert_to_elasticQ(self, input_ws, output_ws=None): """ Helper function to convert the spectrum axis of a sample to ElasticQ. @param input_ws - the name of the workspace to convert from @param output_ws - the name to call the converted workspace """ if output_ws is None: output_ws = input_ws self._get_Efixed(input_ws) axis = mtd[input_ws].getAxis(1) if axis.isSpectra(): convert_axis_alg = self.createChildAlgorithm("ConvertSpectrumAxis", enableLogging=False) convert_axis_alg.setProperty("InputWorkspace", input_ws) convert_axis_alg.setProperty("Target", 'ElasticQ') convert_axis_alg.setProperty("EMode", 'Indirect') convert_axis_alg.setProperty("EFixed", self._e_fixed) convert_axis_alg.setProperty("OutputWorkspace", output_ws) convert_axis_alg.execute() mtd.addOrReplace(output_ws, convert_axis_alg.getProperty("OutputWorkspace").value) elif axis.isNumeric(): # Check that units are Momentum Transfer if axis.getUnit().unitID() != 'MomentumTransfer': raise RuntimeError('Input must have axis values of Q') self._clone_ws(input_ws, output_ws) else: raise RuntimeError('Input workspace must have either spectra or numeric axis.')
def _extract(self, input_ws, output_ws, index): extract_alg = self.createChildAlgorithm("ExtractSingleSpectrum", enableLogging = False) extract_alg.setProperty("InputWorkspace", input_ws) extract_alg.setProperty("WorkspaceIndex", index) extract_alg.setProperty("OutputWorkspace", output_ws) extract_alg.execute() mtd.addOrReplace(output_ws, extract_alg.getProperty("OutputWorkspace").value)
def _rebin_ws(self, rebin_ws, match_ws, output_ws): rebin_ws_alg = self.createChildAlgorithm("RebinToWorkspace", enableLogging=False) rebin_ws_alg.setProperty("WorkspaceToRebin", rebin_ws) rebin_ws_alg.setProperty("WorkspaceToMatch", match_ws) rebin_ws_alg.setProperty("OutputWorkspace", output_ws) rebin_ws_alg.execute() mtd.addOrReplace(output_ws, rebin_ws_alg.getProperty("OutputWorkspace").value)
def _multiply(self, lhs_ws, rhs_ws, output_ws): multiply_alg = self.createChildAlgorithm("Multiply", enableLogging=False) multiply_alg.setProperty("LHSWorkspace", lhs_ws) multiply_alg.setProperty("RHSWorkspace", rhs_ws) multiply_alg.setProperty("OutputWorkspace", output_ws) multiply_alg.execute() mtd.addOrReplace(output_ws, multiply_alg.getProperty("OutputWorkspace").value)
def _append(self, input1_ws, input2_ws, output_ws): append_alg = self.createChildAlgorithm("AppendSpectra", enableLogging = False) append_alg.setProperty("InputWorkspace1", input1_ws) append_alg.setProperty("InputWorkspace2", input2_ws) append_alg.setProperty("OutputWorkspace", output_ws) append_alg.execute() mtd.addOrReplace(output_ws, append_alg.getProperty("OutputWorkspace").value)
def add_directory_structure(dirs): """ create the nested WorkspaceGroup structure in the ADS specified by the stored directory attribute. dirs = ["dir1", "dir2"] eg. ['Muon Data', 'MUSR72105', 'MUSR72105 Raw Data'] """ if not dirs: return if len(dirs) > len(set(dirs)): raise ValueError("Group names must be unique") for directory in dirs: if not mtd.doesExist(directory): workspace_group = api.WorkspaceGroup() mtd.addOrReplace(directory, workspace_group) elif not isinstance(mtd[directory], api.WorkspaceGroup): mtd.remove(directory) workspace_group = api.WorkspaceGroup() mtd.addOrReplace(directory, workspace_group) else: # exists and is a workspace group pass # Create the nested group structure in the ADS previous_dir = "" for i, directory in enumerate(dirs): if i == 0: previous_dir = directory continue mtd[previous_dir].add(directory) previous_dir = directory
def _plus(self, lhs_ws, rhs_ws, output_ws): plus_alg = self.createChildAlgorithm("Plus", enableLogging=False) plus_alg.setProperty("LHSWorkspace", lhs_ws) plus_alg.setProperty("RHSWorkspace", rhs_ws) plus_alg.setProperty("OutputWorkspace", output_ws) plus_alg.execute() mtd.addOrReplace(output_ws, plus_alg.getProperty("OutputWorkspace").value)
def show(self, name=''): """ Show the workspace in the ADS inside the WorkspaceGroup structure specified in name name = dirs/../dirs/workspace_name """ if not self.is_hidden: return if len(name) > 0: self.name = str(name) if len(self.name) > 0 and self.is_hidden: # add workspace to ADS mtd.addOrReplace(self._workspace_name, self._workspace) if self._directory_structure != "": self.add_directory_structure() # Add to the appropriate group group = self._directory_structure.split("/")[-1] mtd[group].add(self._workspace_name) self._workspace = None self._is_in_ads = True else: raise ValueError("Cannot store workspace in ADS with name : ", str(name))
def _crop_ws(self, input_ws, output_ws, xmin, xmax): crop_alg = self.createChildAlgorithm("CropWorkspace", enableLogging=False) crop_alg.setProperty("InputWorkspace", input_ws) crop_alg.setProperty("OutputWorkspace", output_ws) crop_alg.setProperty("XMin", xmin) crop_alg.setProperty("XMax", xmax) crop_alg.execute() mtd.addOrReplace(output_ws, crop_alg.getProperty("OutputWorkspace").value)
def _scale_x(self, input_ws, output_ws, factor): scale_x_alg = self.createChildAlgorithm("ScaleX", enableLogging=False) scale_x_alg.setProperty("InputWorkspace", input_ws) scale_x_alg.setProperty("OutputWorkspace", output_ws) scale_x_alg.setProperty("Factor", factor) scale_x_alg.setProperty("Operation", 'Add') scale_x_alg.execute() mtd.addOrReplace(output_ws, scale_x_alg.getProperty("OutputWorkspace").value)
def _copy_log(self, input_name, output_name): copy_log_alg = self.createChildAlgorithm("CopyLogs", enableLogging=False) copy_log_alg.setProperty("InputWorkspace", input_name) copy_log_alg.setProperty("OutputWorkspace", output_name) copy_log_alg.execute() mtd.addOrReplace(output_name, copy_log_alg.getProperty("OutputWorkspace").value)
def _rename_workspace(self, input_name, output_name): rename_alg = self.createChildAlgorithm("RenameWorkspace", enableLogging=False) rename_alg.setProperty("InputWorkspace", input_name) rename_alg.setProperty("OutputWorkspace", output_name) rename_alg.execute() mtd.addOrReplace(output_name, rename_alg.getProperty("OutputWorkspace").value)
def _append(self, input1_ws, input2_ws, output_ws): append_alg = self.createChildAlgorithm("AppendSpectra", enableLogging=False) append_alg.setProperty("InputWorkspace1", input1_ws) append_alg.setProperty("InputWorkspace2", input2_ws) append_alg.setProperty("OutputWorkspace", output_ws) append_alg.execute() mtd.addOrReplace(output_ws, append_alg.getProperty("OutputWorkspace").value)
def _extract(self, input_ws, index, output_ws): extract_alg = self.createChildAlgorithm("ExtractSingleSpectrum", enableLogging=False) extract_alg.setProperty("InputWorkspace", input_ws) extract_alg.setProperty("WorkspaceIndex", index) extract_alg.setProperty("OutputWorkspace", output_ws) extract_alg.execute() mtd.addOrReplace(output_ws, extract_alg.getProperty("OutputWorkspace").value)
def _spline_interp(self, match_ws, interp_ws, output_ws, deriv_ws, order): spline_interp_alg = self.createChildAlgorithm("SplineInterpolation", enableLogging = False) spline_interp_alg.setProperty("WorkspaceToMatch", match_ws) spline_interp_alg.setProperty("WorkspaceToInterpolate", interp_ws) spline_interp_alg.setProperty("OutputWorkspace", output_ws) spline_interp_alg.setProperty("OutputWorkspaceDeriv", deriv_ws) spline_interp_alg.setProperty("DerivOrder", order) spline_interp_alg.execute() mtd.addOrReplace(output_ws, spline_interp_alg.getProperty("OutputWorkspace").value)
def _append_to(self, initial_workspace, to_append): append_alg = self.createChildAlgorithm("AppendSpectra", enableLogging=False) append_alg.setProperty("InputWorkspace1", initial_workspace) append_alg.setProperty("InputWorkspace2", to_append) append_alg.setProperty("OutputWorkspace", initial_workspace) append_alg.execute() mtd.addOrReplace(initial_workspace, append_alg.getProperty("OutputWorkspace").value)
def _convert_to_histogram(self, workspace_name): convert_to_hist_alg = self.createChildAlgorithm("ConvertToHistogram", enableLogging=False) convert_to_hist_alg.setProperty("InputWorkspace", workspace_name) convert_to_hist_alg.setProperty("OutputWorkspace", workspace_name) convert_to_hist_alg.execute() mtd.addOrReplace( workspace_name, convert_to_hist_alg.getProperty("OutputWorkspace").value)
def _crop_workspace(self, input_name, output_name, x_min, x_max): crop_alg = self.createChildAlgorithm("CropWorkspace", enableLogging=False) crop_alg.setProperty("InputWorkspace", input_name) crop_alg.setProperty("OutputWorkspace", output_name) crop_alg.setProperty("XMin", x_min) crop_alg.setProperty("XMax", x_max) crop_alg.execute() mtd.addOrReplace(output_name, crop_alg.getProperty("OutputWorkspace").value)
def _process_indirect_fit_parameters(self, input_name, column_x, x_unit, parameter_names, output_name): pifp_alg = self.createChildAlgorithm("ProcessIndirectFitParameters", enableLogging=False) pifp_alg.setProperty("InputWorkspace", input_name) pifp_alg.setProperty("ColumnX", column_x) pifp_alg.setProperty("XAxisUnit", x_unit) pifp_alg.setProperty("ParameterNames", parameter_names) pifp_alg.setProperty("OutputWorkspace", output_name) pifp_alg.execute() self._result_ws = pifp_alg.getProperty("OutputWorkspace").value mtd.addOrReplace(self._result_name, pifp_alg.getProperty("OutputWorkspace").value)
def PyExec(self): setup_prog = Progress(self, start=0.05, end=0.95, nreports=3) self._tmp_fit_name = "__fit_ws" self._crop_ws(self._sample_ws, self._tmp_fit_name, self._e_min, self._e_max) convert_to_hist_alg = self.createChildAlgorithm("ConvertToHistogram", enableLogging=False) convert_to_hist_alg.setProperty("InputWorkspace", self._tmp_fit_name) convert_to_hist_alg.setProperty("OutputWorkspace", self._tmp_fit_name) convert_to_hist_alg.execute() mtd.addOrReplace(self._tmp_fit_name, convert_to_hist_alg.getProperty("OutputWorkspace").value) self._convert_to_elasticQ(self._tmp_fit_name) num_hist = self._sample_ws.getNumberHistograms() if self._hist_max is None: self._hist_max = num_hist - 1 setup_prog.report('Fitting 1 peak') self._fit(1) setup_prog.report('Fitting 2 peaks') self._fit(2) self._delete_ws(self._tmp_fit_name) chi_group = self._output_name + '_ChiSq' chi_ws1 = self._output_name + '_1L_ChiSq' chi_ws2 = self._output_name + '_2L_ChiSq' self._clone_ws(chi_ws1, chi_group) self._append(chi_group, chi_ws2, chi_group) ws = mtd[chi_group] ax = TextAxis.create(2) for i, x in enumerate(['1 peak', '2 peaks']): ax.setLabel(i, x) ws.replaceAxis(1, ax) self._delete_ws(chi_ws1) self._delete_ws(chi_ws2) res_group = self._output_name + '_Result' res_ws1 = self._output_name + '_1L_Result' res_ws2 = self._output_name + '_2L_Result' self._extract(res_ws1, res_group, 1) self._extract(res_ws2, '__spectrum', 1) self._append(res_group, '__spectrum', res_group) self._extract(res_ws2, '__spectrum', 3) self._append(res_group, '__spectrum', res_group) ws = mtd[res_group] ax = TextAxis.create(3) for i, x in enumerate(['fwhm.1', 'fwhm.2.1', 'fwhm.2.2']): ax.setLabel(i, x) ws.replaceAxis(1, ax) self._delete_ws(res_ws1) self._delete_ws(res_ws2) self._delete_ws(self._output_name + '_1L_Parameters') self._delete_ws(self._output_name + '_2L_Parameters')
def _convert_to_matrix_workspace(self, table_name, column_x, column_y, output_name): ctmw_alg = self.createChildAlgorithm("ConvertTableToMatrixWorkspace", enableLogging=False) ctmw_alg.setProperty("InputWorkspace", table_name) ctmw_alg.setProperty("ColumnX", column_x) ctmw_alg.setProperty("ColumnY", column_y) ctmw_alg.setProperty("OutputWorkspace", output_name) ctmw_alg.execute() mtd.addOrReplace(output_name, ctmw_alg.getProperty("OutputWorkspace").value)
def _create_ws(self, output_ws, x, y, e): create_alg = self.createChildAlgorithm("CreateWorkspace", enableLogging = False) create_alg.setProperty("OutputWorkspace", output_ws) create_alg.setProperty("DataX", x) create_alg.setProperty("DataY", y) create_alg.setProperty("DataE", e) create_alg.setProperty("Nspec", 1) create_alg.setProperty("UnitX", 'MomentumTransfer') create_alg.setProperty("Distribution", True) create_alg.execute() mtd.addOrReplace(output_ws, create_alg.getProperty("OutputWorkspace").value) if self._type == 'angle': #_input_ws = _theta_temp unitx = mtd[output_ws].getAxis(0).setUnit("Label") unitx.setLabel('2theta', 'deg')
def collect_fit_result(wksp: Union[str, TableWorkspace], outputname: str, peaks, donor: Union[str, Workspace2D] = None, infotype: str = 'centre', chisq_max: float = 1.e4): """ Extracts different information about fit results from a TableWorkspace and places into a Workspace2D This assumes that the input is sorted by wsindex then peakindex :param wksp: Input TableWorkspace from PDCalibration or FitPeaks (should have infotype as a column) :param outputname: Name of output Workspace2D created :param peaks: Array of peak positions :param donor: Optional Workspace2D to use to determine output size :param infotype: Type of fit information to extract ("centre", "width", "height", or "intensity") :param chisq_max: Max chisq value that should be included in output, data gets set to nan if above this :return: Created Workspace2D with infotype extracted from wksp """ KNOWN_COLUMNS = ['centre', 'width', 'height', 'intensity'] if infotype not in KNOWN_COLUMNS: raise ValueError(f'Do not know how to extract "{infotype}"') wksp = mtd[str(wksp)] for name in KNOWN_COLUMNS + ['wsindex', 'peakindex', 'chi2']: if name not in wksp.getColumnNames(): raise RuntimeError( 'did not find column "{}" in workspace "{}"'.format( name, str(wksp))) wsindex = np.asarray(wksp.column('wsindex')) wsindex_unique = np.unique(wsindex) chi2 = np.asarray(wksp.column('chi2')) observable = np.asarray(wksp.column(infotype)) # set values to nan where the chisq is too high observable[chi2 > chisq_max] = np.nan # convert the numpy arrays to a Workspace2d numPeaks = len(peaks) if donor: numSpec = mtd[str(donor)].getNumberHistograms() else: numSpec = len(wsindex_unique) output = __create_outputws(donor, numSpec, numPeaks) for i in range(len(wsindex_unique)): start = int(np.searchsorted(wsindex, wsindex_unique[i])) i = int(i) # to be compliant with mantid API output.setX(i, peaks) output.setY(i, observable[start:start + numPeaks]) mtd.addOrReplace(outputname, output) return mtd[outputname]
def _create_ws(self, output_ws, x, y, e, nspec, names): create_alg = self.createChildAlgorithm("CreateWorkspace", enableLogging = False) create_alg.setProperty("OutputWorkspace", output_ws) create_alg.setProperty("DataX", x) create_alg.setProperty("DataY", y) create_alg.setProperty("DataE", e) create_alg.setProperty("Nspec", nspec) create_alg.setProperty("UnitX", 'MomentumTransfer') create_alg.setProperty("VerticalAxisUnit", 'Text') create_alg.setProperty("VerticalAxisValues", names) create_alg.setProperty("Distribution", True) create_alg.execute() mtd.addOrReplace(output_ws, create_alg.getProperty("OutputWorkspace").value) unitx = mtd[output_ws].getAxis(0).setUnit("Label") unitx.setLabel('2theta', 'deg')
def _plot_peak_by_log_value(self, input_string, function, start_x, end_x, fit_type, minimizer, max_iterations, output_name, create_output=True, composite_members=True, convolve_members=True): plot_alg = self.createChildAlgorithm("PlotPeakByLogValue", enableLogging=False) plot_alg.setProperty("Input", input_string) plot_alg.setProperty("Function", function) plot_alg.setProperty("StartX", start_x) plot_alg.setProperty("EndX", end_x) plot_alg.setProperty("FitType", fit_type) plot_alg.setProperty("Minimizer", minimizer) plot_alg.setProperty("MaxIterations", max_iterations) plot_alg.setProperty("CreateOutput", create_output) plot_alg.setProperty("OutputCompositeMembers", composite_members) plot_alg.setProperty("ConvolveMembers", convolve_members) plot_alg.setProperty("OutputWorkspace", output_name) plot_alg.execute() mtd.addOrReplace(output_name, plot_alg.getProperty("OutputWorkspace").value)
def extract_peak_info(wksp: Union[str, Workspace2D], outputname: str, peak_position: float): """ Extract information about a single peak from a Workspace2D. The input workspace is expected to have common x-axis of observed d-spacing. The y-values and errors are extracted. The output workspace will be a single spectra with the x-axis being the detector-id. The y-values and errors are extracted from the input workspace. """ # confirm that the input is a workspace pointer wksp = mtd[str(wksp)] numSpec = wksp.getNumberHistograms() # get the index into the x/y arrays of the peak position peak_index = wksp.readX(0).searchsorted(peak_position) # create a workspace to put the result into single = WorkspaceFactory.create('Workspace2D', NVectors=1, XLength=wksp.getNumberHistograms(), YLength=wksp.getNumberHistograms()) single.setTitle('d-spacing={}\\A'.format(wksp.readX(0)[peak_index])) # get a handle to map the detector positions detids = wksp.detectorInfo().detectorIDs() have_detids = bool(len(detids) > 0) # fill in the data values x = single.dataX(0) y = single.dataY(0) e = single.dataE(0) start_detid = np.searchsorted(detids, 0) for wksp_index in range(numSpec): if have_detids: x[wksp_index] = detids[start_detid + wksp_index] else: x[wksp_index] = wksp_index y[wksp_index] = wksp.readY(wksp_index)[peak_index] e[wksp_index] = wksp.readE(wksp_index)[peak_index] # add the workspace to the AnalysisDataService mtd.addOrReplace(outputname, single) return mtd[outputname]
def collect_peaks(wksp: Union[str, TableWorkspace], outputname: str, donor: Union[str, Workspace2D] = None, infotype: str = 'strain'): """ Calculate different types of information for each peak position in wksp and create a new Workspace2D where each column is a peak position and each row is the info for each workspace index in donor :param wksp: Input TableWorkspace (i.e, dspacing table from PDCalibration) :param outputname: Name of the Workspace2D to create with the information :param donor: Name of the donor Workspace2D, used to create the shape of the output :param infotype: 'strain', 'difference', or 'dpsacing' to specify which kind of data to output :return: Created Workspace2D with fractional difference, relative difference, or dspacing values """ if infotype not in ['strain', 'difference', 'dspacing']: raise ValueError('Do not know how to calculate "{}"'.format(infotype)) wksp = mtd[str(wksp)] numSpec = int(wksp.rowCount()) peak_names = [ item for item in wksp.getColumnNames() if item not in ['detid', 'chisq', 'normchisq'] ] peaks = np.asarray([float(item[1:]) for item in peak_names]) numPeaks = len(peaks) # convert the d-space table to a Workspace2d output = __create_outputws(donor, numSpec, numPeaks) for i in range(numSpec): # TODO get the detID correct output.setX(i, peaks) if infotype == 'strain': output.setY(i, __calculate_strain(wksp.row(i), peaks)) elif infotype == 'difference': output.setY(i, __calculate_difference(wksp.row(i), peaks)) elif infotype == 'dspacing': output.setY(i, __calculate_dspacing(wksp.row(i))) else: raise ValueError(f'Do not know how to calculate {infotype}') # add the workspace to the AnalysisDataService mtd.addOrReplace(outputname, output) return mtd[outputname]
def show(self, name): """ Show the workspace in the ADS inside the WorkspaceGroup structure specified in name name = dirs/../dirs/workspace_name """ if not self.is_hidden: return if len(name) > 0 and self.is_hidden: self.name = str(name) # add workspace to ADS mtd.addOrReplace(self._workspace_name, self._workspace) if self._directory_structure != "": self.add_directory_structure() # Add to the appropriate group group = self._directory_structure.split("/")[-1] mtd[group].add(self._workspace_name) self._workspace = None self._is_in_ads = True else: raise ValueError("Cannot store workspace in ADS with name : ", str(name))
def PyExec(self): self._setup() scan_progress = Progress(self, 0.0, 0.05, 3) scan_progress.report('Running scan') scan_alg = self.createChildAlgorithm("EnergyWindowScan", 0.05, 0.95) scan_alg.setProperty('InputFiles', self._data_files) scan_alg.setProperty('LoadLogFiles', True) scan_alg.setProperty('CalibrationWorkspace', '') scan_alg.setProperty('Instrument', self._instrument_name) scan_alg.setProperty('Analyser', self._analyser) scan_alg.setProperty('Reflection', self._reflection) scan_alg.setProperty('SpectraRange', self._spectra_range) scan_alg.setProperty('ElasticRange', self._elastic_range) scan_alg.setProperty('InelasticRange', self._inelastic_range) scan_alg.setProperty('TotalRange', self._total_range) scan_alg.setProperty('DetailedBalance', Property.EMPTY_DBL) scan_alg.setProperty('GroupingMethod', 'Individual') scan_alg.setProperty('SampleEnvironmentLogName', self._sample_log_name) scan_alg.setProperty('SampleEnvironmentLogValue', self._sample_log_value) scan_alg.setProperty('MSDFit', self._msdfit) scan_alg.setProperty('ReducedWorkspace', self._output_ws) scan_alg.setProperty('ScanWorkspace', self._scan_ws) scan_alg.execute() logger.information('OutputWorkspace : %s' % self._output_ws) logger.information('ScanWorkspace : %s' % self._scan_ws) if self._widthfit: result_workspaces = list() chi_workspaces = list() temperatures = list() # Get input workspaces fit_progress = Progress(self, 0.0, 0.05, 3) input_workspace_names = mtd[self._output_ws].getNames() x = mtd[input_workspace_names[0]].readX(0) xmin = x[0] xmax = x[len(x) - 1] for input_ws in input_workspace_names: red_ws = input_ws[:-3] + 'red' # Get the sample temperature temp = self._get_temperature(red_ws) if temp is not None: temperatures.append(temp) else: # Get the run number run_no = self._get_InstrRun(input_ws)[1] run_numbers.append(run_no) num_hist = mtd[input_ws].getNumberHistograms() logger.information('Reduced histograms : %i' % num_hist) result = input_ws[:-3] + 'fit' func = 'name=Lorentzian,Amplitude=1.0,PeakCentre=0.0,FWHM=0.01' func += ',constraint=(Amplitude>0.0,FWHM>0.0)' for idx in range(num_hist): fit_progress.report('Fitting workspace: %s ; spectrum %i' % (input_ws, idx)) IndirectTwoPeakFit(SampleWorkspace=input_ws, EnergyMin=xmin, EnergyMax=xmax, Minimizer='Levenberg-Marquardt', MaxIterations=500, OutputName=result) result_workspaces.append(result + '_Result') chi_workspaces.append(result + '_ChiSq') self._group_ws(chi_workspaces, self._output_ws + '_ChiSq') logger.information('ChiSq Group Workspace : %s' % self._output_ws + '_ChiSq') self._group_ws(result_workspaces, self._output_ws + '_Result') logger.information('Result Group Workspace : %s' % self._output_ws + '_Result') fit_progress.report('Creating width Group workspace') width_name = self._output_ws + '_Width1' for index, width_ws in enumerate(result_workspaces): if index == 0: self._extract(width_ws, width_name, 0) else: self._extract(width_ws, '__spectrum', 0) self._append(width_name, '__spectrum', width_name) numb_temp = len(temperatures) x_axis_is_temp = len(input_workspace_names) == numb_temp if x_axis_is_temp: logger.information('X axis is in temperature') unit = ('Temperature', 'K') else: logger.information('X axis is in run number') unit = ('Run No', 'last 3 digits') ax = NumericAxis.create(numb_temp) for idx in range(numb_temp): if x_axis_is_temp: val = float(temperatures[idx]) else: val = float(run_numbers[idx][-3:]) ax.setValue(idx, val) mtd[width_name].replaceAxis(1, ax) mtd[width_name].setYUnitLabel("Temperature") xdat = list() ydat = list() edat = list() num_hist = mtd[width_name].getNumberHistograms() for idx in range(num_hist): x = mtd[width_name].readX(idx) y = mtd[width_name].readY(idx) e = mtd[width_name].readE(idx) if x_axis_is_temp: xdat.append(float(temperatures[idx])) else: xdat.append(float(run_numbers[idx][-3:])) ydat.append(y[5] / x[5]) edat.append(e[5] / x[5]) diffusion_workspace = self._output_ws + '_Diffusion' fit_progress.report('Creating diffusion workspace: %s' % diffusion_workspace) create_alg = self.createChildAlgorithm("CreateWorkspace", enableLogging=False) create_alg.setProperty("OutputWorkspace", diffusion_workspace) create_alg.setProperty("DataX", xdat) create_alg.setProperty("DataY", ydat) create_alg.setProperty("DataE", edat) create_alg.setProperty("NSpec", 1) create_alg.setProperty("YUnitLabel", 'Diffusion') create_alg.execute() mtd.addOrReplace(diffusion_workspace, create_alg.getProperty("OutputWorkspace").value) unitx = mtd[diffusion_workspace].getAxis(0).setUnit("Label") unitx.setLabel(unit[0], unit[1]) logger.information('Diffusion Workspace : %s' % diffusion_workspace) if self._plot: self._plot_result() if self._save: self._save_output()
def _group_ws(self, input_ws, output_ws): group_alg = self.createChildAlgorithm("GroupWorkspaces", enableLogging=False) group_alg.setProperty("InputWorkspaces", input_ws) group_alg.setProperty("OutputWorkspace", output_ws) group_alg.execute() mtd.addOrReplace(output_ws, group_alg.getProperty("OutputWorkspace").value)
def PyExec(self): progess_steps = 1. if not self._container_ws else 0.25 sample_wave_ws = self._convert_to_wavelength(self._sample_ws) self._set_beam(sample_wave_ws) # make sure there is no container defined at this point self._set_sample(sample_wave_ws, ['Sample']) monte_carlo_alg = self.createChildAlgorithm("MonteCarloAbsorption", enableLogging=True, startProgress=0, endProgress=progess_steps) self._set_algorithm_properties(monte_carlo_alg, self._monte_carlo_kwargs) monte_carlo_alg.setProperty("InputWorkspace", sample_wave_ws) monte_carlo_alg.setProperty("OutputWorkspace", self._ass_ws_name) monte_carlo_alg.setProperty("SimulateScatteringPointIn", "SampleOnly") monte_carlo_alg.execute() ass_ws = monte_carlo_alg.getProperty("OutputWorkspace").value ass_ws = self._convert_from_wavelength(ass_ws) mtd.addOrReplace(self._ass_ws_name, ass_ws) self._output_ws = self._group_ws([ass_ws]) if self._container_ws: self._set_sample(sample_wave_ws, ['Sample', 'Container']) monte_carlo_alg_ssc = self.createChildAlgorithm( "MonteCarloAbsorption", enableLogging=True, startProgress=progess_steps, endProgress=2 * progess_steps) self._set_algorithm_properties(monte_carlo_alg_ssc, self._monte_carlo_kwargs) monte_carlo_alg_ssc.setProperty("InputWorkspace", sample_wave_ws) monte_carlo_alg_ssc.setProperty("OutputWorkspace", self._assc_ws_name) monte_carlo_alg_ssc.setProperty("SimulateScatteringPointIn", "SampleOnly") monte_carlo_alg_ssc.execute() assc_ws = monte_carlo_alg_ssc.getProperty("OutputWorkspace").value assc_ws = self._convert_from_wavelength(assc_ws) mtd.addOrReplace(self._assc_ws_name, assc_ws) can_wave_ws = self._convert_to_wavelength(self._container_ws) self._set_beam(can_wave_ws) # since container can not exist without a valid sample, we work around this by setting container as sample self._set_sample(can_wave_ws, ['Container'], True) monte_carlo_alg_cc = self.createChildAlgorithm( "MonteCarloAbsorption", enableLogging=True, startProgress=2 * progess_steps, endProgress=3 * progess_steps) self._set_algorithm_properties(monte_carlo_alg_cc, self._monte_carlo_kwargs) monte_carlo_alg_cc.setProperty("InputWorkspace", can_wave_ws) monte_carlo_alg_cc.setProperty("OutputWorkspace", self._acc_ws_name) monte_carlo_alg_cc.setProperty("SimulateScatteringPointIn", "SampleOnly") monte_carlo_alg_cc.execute() acc_ws = monte_carlo_alg_cc.getProperty("OutputWorkspace").value acc_ws = self._convert_from_wavelength(acc_ws) mtd.addOrReplace(self._acc_ws_name, acc_ws) self._set_sample(can_wave_ws, ['Sample', 'Container']) monte_carlo_alg_csc = self.createChildAlgorithm( "MonteCarloAbsorption", enableLogging=True, startProgress=3 * progess_steps, endProgress=1.) self._set_algorithm_properties(monte_carlo_alg_csc, self._monte_carlo_kwargs) monte_carlo_alg_csc.setProperty("InputWorkspace", can_wave_ws) monte_carlo_alg_csc.setProperty("OutputWorkspace", self._acsc_ws_name) monte_carlo_alg_csc.setProperty("SimulateScatteringPointIn", "EnvironmentOnly") monte_carlo_alg_csc.execute() acsc_ws = monte_carlo_alg_csc.getProperty("OutputWorkspace").value acsc_ws = self._convert_from_wavelength(acsc_ws) mtd.addOrReplace(self._acsc_ws_name, acsc_ws) self._output_ws = self._group_ws( [ass_ws, assc_ws, acsc_ws, acc_ws]) self.setProperty('CorrectionsWorkspace', self._output_ws)
def _fit(self, numb): function = self._calc_function(numb) # Name stem for generated workspace self._output_workspace = self._output_name + '_%s' % (self._fit_type) logger.information('Fit workspace = '+ self._output_workspace) # Build input string for PlotPeakByLogValue num_hist = mtd[self._tmp_fit_name].getNumberHistograms() # _red file works with range(num_hist) BUT _sqw gives error when trying to do nhist+1 !!! input_str = [self._tmp_fit_name + ',i%s' % i for i in range(num_hist -1)] input_str = ';'.join(input_str) PlotPeakByLogValue(Input=input_str, OutputWorkspace=self._output_workspace, Function=function, StartX=self._e_min, EndX=self._e_max, FitType='Sequential', Minimizer=self._minimizer, MaxIterations=self._max_iterations, CreateOutput=True, OutputCompositeMembers=True, ConvolveMembers=True) # Remove unused workspaces self._delete_ws(self._output_workspace + '_NormalisedCovarianceMatrices') self._delete_ws(self._output_workspace + '_Parameters') # rename workspaces to match user input self._fit_group_name = self._output_workspace + '_Workspaces' if self._output_workspace + "_Workspaces" != self._fit_group_name: self._rename_ws(self._output_workspace + "_Workspaces", self._fit_group_name) self._parameter_name = self._output_workspace + '_Parameters' if self._output_workspace != self._parameter_name: self._rename_ws(self._output_workspace, self._parameter_name) # Create *_Result workspace if numb == 1: parameters = 'A0,Amplitude,FWHM' if self._elastic: parameters = 'A0,Amplitude,FWHM,Height' if numb == 2: parameters = 'A0,f0.Amplitude,f0.FWHM,f1.Amplitude,f1.FWHM' if self._elastic: parameters = 'A0,f0.Amplitude,f0.FWHM,f1.Amplitude,f1.FWHM,f2.Height' self._result_name = self._output_workspace + "_Result" pifp_alg = self.createChildAlgorithm("ProcessIndirectFitParameters", enableLogging=False) pifp_alg.setProperty("InputWorkspace", self._parameter_name) pifp_alg.setProperty("ColumnX", "axis-1") pifp_alg.setProperty("XAxisUnit", "MomentumTransfer") pifp_alg.setProperty("ParameterNames", parameters) pifp_alg.setProperty("OutputWorkspace", self._result_name) pifp_alg.execute() self._result_ws = pifp_alg.getProperty("OutputWorkspace").value mtd.addOrReplace(self._result_name, pifp_alg.getProperty("OutputWorkspace").value) self._transfer_sample_logs(self._result_name) chi_workspace = self._output_workspace + "_ChiSq" ctmw_alg = self.createChildAlgorithm("ConvertTableToMatrixWorkspace", enableLogging=False) ctmw_alg.setProperty("InputWorkspace", self._parameter_name) ctmw_alg.setProperty("OutputWorkspace", chi_workspace) ctmw_alg.setProperty("ColumnX", "axis-1") ctmw_alg.setProperty("ColumnY", 'Chi_squared') ctmw_alg.execute() mtd.addOrReplace(chi_workspace, ctmw_alg.getProperty("OutputWorkspace").value) self._transfer_sample_logs(chi_workspace) # Process generated workspaces wsnames = mtd[self._fit_group_name].getNames() for i, workspace in enumerate(wsnames): output_ws = self._output_workspace + '_%d_Workspace' % i self._rename_ws(workspace, output_ws) self._transfer_sample_logs(output_ws)
def _copy_log(self, input_ws, output_ws): copy_log_alg = self.createChildAlgorithm("CopyLogs", enableLogging=False) copy_log_alg.setProperty("InputWorkspace", input_ws) copy_log_alg.setProperty("OutputWorkspace", output_ws) copy_log_alg.execute() mtd.addOrReplace(output_ws, copy_log_alg.getProperty("OutputWorkspace").value)
def PyExec(self): progess_steps = 1. if not self._has_can else 0.25 input_wave_ws = self._convert_to_wavelength(self._input_ws) self._set_beam(input_wave_ws) self._sample_shape = input_wave_ws.sample().getShape() if input_wave_ws.sample().hasEnvironment(): self._sample_env = input_wave_ws.sample().getEnvironment() # make sure there is no container defined at this point self._set_sample(input_wave_ws, ['Sample']) monte_carlo_alg = self.createChildAlgorithm("MonteCarloAbsorption", enableLogging=True, startProgress=0, endProgress=progess_steps) self._set_algorithm_properties(monte_carlo_alg, self._monte_carlo_kwargs) monte_carlo_alg.setProperty("InputWorkspace", input_wave_ws) monte_carlo_alg.setProperty("OutputWorkspace", self._ass_ws_name) monte_carlo_alg.setProperty("SimulateScatteringPointIn", "SampleOnly") monte_carlo_alg.execute() ass_ws = monte_carlo_alg.getProperty("OutputWorkspace").value ass_ws = self._convert_from_wavelength(ass_ws) mtd.addOrReplace(self._ass_ws_name, ass_ws) self._output_ws = self._group_ws([ass_ws]) if self._has_can: self._set_sample(input_wave_ws, ['Sample', 'Container']) monte_carlo_alg_ssc = self.createChildAlgorithm( "MonteCarloAbsorption", enableLogging=True, startProgress=progess_steps, endProgress=2 * progess_steps) self._set_algorithm_properties(monte_carlo_alg_ssc, self._monte_carlo_kwargs) monte_carlo_alg_ssc.setProperty("InputWorkspace", input_wave_ws) monte_carlo_alg_ssc.setProperty("OutputWorkspace", self._assc_ws_name) monte_carlo_alg_ssc.setProperty("SimulateScatteringPointIn", "SampleOnly") monte_carlo_alg_ssc.execute() assc_ws = monte_carlo_alg_ssc.getProperty("OutputWorkspace").value assc_ws = self._convert_from_wavelength(assc_ws) mtd.addOrReplace(self._assc_ws_name, assc_ws) self._set_sample(input_wave_ws, ['Container']) monte_carlo_alg_cc = self.createChildAlgorithm( "MonteCarloAbsorption", enableLogging=True, startProgress=2 * progess_steps, endProgress=3 * progess_steps) self._set_algorithm_properties(monte_carlo_alg_cc, self._monte_carlo_kwargs) monte_carlo_alg_cc.setProperty("InputWorkspace", input_wave_ws) monte_carlo_alg_cc.setProperty("OutputWorkspace", self._acc_ws_name) monte_carlo_alg_cc.setProperty("SimulateScatteringPointIn", "EnvironmentOnly") monte_carlo_alg_cc.execute() acc_ws = monte_carlo_alg_cc.getProperty("OutputWorkspace").value acc_ws = self._convert_from_wavelength(acc_ws) mtd.addOrReplace(self._acc_ws_name, acc_ws) self._set_sample(input_wave_ws, ['Sample', 'Container']) monte_carlo_alg_csc = self.createChildAlgorithm( "MonteCarloAbsorption", enableLogging=True, startProgress=3 * progess_steps, endProgress=1.) self._set_algorithm_properties(monte_carlo_alg_csc, self._monte_carlo_kwargs) monte_carlo_alg_csc.setProperty("InputWorkspace", input_wave_ws) monte_carlo_alg_csc.setProperty("OutputWorkspace", self._acsc_ws_name) monte_carlo_alg_csc.setProperty("SimulateScatteringPointIn", "EnvironmentOnly") monte_carlo_alg_csc.execute() acsc_ws = monte_carlo_alg_csc.getProperty("OutputWorkspace").value acsc_ws = self._convert_from_wavelength(acsc_ws) mtd.addOrReplace(self._acsc_ws_name, acsc_ws) self._output_ws = self._group_ws( [ass_ws, assc_ws, acsc_ws, acc_ws]) self.setProperty('CorrectionsWorkspace', self._output_ws)
def _clone_ws(self, input_ws, output_ws): clone_alg = self.createChildAlgorithm("CloneWorkspace", enableLogging=False) clone_alg.setProperty("InputWorkspace", input_ws) clone_alg.setProperty("OutputWorkspace", output_ws) clone_alg.execute() mtd.addOrReplace(output_ws, clone_alg.getProperty("OutputWorkspace").value)