def test_remove_workspace_by_name_will_remove_a_fit_containing_a_specific_parameter_workspace( self): output_ws = WorkspaceFactory.create("Workspace2D", NVectors=3, YLength=5, XLength=5) table_workspace = WorkspaceFactory.createTable() output_ws_wrap1 = StaticWorkspaceWrapper("Output1", output_ws) parameter_ws_wrap1 = StaticWorkspaceWrapper("Parameter1", table_workspace) covariance_ws_wrap1 = StaticWorkspaceWrapper("Covariance1", table_workspace) output_ws_wrap2 = StaticWorkspaceWrapper("Output2", output_ws) parameter_ws_wrap2 = StaticWorkspaceWrapper("Parameter2", table_workspace) covariance_ws_wrap2 = StaticWorkspaceWrapper("Covariance2", table_workspace) fit1 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1], parameter_ws_wrap1, covariance_ws_wrap1) fit2 = FitInformation(["Input2"], "GausOsc", [output_ws_wrap2], parameter_ws_wrap2, covariance_ws_wrap2) self.fitting_context.active_fit_history = [fit1, fit2] self.fitting_context.remove_workspace_by_name("Parameter1") self.assertEqual(self.fitting_context.active_fit_history[0], fit2) self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2)
def test_that_all_latest_fits_will_return_the_two_most_recent_unique_fits( self): output_ws = WorkspaceFactory.create("Workspace2D", NVectors=3, YLength=5, XLength=5) table_workspace = WorkspaceFactory.createTable() output_ws_wrap1 = StaticWorkspaceWrapper("Output1", output_ws) parameter_ws_wrap1 = StaticWorkspaceWrapper("Parameter1", table_workspace) covariance_ws_wrap1 = StaticWorkspaceWrapper("Covariance1", table_workspace) output_ws_wrap2 = StaticWorkspaceWrapper("Output2", output_ws) parameter_ws_wrap2 = StaticWorkspaceWrapper("Parameter2", table_workspace) covariance_ws_wrap2 = StaticWorkspaceWrapper("Covariance2", table_workspace) fit1 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1], parameter_ws_wrap1, covariance_ws_wrap1) fit2 = FitInformation(["Input2"], "GausOsc", [output_ws_wrap2], parameter_ws_wrap2, covariance_ws_wrap2) fit3 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1], parameter_ws_wrap1, covariance_ws_wrap1) self.fitting_context.active_fit_history = [fit1, fit2, fit3] self.assertEqual(self.fitting_context.active_fit_history[0], fit1) self.assertEqual(self.fitting_context.active_fit_history[1], fit2) self.assertEqual(self.fitting_context.active_fit_history[2], fit3) # fit3 == fit1 and fit3 is more recent, so 'all_latest_fits' will only return the most recent unique fits. self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2) self.assertEqual(self.fitting_context.all_latest_fits()[1], fit3)
def test_fit_result_matrix_workspace_in_browser_is_viewed_when_clicked( self): from mantidqt.widgets.workspacedisplay.table.presenter import TableWorkspaceDisplay name = "ws" fig, canvas, _ = self._create_and_plot_matrix_workspace(name) property_browser = self._create_widget(canvas=canvas) property_browser.setOutputName(name) # create fake fit output results matrixWorkspace = WorkspaceFactory.Instance().create("Workspace2D", NVectors=3, YLength=5, XLength=5) AnalysisDataService.Instance().addOrReplace(name + "_Workspace", matrixWorkspace) tableWorkspace = WorkspaceFactory.createTable() AnalysisDataService.Instance().addOrReplace(name + "_Parameters", tableWorkspace) property_browser.fitting_done_slot(name + "_Workspace") wsList = property_browser.getWorkspaceList() TableWorkspaceDisplay.show_view = Mock() # click on table workspace item = wsList.item(0).text() property_browser.workspaceClicked.emit(item) self.assertEqual(1, TableWorkspaceDisplay.show_view.call_count)
def test_that_all_latest_fits_will_return_the_two_most_recent_unique_fits(self): output_ws = WorkspaceFactory.create("Workspace2D", NVectors=3, YLength=5, XLength=5) table_workspace = WorkspaceFactory.createTable() output_ws_wrap1 = StaticWorkspaceWrapper("Output1", output_ws) parameter_ws_wrap1 = StaticWorkspaceWrapper("Parameter1", table_workspace) covariance_ws_wrap1 = StaticWorkspaceWrapper("Covariance1", table_workspace) output_ws_wrap2 = StaticWorkspaceWrapper("Output2", output_ws) parameter_ws_wrap2 = StaticWorkspaceWrapper("Parameter2", table_workspace) covariance_ws_wrap2 = StaticWorkspaceWrapper("Covariance2", table_workspace) fit1 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1], parameter_ws_wrap1, covariance_ws_wrap1) fit2 = FitInformation(["Input2"], "GausOsc", [output_ws_wrap2], parameter_ws_wrap2, covariance_ws_wrap2) fit3 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1], parameter_ws_wrap1, covariance_ws_wrap1) self.fitting_context.tf_asymmetry_mode = True self.fitting_context.simultaneous_fitting_mode = True self.fitting_context.active_fit_history = [fit1, fit2, fit3] self.assertEqual(self.fitting_context.active_fit_history[0], fit1) self.assertEqual(self.fitting_context.active_fit_history[1], fit2) self.assertEqual(self.fitting_context.active_fit_history[2], fit3) self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2) self.assertEqual(self.fitting_context.all_latest_fits()[1], fit3) self.fitting_context.tf_asymmetry_mode = False self.assertEqual(self.fitting_context.active_fit_history, []) self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2) self.assertEqual(self.fitting_context.all_latest_fits()[1], fit3)
def _loadFullprofPrfFile(self, prffilename): """ Load Fullprof .prf file """ # 1. Parse the file to dictionary infodict, data = self._parseFullprofPrfFile(prffilename) # 2. Export information to table file tablews = WorkspaceFactory.createTable() tablews.addColumn("str", "Name") tablews.addColumn("double", "Value") for parname in infodict.keys(): parvalue = infodict[parname] tablews.addRow([parname, parvalue]) # 3. Export the data workspace datasize = len(data) print "Data Size = ", datasize dataws = WorkspaceFactory.create("Workspace2D", 4, datasize, datasize) for i in xrange(datasize): for j in xrange(4): dataws.dataX(j)[i] = data[i][0] dataws.dataY(j)[i] = data[i][j+1] dataws.dataE(j)[i] = 1.0 return (tablews, dataws)
def PyExec(self): """ Main Execution Body """ # 1. Setup output workspaces paramWS = WorkspaceFactory.createTable() self.setProperty("InstrumentParameterWorkspace", paramWS) hklWS = WorkspaceFactory.createTable() self.setProperty("BraggPeakParameterWorkspace", hklWS) # 2. Get Other Properties instrument = self.getProperty("Instrument") reflectionfilename = self.getPropertyValue("ReflectionsFile") irffilename = self.getPropertyValue("FullprofParameterFile") # 3. Import reflections list hkldict = self.importFullProfHKLFile(reflectionfilename) hkllist = sorted(hkldict.keys()) if _OUTPUTLEVEL == "INFORMATION": for hkl in hkllist: print "Import Peak (%d, %d, %d): FWHM = %f" % (hkl[0], hkl[1], hkl[2], hkldict[hkl]["FWHM"]) # 4. Import parameter file (.irf) peakparamsdict = self.parseFullprofPeakProfileFile(irffilename) # 5. Set up the table workspaces self.createPeakParameterWorkspace(peakparamsdict, paramWS) self.createReflectionWorkspace(hkldict, hklWS) return
def _loadFullprofPrfFile(self, prffilename): """ Load Fullprof .prf file """ # 1. Parse the file to dictionary infodict, data = self._parseFullprofPrfFile(prffilename) # 2. Export information to table file tablews = WorkspaceFactory.createTable() tablews.addColumn("str", "Name") tablews.addColumn("double", "Value") for parname in infodict.keys(): parvalue = infodict[parname] tablews.addRow([parname, parvalue]) # 3. Export the data workspace datasize = len(data) print "Data Size = ", datasize dataws = WorkspaceFactory.create("Workspace2D", 4, datasize, datasize) for i in xrange(datasize): for j in xrange(4): dataws.dataX(j)[i] = data[i][0] dataws.dataY(j)[i] = data[i][j + 1] dataws.dataE(j)[i] = 1.0 return (tablews, dataws)
def test_fit_curves_removed_when_workspaces_deleted(self): fig, canvas, _ = self._create_and_plot_matrix_workspace(name="ws") property_browser = self._create_widget(canvas=canvas) manager_mock = Mock() manager_mock.canvas = canvas observer = FigureManagerADSObserver(manager=manager_mock) # noqa: F841 for plot_diff in [True, False]: # create fake fit output results matrixWorkspace = WorkspaceFactory.Instance().create("Workspace2D", NVectors=3, YLength=5, XLength=5) tableWorkspace = WorkspaceFactory.createTable() AnalysisDataService.Instance().addOrReplace("ws_Workspace", matrixWorkspace) AnalysisDataService.Instance().addOrReplace("ws_Parameters", tableWorkspace) AnalysisDataService.Instance().addOrReplace("ws_NormalisedCovarianceMatrix", tableWorkspace) property_browser.plotDiff = Mock(return_value=plot_diff) property_browser.fitting_done_slot("ws_Workspace") if plot_diff: self.assertEqual(3, len(fig.get_axes()[0].lines)) else: self.assertEqual(2, len(fig.get_axes()[0].lines)) AnalysisDataService.Instance().remove("ws_Workspace") AnalysisDataService.Instance().remove("ws_Parameters") AnalysisDataService.Instance().remove("ws_NormalisedCovarianceMatrix") self.assertEqual(1, len(fig.get_axes()[0].lines))
def test_fit_result_workspaces_are_added_to_browser_when_fitting_done( self): name = "ws" fig, canvas, _ = self._create_and_plot_matrix_workspace(name) property_browser = self._create_widget(canvas=canvas) property_browser.setOutputName(name) # create fake fit output results matrixWorkspace = WorkspaceFactory.Instance().create("Workspace2D", NVectors=3, YLength=5, XLength=5) tableWorkspace = WorkspaceFactory.createTable() AnalysisDataService.Instance().addOrReplace(name + "_Workspace", matrixWorkspace) AnalysisDataService.Instance().addOrReplace(name + "_Parameters", tableWorkspace) AnalysisDataService.Instance().addOrReplace( name + "_NormalisedCovarianceMatrix", tableWorkspace) property_browser.fitting_done_slot(name + "_Workspace") workspaceList = property_browser.getWorkspaceList() self.assertEqual(3, workspaceList.count()) self.assertEqual(name + "_NormalisedCovarianceMatrix", workspaceList.item(0).text()) self.assertEqual(name + "_Parameters", workspaceList.item(1).text()) self.assertEqual(name + "_Workspace", workspaceList.item(2).text())
def test_that_can_add_workspaces_to_WorkspaceGroup_when_not_in_ADS(self): ws1 = WorkspaceFactory.create("Workspace2D", 2, 2, 2) ws2 = WorkspaceFactory.create("Workspace2D", 2, 2, 2) ws_group = WorkspaceGroup() ws_group.addWorkspace(ws1) ws_group.addWorkspace(ws2) self.assertEqual(ws_group.size(), 2)
def setUp(self): # patch away getting a real icon as it can hit a race condition when running tests # in parallel patcher = mock.patch('mantidqt.dialogs.spectraselectordialog.get_icon') self._mock_get_icon = patcher.start() self._mock_get_icon.return_value = QIcon() self.addCleanup(patcher.stop) if self._single_spec_ws is None: self.__class__._single_spec_ws = WorkspaceFactory.Instance().create("Workspace2D", NVectors=1, XLength=1, YLength=1) self.__class__._multi_spec_ws = WorkspaceFactory.Instance().create("Workspace2D", NVectors=200, XLength=1, YLength=1)
def setUp(self): if self._test_ws is None: self.__class__._test_ws = WorkspaceFactory.Instance().create( "Workspace2D", NVectors=2, YLength=5, XLength=5) if self._test_ws_2 is None: self.__class__._test_ws_2 = WorkspaceFactory.Instance().create( "Workspace2D", NVectors=2, YLength=5, XLength=5) AnalysisDataService.addOrReplace('test_ws', self._test_ws) AnalysisDataService.addOrReplace('test_ws_2', self._test_ws_2) self.get_spectra_selection_patcher = mock.patch('mantidqt.plotting.functions.get_spectra_selection') self.addCleanup(self.get_spectra_selection_patcher.stop) self.get_spectra_selection_mock = self.get_spectra_selection_patcher.start()
def test_adding_table_data_using_numpy(self): table = WorkspaceFactory.createTable() table.addColumn(type="int",name="index") self.assertEquals(table.columnCount(), 1) table.addColumn(type="int",name="value") self.assertEquals(table.columnCount(), 2) nextrow = [1, 10] values32 = numpy.array(nextrow).astype(numpy.int32) values64 = numpy.array(nextrow).astype(numpy.int64) table.addRow(values32) self.assertEquals(len(table), 1) insertedrow = table.row(0) self.assertEquals(1, insertedrow['index']) self.assertEquals(10, insertedrow['value']) table.addRow(values64) self.assertEquals(len(table), 2) insertedrow = table.row(1) self.assertEquals(1, insertedrow['index']) self.assertEquals(10, insertedrow['value']) incorrect_type = numpy.array(['1', '10']) self.assertRaises(TypeError, table.addRow, incorrect_type)
def test_log_names_respects_filter(self): time_series_logs = (('ts_1', (1., )), ('ts_2', (3., )), ('ts_3', [2.]), ('ts_4', [3.])) fake1 = create_test_workspace( ws_name='fake1', time_series_logs=time_series_logs[:2]) fake2 = create_test_workspace( ws_name='fake2', time_series_logs=time_series_logs[2:]) table_workspace = WorkspaceFactory.createTable() fit1 = FitInformation(mock.MagicMock(), 'func1', [StaticWorkspaceWrapper(fake1.name(), fake1)], StaticWorkspaceWrapper(fake1.name(), table_workspace), mock.MagicMock()) fit2 = FitInformation(mock.MagicMock(), 'func1', [StaticWorkspaceWrapper(fake2.name(), fake2)], StaticWorkspaceWrapper(fake2.name(), table_workspace), mock.MagicMock()) self.mock_active_fit_history = mock.PropertyMock(return_value=[fit1, fit2]) type(self.fitting_context).active_fit_history = self.mock_active_fit_history self.fitting_context.all_latest_fits = mock.MagicMock(return_value=[fit1, fit2]) self.fitting_context.add_fit(fit1) self.fitting_context.add_fit(fit2) required_logs = ('ts_2', 'ts_4') log_names = self.fitting_context.log_names( filter_fn=lambda log: log.name in required_logs) self.assertEqual(len(required_logs), len(log_names)) for name in required_logs: self.assertTrue( name in log_names, msg="{} not found in log list".format(name))
def PyExec(self): """ Main Execution Body """ warnings.warn("A message", ModuleDeprecationWarning) # 1. Get Input properties inppeakws = self.getProperty("BraggPeakParameterWorkspace").value inpzscows = self.getProperty("ZscoreWorkspace").value minpeakheight = float(self.getPropertyValue("MinimumPeakHeight")) zscorefilterstr = self.getPropertyValue("ZscoreFilter") print "Input: PeakParameterWorkspace = %s; ZscoreWorkspace = %s" % (inppeakws.name, inpzscows.name) print " Minimum peak height = %f" % (minpeakheight) print " Zscore filter: %s" % (zscorefilterstr) # 3. Parse Zscore table and peak parameters self.mPeaks = {} zscoredict = self.parseBraggPeakParameterTable(inpzscows) self.mPeaks = self.parseBraggPeakParameterTable(inppeakws) # 4. Filter by peak height self.filterByPeakHeight(minpeakheight) # 5. Filter by zscore zscorefilterdict = self.parseZscoreFilter(zscorefilterstr) self.filterByZscore(zscoredict, zscorefilterdict) # 6. Generate the output paramWS = WorkspaceFactory.createTable() self.genBraggPeakParameterWorkspace(paramWS) self.setProperty("OutputBraggPeakParameterWorkspace", paramWS) return
def setUp(self): self.results_context = ResultsContext() self.result_table_names = ["Name1", "Name2"] workspace = WorkspaceFactory.create("Workspace2D", NVectors=3, YLength=5, XLength=5) add_ws_to_ads("Name1", workspace) add_ws_to_ads("Name2", workspace)
def test_creating_a_workspace_from_another_with_different_size(self): clean = self._create_clean_workspace(nhist=2, xlength=4, ylength=3) nhist = 4 xlength = 6 ylength = 5 copy = WorkspaceFactory.create(clean, nhist, xlength, ylength) self._verify(copy, nhist, xlength, ylength)
def test_creating_a_workspace_from_another_gives_one_of_same_size(self): nhist = 2 xlength = 4 ylength = 3 clean = self._create_clean_workspace(nhist, xlength, ylength) copy = WorkspaceFactory.create(clean) self._verify(copy, nhist, xlength, ylength)
def test_create_results_table_with_logs_selected(self): workspace = WorkspaceFactory.create("Workspace2D", NVectors=3, YLength=5, XLength=5) workspace.mutableRun().addProperty("sample_temp", 50, True) workspace.mutableRun().addProperty("sample_magn_field", 2, True) _, model = create_test_model(('ws1',), 'func1', self.parameters, [StaticWorkspaceWrapper('ws1', workspace)], self.logs) selected_results = [('ws1', 0)] table = model.create_results_table(self.log_names, selected_results) expected_cols = ['workspace_name'] + self.log_names + [ 'f0.Height', 'f0.HeightError', 'f0.PeakCentre', 'f0.PeakCentreError', 'f0.Sigma', 'f0.SigmaError', 'f1.Height', 'f1.HeightError', 'f1.PeakCentre', 'f1.PeakCentreError', 'f1.Sigma', 'f1.SigmaError', 'Cost function value' ] expected_types = (TableColumnType.NoType, TableColumnType.X, TableColumnType.X, TableColumnType.Y, TableColumnType.YErr, TableColumnType.Y, TableColumnType.YErr, TableColumnType.Y, TableColumnType.YErr, TableColumnType.Y, TableColumnType.YErr, TableColumnType.Y, TableColumnType.YErr, TableColumnType.Y, TableColumnType.YErr, TableColumnType.Y) avg_log_values = 50., 2.0 expected_content = [ ('ws1_Parameters', avg_log_values[0], avg_log_values[1], self.f0_height[0], self.f0_height[1], self.f0_centre[0], self.f0_centre[1], self.f0_sigma[0], self.f0_sigma[1], self.f1_height[0], self.f1_height[1], self.f1_centre[0], self.f1_centre[1], self.f1_sigma[0], self.f1_sigma[1], self.cost_function[0]) ] self._assert_table_matches_expected(zip(expected_cols, expected_types), expected_content, table, model.results_table_name())
def test_that_get_workspace_names_to_display_from_context_only_returns_the_names_that_exist_in_the_ADS(self): self.model.context.results_context.result_table_names = self.result_table_names table_workspace = WorkspaceFactory.createTable() add_ws_to_ads("Result1", table_workspace) self.assertEqual(self.model.get_workspace_names_to_display_from_context(), ["Result1"])
def test_adding_table_data_using_numpy(self): table = WorkspaceFactory.createTable() table.addColumn(type="int", name="index") self.assertEqual(table.columnCount(), 1) table.addColumn(type="int", name="value") self.assertEqual(table.columnCount(), 2) nextrow = [1, 10] values32 = numpy.array(nextrow).astype(numpy.int32) values64 = numpy.array(nextrow).astype(numpy.int64) table.addRow(values32) self.assertEqual(len(table), 1) insertedrow = table.row(0) self.assertEqual(1, insertedrow['index']) self.assertEqual(10, insertedrow['value']) table.addRow(values64) self.assertEqual(len(table), 2) insertedrow = table.row(1) self.assertEqual(1, insertedrow['index']) self.assertEqual(10, insertedrow['value']) incorrect_type = numpy.array(['1', '10']) self.assertRaises(TypeError, table.addRow, incorrect_type)
def _createReflectionWorkspace(self, hkldict): """ Create TableWorkspace containing reflections and etc. """ # 1. Set up columns tablews = WorkspaceFactory.createTable() tablews.addColumn("int", "H") tablews.addColumn("int", "K") tablews.addColumn("int", "L") tablews.addColumn("double", "Alpha") tablews.addColumn("double", "Beta") tablews.addColumn("double", "Sigma2") tablews.addColumn("double", "Gamma") tablews.addColumn("double", "FWHM") tablews.addColumn("double", "PeakHeight") # 2. Add rows for hkl in sorted(hkldict.keys()): pardict = hkldict[hkl] tablews.addRow([ hkl[0], hkl[1], hkl[2], pardict["alpha"], pardict["beta"], pardict["sigma2"], pardict["gamma2"], pardict["FWHM"], 1.0 ]) # ENDFOR return tablews
def test_table_is_resized_correctly(self): table = WorkspaceFactory.createTable() self.assertEqual(len(table), 0) table.setRowCount(5) self.assertEqual(len(table), 5) self.assertTrue(table.addColumn(type="int", name="index")) self.assertEqual(table.columnCount(), 1)
def test_creating_a_workspace_from_another_gives_one_of_same_size(self): nhist = 2 xlength = 3 ylength = 4 clean = self._create_clean_workspace(nhist, xlength, ylength) copy = WorkspaceFactory.create(clean) self._verify(copy, nhist, xlength, ylength)
def PyExec(self): """ Main Execution Body """ # 1. Get Input properties inppeakws = self.getProperty("BraggPeakParameterWorkspace").value inpzscows = self.getProperty("ZscoreWorkspace").value minpeakheight = float(self.getPropertyValue("MinimumPeakHeight")) zscorefilterstr = self.getPropertyValue("ZscoreFilter") print "Input: PeakParameterWorkspace = %s; ZscoreWorkspace = %s" % (inppeakws.name, inpzscows.name) print " Minimum peak height = %f" % (minpeakheight) print " Zscore filter: %s" % (zscorefilterstr) # 3. Parse Zscore table and peak parameters self.mPeaks = {} zscoredict = self.parseBraggPeakParameterTable(inpzscows) self.mPeaks = self.parseBraggPeakParameterTable(inppeakws) # 4. Filter by peak height self.filterByPeakHeight(minpeakheight) # 5. Filter by zscore zscorefilterdict = self.parseZscoreFilter(zscorefilterstr) self.filterByZscore(zscoredict, zscorefilterdict) # 6. Generate the output paramWS = WorkspaceFactory.createTable() self.genBraggPeakParameterWorkspace(paramWS) self.setProperty("OutputBraggPeakParameterWorkspace", paramWS) return
def test_filling_workspace_details_multiple_workspaces_of_different_sizes(self): cropped_ws = WorkspaceFactory.Instance().create("Workspace2D", NVectors=50, XLength=1, YLength=1) for i in range(cropped_ws.getNumberHistograms()): cropped_ws.getSpectrum(i).setSpectrumNo(51 + i) dlg = SpectraSelectionDialog([cropped_ws, self._multi_spec_ws]) self.assertEqual("valid range: 51-100", dlg._ui.specNums.placeholderText()) self.assertEqual("valid range: 0-49", dlg._ui.wkspIndices.placeholderText())
def test_table_is_resized_correctly(self): table = WorkspaceFactory.createTable() self.assertEquals(len(table), 0) table.setRowCount(5) self.assertEquals(len(table), 5) self.assertTrue(table.addColumn(type="int",name="index")) self.assertEquals(table.columnCount(), 1)
def _fill_s_1d_workspace(self, s_points=None, workspace=None, protons_number=None, nucleons_number=None): """ Puts 1D S into workspace. :param protons_number: number of protons in the given type of atom :param nucleons_number: number of nucleons in the given type of atom :param s_points: dynamical factor for the given atom :param workspace: workspace to be filled with S """ if protons_number is not None: s_points = s_points * self._scale * self.get_cross_section( scattering=self._scale_by_cross_section, protons_number=protons_number, nucleons_number=nucleons_number) dim = 1 length = s_points.size wrk = WorkspaceFactory.create("Workspace2D", NVectors=dim, XLength=length + 1, YLength=length) for i in range(dim): wrk.getSpectrum(i).setDetectorID(i + 1) wrk.setX(0, self._bins) wrk.setY(0, s_points) AnalysisDataService.addOrReplace(workspace, wrk) # Set correct units on workspace self.set_workspace_units(workspace, layout="1D")
def test_fit_result_matrix_workspace_in_browser_is_viewed_when_clicked( self): if not PYQT5: self.skipTest( "MatrixWorkspaceDisplay and TableWorkspaceDisplay cannot be " "imported in qt4 so the test fails with an error.") from mantidqt.widgets.workspacedisplay.matrix.presenter import MatrixWorkspaceDisplay name = "ws" fig, canvas = self._create_and_plot_matrix_workspace(name) property_browser = self._create_widget(canvas=canvas) property_browser.setOutputName(name) # create fake fit output results matrixWorkspace = WorkspaceFactory.Instance().create("Workspace2D", NVectors=3, YLength=5, XLength=5) AnalysisDataService.Instance().addOrReplace(name + "_Workspace", matrixWorkspace) property_browser.fitting_done_slot(name + "_Workspace") wsList = property_browser.getWorkspaceList() # click on matrix workspace MatrixWorkspaceDisplay.show_view = Mock() item = wsList.item(0).text() property_browser.workspaceClicked.emit(item) self.assertEqual(1, MatrixWorkspaceDisplay.show_view.call_count)
def test_get_spectra_selection_removes_wrong_workspace_types_from_list( self): table = WorkspaceFactory.Instance().createTable() workspaces = [self._single_spec_ws, table] self.assertEqual( get_spectra_selection(workspaces).workspaces, [self._single_spec_ws])
def test_construction_with_non_MatrixWorkspace_type_removes_non_MatrixWorkspaces_from_list( self): table = WorkspaceFactory.Instance().createTable() workspaces = [self._single_spec_ws, table] ssd = SpectraSelectionDialog(workspaces) spectraselectordialog.RED_ASTERISK = None self.assertEqual(ssd._workspaces, [self._single_spec_ws])
def test_creating_a_workspace_from_another_with_different_size(self): clean = self._create_clean_workspace(nhist=2, xlength=3, ylength=4) nhist = 4 xlength = 5 ylength = 6 copy = WorkspaceFactory.create(clean, nhist, xlength, ylength) self._verify(copy, nhist, xlength, ylength)
def test_pcolormesh_from_names_with_non_plottable_workspaces_returns_None( self): table = WorkspaceFactory.Instance().createTable() table_name = 'test_pcolormesh_from_names_with_non_plottable_workspaces_returns_None' AnalysisDataService.Instance().addOrReplace(table_name, table) result = pcolormesh_from_names([table_name]) self.assertEqual(result, None)
def create_test_workspace(ws_name=None, time_series_logs=None, string_value_logs=None): """ Create a test workspace. :param ws_name: An optional name for the workspace :param time_series_logs: A set of (name, (values,...)) :param string_value_logs: A set of (name, value) pairs :return: The new workspace """ fake_ws = WorkspaceFactory.create('Workspace2D', 1, 1, 1) run = fake_ws.run() if time_series_logs is not None: for name, values in time_series_logs: tsp = FloatTimeSeriesProperty(name) for item in values: try: time, value = item[0], item[1] except TypeError: time, value = "2000-05-01T12:00:00", item tsp.addValue(time, value) run.addProperty(name, tsp, replace=True) if string_value_logs is not None: for name, value in string_value_logs: run.addProperty(name, StringPropertyWithValue(name, value), replace=True) ws_name = ws_name if ws_name is not None else 'fitting_context_model_test' AnalysisDataService.Instance().addOrReplace(ws_name, fake_ws) return fake_ws
def test_set_and_extract_v3d_columns(self): from mantid.kernel import V3D table = WorkspaceFactory.createTable() table.addColumn(type='V3D', name='pos') table.addRow([V3D(1, 1, 1)]) self.assertEqual(V3D(1, 1, 1), table.cell(0, 0))
def _create_test_table(self): table = WorkspaceFactory.createTable() table.addColumn(type='int', name='index') table.addColumn(type='str', name='name') table.addRow([0,'1']) table.addRow([0,'2']) table.addRow([0,'3']) return table
def test_set_and_extract_v3d_columns(self): from mantid.kernel import V3D table = WorkspaceFactory.createTable() table.addColumn(type='V3D', name='pos') table.addRow([V3D(1,1,1)]) self.assertEquals(V3D(1,1,1), table.cell(0, 0))
def _create_test_table(self): table = WorkspaceFactory.createTable() table.addColumn(type="int", name="index") table.addColumn(type="str", name="name") table.addRow([0, "1"]) table.addRow([0, "2"]) table.addRow([0, "3"]) return table
def _create_test_table(self): table = WorkspaceFactory.createTable() table.addColumn(type='int', name='index') table.addColumn(type='str', name='name') table.addRow([0, '1']) table.addRow([0, '2']) table.addRow([0, '3']) return table
def test_setting_spectra_from_array_using_incorrect_index_raises_error(self): nvectors = 2 xlength = 11 ylength = 10 test_ws = WorkspaceFactory.create("Workspace2D", nvectors, xlength, ylength) xvalues = np.arange(xlength) self.assertRaises(RuntimeError, test_ws.setX, 3, xvalues)
def test_set_and_extract_boolean_columns(self): table = WorkspaceFactory.createTable() table.addColumn(type='bool', name='yes_no') table.addRow([True]) table.addRow([False]) self.assertTrue(table.cell(0, 0)) self.assertFalse(table.cell(1, 0))
def test_setting_spectra_from_array_of_incorrect_length_raises_error(self): nvectors = 2 xlength = 11 ylength = 10 test_ws = WorkspaceFactory.create("Workspace2D", nvectors, xlength, ylength) values = np.arange(xlength + 1) self.assertRaises(ValueError, test_ws.setX, 0, values) self.assertRaises(ValueError, test_ws.setY, 0, values) self.assertRaises(ValueError, test_ws.setE, 0, values)
def runTest(self): PDLoadCharacterizations(Filename=self.char_file, OutputWorkspace='characterizations', SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0') self.wksp_mem = os.path.basename(self.data_file).split('.')[0] self.wksp_mem, self.wksp_file = self.wksp_mem + '_mem', self.wksp_mem + '_file' # load then process LoadEventAndCompress(Filename=self.data_file, OutputWorkspace=self.wksp_mem, MaxChunkSize=16, FilterBadPulses=0) LoadDiffCal(Filename=self.cal_file, InputWorkspace=self.wksp_mem, WorkspaceName='PG3') PDDetermineCharacterizations(InputWorkspace=self.wksp_mem, Characterizations='characterizations', ReductionProperties='__snspowderreduction_inner') # set-up the absorption calculation num_wl_bins = 200 prop_manager = PropertyManagerDataService.retrieve('__snspowderreduction_inner') wl_min, wl_max = prop_manager['wavelength_min'].value, prop_manager['wavelength_max'].value # 0.05, 2.20 absorptionWS = WorkspaceFactory.create(mtd[self.wksp_mem], NVectors=mtd[self.wksp_mem].getNumberHistograms(), XLength=num_wl_bins+1, YLength=num_wl_bins) xaxis = np.arange(0., float(num_wl_bins + 1)) * (wl_max - wl_min) / (num_wl_bins) + wl_min for i in range(absorptionWS.getNumberHistograms()): absorptionWS.setX(i, xaxis) absorptionWS.getAxis(0).setUnit('Wavelength') mantid.api.AnalysisDataService.addOrReplace('V_abs', absorptionWS) SetSample(InputWorkspace='V_abs', Material={'ChemicalFormula': 'V', 'SampleNumberDensity': 0.0721}, Geometry={'Shape': 'Cylinder', 'Height': 6.97, 'Radius': (0.63 / 2), 'Center': [0., 0., 0.]}) self.assertEqual(absorptionWS.getNumberBins(), num_wl_bins) # calculate the absorption CylinderAbsorption(InputWorkspace='V_abs', OutputWorkspace='V_abs', NumberOfSlices=20, NumberOfAnnuli=3) # do the work in memory ConvertUnits(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, Target='Wavelength') Divide(LHSWorkspace=self.wksp_mem, RHSWorkspace='V_abs', OutputWorkspace=self.wksp_mem) ConvertUnits(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, Target='TOF') AlignAndFocusPowder(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal', MaskWorkspace='PG3_mask', Params=-.0002, CompressTolerance=0.01, PrimaryFlightPath=60, SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0', ReductionProperties='__snspowderreduction_inner') NormaliseByCurrent(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem) ConvertUnits(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, Target='dSpacing') # everything inside the algorithm AlignAndFocusPowderFromFiles(Filename=self.data_file, OutputWorkspace=self.wksp_file, GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal', MaskWorkspace='PG3_mask', AbsorptionWorkspace='V_abs', Params=-.0002, CompressTolerance=0.01, PrimaryFlightPath=60, SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0', ReductionProperties='__snspowderreduction_inner') NormaliseByCurrent(InputWorkspace=self.wksp_file, OutputWorkspace=self.wksp_file) ConvertUnits(InputWorkspace=self.wksp_file, OutputWorkspace=self.wksp_file, Target='dSpacing')
def create_test_workspace(model, num_bins): workspace = WorkspaceFactory.create("Workspace2D", NVectors=1, XLength=num_bins, YLength=num_bins) for i in range(1, num_bins): noise = random.uniform(0.8, 1.2) x_value = i * 1.2 workspace.dataX(0)[i] = x_value workspace.dataY(0)[i] = noise * model(x_value) workspace.dataE(0)[i] = 1 return workspace
def test_setting_spectra_from_array_of_incorrect_shape_raises_error(self): nvectors = 2 xlength = 11 ylength = 10 test_ws = WorkspaceFactory.create("Workspace2D", nvectors, xlength, ylength) values = np.linspace(0,1,num=xlength-1) values = values.reshape(5,2) self.assertRaises(ValueError, test_ws.setX, 0, values) self.assertRaises(ValueError, test_ws.setY, 0, values) self.assertRaises(ValueError, test_ws.setE, 0, values)
def test_set_and_extract_vector_columns(self): table = WorkspaceFactory.createTable() table.addColumn(type='vector_int', name='values') # Settings from general Python list table.addRow([ [1,2,3,4,5] ]) # Setting from numpy array table.addRow([ numpy.array([6,7,8,9,10]) ]) self.assertTrue( numpy.array_equal( table.cell(0,0), numpy.array([1,2,3,4,5]) ) ) self.assertTrue( numpy.array_equal( table.cell(1,0), numpy.array([6,7,8,9,10]) ) )
def test_adding_table_data_using_list(self): table = WorkspaceFactory.createTable() table.addColumn(type="int",name="index") self.assertEquals(table.columnCount(), 1) table.addColumn(type="str",name="value") self.assertEquals(table.columnCount(), 2) nextrow = {'index':1, 'value':'10'} values = nextrow.values() table.addRow(nextrow) self.assertEquals(len(table), 1) insertedrow = table.row(0) self.assertEquals(insertedrow, nextrow) insertedrow = table.row(0) self.assertEquals(insertedrow, nextrow)
def test_adding_table_data_using_dictionary(self): table = WorkspaceFactory.createTable() table.addColumn(type="int",name="index") self.assertEquals(table.columnCount(), 1) table.addColumn(type="str",name="value") self.assertEquals(table.columnCount(), 2) nextrow = {'index':1, 'value':'10'} table.addRow(nextrow) self.assertEquals(len(table), 1) insertedrow = table.row(0) self.assertEquals(insertedrow, nextrow) incorrect_type = {'index':1, 'value':10} self.assertRaises(ValueError, table.addRow, incorrect_type)
def test_setxy_data_coerced_correctly_to_float64(self): nbins = 10 nspec = 2 xdata = np.arange(nbins+1) ydata = np.arange(nbins) ws = WorkspaceFactory.create("Workspace2D", NVectors=nspec, XLength=nbins+1, YLength=nbins) for i in range(nspec): ws.setX(i, xdata) ws.setY(i, ydata) # Verify x_expected, y_expected = np.vstack((xdata, xdata)), np.vstack((ydata, ydata)) x_extracted, y_extracted = ws.extractX(), ws.extractY() self.assertTrue(np.array_equal(x_expected, x_extracted)) self.assertTrue(np.array_equal(y_expected, y_extracted))
def test_setxy_accepts_python_list(self): nbins = 10 nspec = 2 xdata = list(range(nbins+1)) ydata = list(range(nbins)) ws = WorkspaceFactory.create("Workspace2D", NVectors=nspec, XLength=nbins+1, YLength=nbins) for i in range(nspec): ws.setX(i, xdata) ws.setY(i, ydata) # Verify xdata, ydata = np.array(xdata), np.array(ydata) x_expected, y_expected = np.vstack((xdata, xdata)), np.vstack((ydata, ydata)) x_extracted, y_extracted = ws.extractX(), ws.extractY() self.assertTrue(np.array_equal(x_expected, x_extracted)) self.assertTrue(np.array_equal(y_expected, y_extracted))
def test_adding_table_data_using_list(self): table = WorkspaceFactory.createTable() table.addColumn(type="int",name="index") self.assertEquals(table.columnCount(), 1) table.addColumn(type="str",name="value") self.assertEquals(table.columnCount(), 2) values = [1, '10'] table.addRow(values) self.assertEquals(len(table), 1) insertedrow = table.row(0) self.assertEquals(1, insertedrow['index']) self.assertEquals('10', insertedrow['value']) incorrect_type = [1, 10] self.assertRaises(TypeError, table.addRow, incorrect_type)
def test_pickle_table_workspace(self): from mantid.kernel import V3D import pickle table = WorkspaceFactory.createTable() table.addColumn(type="int",name="index") table.addColumn(type="str",name="value") table.addColumn(type="V3D",name="position") values = (1, '10', V3D(0, 0, 1)) table.addRow(values) values = (2, '100', V3D(1, 0, 0)) table.addRow(values) p = pickle.dumps(table) table2 = pickle.loads(p) self.assertEqual(table.toDict(), table2.toDict())
def test_set_and_extract_plot_types(self): table = WorkspaceFactory.createTable() table.addColumn("int", "index") table.addColumn("int", "value", 3) self.assertEquals(table.columnCount(), 2) self.assertEquals(table.getPlotType(0), -1000) # default plot type self.assertEquals(table.getPlotType(1), 3) table.setPlotType(0, 1) table.setPlotType("value", 2) self.assertEquals(table.getPlotType("index"), 1) self.assertEquals(table.getPlotType("value"), 2) table.addRow([1, 2]) table.addRow([3, 4]) self.assertEquals(table.rowCount(), 2)
def test_convert_to_dict(self): from mantid.kernel import V3D expected_output = { 'index': [1, 2], 'value': ['10', '100'], 'position': [V3D(0, 0, 1), V3D(1, 0, 0)] } table = WorkspaceFactory.createTable() table.addColumn(type="int",name="index") table.addColumn(type="str",name="value") table.addColumn(type="V3D",name="position") values = (1, '10', V3D(0, 0, 1)) table.addRow(values) values = (2, '100', V3D(1, 0, 0)) table.addRow(values) data = table.toDict() self.assertEquals(data, expected_output)
def test_setting_spectra_from_array_sets_expected_values(self): nvectors = 2 xlength = 11 ylength = 10 test_ws = WorkspaceFactory.create("Workspace2D", nvectors, xlength, ylength) ws_index = 1 values = np.linspace(0, 1, xlength) test_ws.setX(ws_index, values) ws_values = test_ws.readX(ws_index) self.assertTrue(np.array_equal(values, ws_values)) values = np.ones(ylength) test_ws.setY(ws_index, values) ws_values = test_ws.readY(ws_index) self.assertTrue(np.array_equal(values, ws_values)) values = np.sqrt(values) test_ws.setE(ws_index, values) ws_values = test_ws.readE(ws_index) self.assertTrue(np.array_equal(values, ws_values))
def PyExec(self): input_ws = self.getProperty("InputWorkspace").value output_ws_name = self.getProperty('OutputWorkspace').valueAsStr from_quantity = self.getProperty("From").value to_quantity = self.getProperty("To").value if input_ws.name() == output_ws_name: output_ws = input_ws else: output_ws = WorkspaceFactory.create(input_ws) self.setProperty('OutputWorkspace', output_ws) if from_quantity == to_quantity: logger.warning('The input and output functions are the same. Nothing to be done') return c = Converter() transformation = {SQ: {FQ: c.S_to_F, FKQ: c.S_to_FK, DCS: c.S_to_DCS}, FQ: {SQ: c.F_to_S, FKQ: c.F_to_FK, DCS: c.F_to_DCS}, FKQ: {SQ: c.FK_to_S, FQ: c.FK_to_F, DCS: c.FK_to_DCS}, DCS: {SQ: c.DCS_to_S, FQ: c.DCS_to_F, FKQ: c.DCS_to_FK}} if input_ws.sample().getMaterial(): sample_kwargs = {"<b_coh>^2": input_ws.sample().getMaterial().cohScatterLengthSqrd(), "<b_tot^2>": input_ws.sample().getMaterial().totalScatterLengthSqrd(), "rho": input_ws.sample().getMaterial().numberDensity} else: sample_kwargs = dict() for sp_num in range(input_ws.getNumberHistograms()): x = input_ws.readX(sp_num) output_ws.setX(sp_num, x) y = input_ws.readY(sp_num) e = input_ws.readE(sp_num) if len(x) == len(y) + 1: x = 0.5 * (x[:-1] + x[1:]) new_y, new_e = transformation[from_quantity][to_quantity](x, y, e, **sample_kwargs) output_ws.setY(sp_num, new_y) output_ws.setE(sp_num, new_e)
def _createReflectionWorkspace(self, hkldict): """ Create TableWorkspace containing reflections and etc. """ # 1. Set up columns tablews = WorkspaceFactory.createTable() tablews.addColumn("int", "H"); tablews.addColumn("int", "K"); tablews.addColumn("int", "L"); tablews.addColumn("double", "Alpha"); tablews.addColumn("double", "Beta"); tablews.addColumn("double", "Sigma2"); tablews.addColumn("double", "Gamma"); tablews.addColumn("double", "FWHM"); tablews.addColumn("double", "PeakHeight"); # 2. Add rows for hkl in sorted(hkldict.keys()): pardict = hkldict[hkl] tablews.addRow([hkl[0], hkl[1], hkl[2], pardict["alpha"], pardict["beta"], pardict["sigma2"], pardict["gamma2"], pardict["FWHM"], 1.0]) # ENDFOR return tablews
def _fill_s_1d_workspace(self, s_points=None, workspace=None, protons_number=None, nucleons_number=None): """ Puts 1D S into workspace. :param protons_number: number of protons in the given type fo atom :param nucleons_number: number of nucleons in the given type of atom :param s_points: dynamical factor for the given atom :param workspace: workspace to be filled with S """ if protons_number is not None: s_points = s_points * self._scale * self._get_cross_section(protons_number=protons_number, nucleons_number=nucleons_number) dim = 1 length = s_points.size wrk = WorkspaceFactory.create("Workspace2D", NVectors=dim, XLength=length + 1, YLength=length) for i in range(dim): wrk.getSpectrum(i).setDetectorID(i + 1) wrk.setX(0, self._bins) wrk.setY(0, s_points) AnalysisDataService.addOrReplace(workspace, wrk) # Set correct units on workspace self._set_workspace_units(wrk=workspace)