def _create_workspaces(self): cal=CreateSampleWorkspace(NumBanks=1,BinWidth=20000,PixelSpacing=0.1,BankPixelWidth=100) RotateInstrumentComponent(cal, ComponentName='bank1', X=1, Y=0.5, Z=2, Angle=35) MoveInstrumentComponent(cal, ComponentName='bank1', X=1, Y=1, Z=5) bkg=CloneWorkspace(cal) data=CloneWorkspace(cal) AddSampleLog(cal, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='200') AddSampleLog(bkg, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='50') AddSampleLog(data, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText='100') AddSampleLog(cal, LogName="duration", LogType='Number', NumberType='Double', LogText='20') AddSampleLog(bkg, LogName="duration", LogType='Number', NumberType='Double', LogText='5') AddSampleLog(data, LogName="duration", LogType='Number', NumberType='Double', LogText='10') def get_cal_counts(n): if n < 5000: return 0.9 else: return 1.0 def get_bkg_counts(n): return 1.5*get_cal_counts(n) def get_data_counts(n,twoTheta): tt1=30 tt2=45 return get_bkg_counts(n)+10*np.exp(-(twoTheta-tt1)**2/1)+20*np.exp(-(twoTheta-tt2)**2/0.2) for i in range(cal.getNumberHistograms()): cal.setY(i, [get_cal_counts(i)*2.0]) bkg.setY(i, [get_bkg_counts(i)/2.0]) twoTheta=data.getInstrument().getDetector(i+10000).getTwoTheta(V3D(0,0,0),V3D(0,0,1))*180/np.pi data.setY(i, [get_data_counts(i,twoTheta)]) return data, cal, bkg
def test_isCommonLogBins(self): self.assertFalse(self._test_ws.isCommonLogBins()) ws=CreateSampleWorkspace('Event') ws=Rebin(ws, '1,-1,10000') self.assertTrue(ws.isCommonLogBins()) ws=Rebin(ws, '1,-0.1,10000') self.assertTrue(ws.isCommonLogBins())
def test_computeincoherentdos(self): ws = CreateSampleWorkspace() # Will fail unless the input workspace has Q and DeltaE axes. with self.assertRaises(RuntimeError): ws_DOS = ComputeIncoherentDOS(ws) ws = CreateSampleWorkspace(XUnit = 'DeltaE') with self.assertRaises(RuntimeError): ws_DOS = ComputeIncoherentDOS(ws) # Creates a workspace with two optic phonon modes at +E and -E with Q^2 dependence and population correct for T=300K ws = self.createPhononWS(300, 5, 'DeltaE') # This should work! ws_DOS = ComputeIncoherentDOS(ws) self.assertEquals(ws_DOS.getAxis(0).getUnit().unitID(), 'DeltaE') self.assertEquals(ws_DOS.getNumberHistograms(), 1) # Checks that it works if the workspace has |Q| along x instead of y, and converts energy to wavenumber ws = Transpose(ws) ws_DOS = ComputeIncoherentDOS(ws, Temperature = 300, EnergyBinning = '-20, 0.2, 20', Wavenumbers = True) self.assertEquals(ws_DOS.getAxis(0).getUnit().unitID(), 'DeltaE_inWavenumber') self.assertEquals(ws_DOS.blocksize(), 200) # Checks that the Bose factor correction is ok. dos_eplus = np.max(ws_DOS.readY(0)[100:200]) dos_eminus = np.max(ws_DOS.readY(0)[:100]) self.assertAlmostEqual(dos_eplus / dos_eminus, 1., places=1) # Check that unit conversion from cm^-1 to meV works and also that conversion to states/meV is done ws = self.convertToWavenumber(ws) SetSampleMaterial(ws, 'Al') ws_DOSn = ComputeIncoherentDOS(ws, EnergyBinning = '-160, 1.6, 160', StatesPerEnergy = True) self.assertTrue('states' in ws_DOSn.YUnitLabel()) self.assertEquals(ws_DOSn.getAxis(0).getUnit().unitID(), 'DeltaE') material = ws.sample().getMaterial() factor = material.relativeMolecularMass() / (material.totalScatterXSection() * 1000) * 4 * np.pi self.assertAlmostEqual(np.max(ws_DOSn.readY(0)) / (np.max(ws_DOS.readY(0))*factor), 1., places=1)
def test_SampleLogs(self): ws = CreateSampleWorkspace(NumBanks=1, BankPixelWidth=1) ws.mutableRun().addProperty('a', 7, True) ws.mutableRun().addProperty('b.c', 13, True) logs = directtools.SampleLogs(ws) self.assertTrue(hasattr(logs, 'a')) self.assertEqual(logs.a, 7) self.assertTrue(hasattr(logs, 'b')) self.assertTrue(hasattr(logs.b, 'c')) self.assertEqual(logs.b.c, 13)
def test_non_scanning_case(self): input_ws = CreateSampleWorkspace(NumMonitors=0, NumBanks=6, BankPixelWidth=1, XMin=0, XMax=1, BinWidth=1) calibration_x = np.array([0, 0, 0, 0, 0, 0]) calibration_y = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) calibration_ws = CreateWorkspace(DataX=calibration_x, DataY=calibration_y, Nspec=calibration_y.size) calibrated_ws = ApplyDetectorScanEffCorr(input_ws, calibration_ws) for i in range(6): self.assertEquals(calibrated_ws.readY(i), input_ws.readY(i) * (i+1)) self.assertEquals(calibrated_ws.readE(i), input_ws.readE(i) * (i+1))
def test_window_deleted_correctly(self): ws = CreateSampleWorkspace() LoadInstrument(ws, InstrumentName='MARI', RewriteSpectraMap=False) p = InstrumentViewPresenter(ws) self.assert_widget_created() p.close(ws.name()) QApplication.processEvents() self.assertEqual(None, p.ads_observer) self.assert_widget_not_present("instr") self.assert_no_toplevel_widgets()
def test_simple_scanning_case(self): input_ws = CreateSampleWorkspace(NumMonitors=0, NumBanks=6, BankPixelWidth=1, XMin=0, XMax=1, BinWidth=1, NumScanPoints=2) calibration_x = np.array([0, 0, 0, 0, 0, 0]) calibration_y = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) # Note the monitors are in the wrong place doing the test workspace creation like this - but it does not affect the test. calibration_ws = CreateWorkspace(DataX=calibration_x, DataY=calibration_y, Nspec=calibration_y.size) expected = np.repeat(calibration_y, 2) calibrated_ws = ApplyDetectorScanEffCorr(input_ws, calibration_ws) for i in range(12): self.assertEquals(calibrated_ws.readY(i), input_ws.readY(i) * expected[i]) self.assertEquals(calibrated_ws.readE(i), input_ws.readE(i) * expected[i])
def test_window_deleted_correctly(self): ws = CreateSampleWorkspace() p = MatrixWorkspaceDisplay(ws) self.assert_widget_created() p.close(ws.name()) self.assert_widget_created() QApplication.processEvents() self.assertEqual(None, p.ads_observer) self.assert_widget_not_present("work") self.assert_no_toplevel_widgets()
def test_2d_scanning_workspace(self): input_ws = CreateSampleWorkspace(NumMonitors=0, NumBanks=3, BankPixelWidth=2, XMin=0, XMax=5, BinWidth=1, NumScanPoints=7) calibration_x = np.array([0,1,2,0,1,2,0,1,2,0,1,2]) calibration_y = np.arange(12) calibration_ws = CreateWorkspace(DataX=calibration_x, DataY=calibration_y, Nspec=4) calibrated_ws = ApplyDetectorScanEffCorr(input_ws, calibration_ws) tmp = Transpose(calibration_ws) tmp = tmp.extractY().flatten() to_multiply = np.repeat(tmp, 5*7) to_multiply = np.reshape(to_multiply, [7*12,5]) for det in range(7*12): for bin in range(5): self.assertEquals(calibrated_ws.readY(det)[bin], input_ws.readY(det)[bin] * to_multiply[det][bin])
def createPhononWS(self, T, en, e_units): fn = 'name=Gaussian, PeakCentre='+str(en)+', Height=1, Sigma=0.5;' fn +='name=Gaussian, PeakCentre=-'+str(en)+', Height='+str(np.exp(-en*11.6/T))+', Sigma=0.5;' ws = CreateSampleWorkspace(binWidth = 0.1, XMin = -25, XMax = 25, XUnit = e_units, Function = 'User Defined', UserDefinedFunction=fn) LoadInstrument(ws, InstrumentName='MARI', RewriteSpectraMap = True) with self.assertRaises(RuntimeError): ws_DOS = ComputeIncoherentDOS(ws) ws = SofQW(ws, [0, 0.05, 8], 'Direct', 25) qq = np.arange(0, 8, 0.05)+0.025 for i in range(ws.getNumberHistograms()): ws.setY(i, ws.readY(i)*qq[i]**2) ws.setE(i, ws.readE(i)*qq[i]**2) return ws
def test_execute_single_with_solid_angle(self): alg = AlgorithmManager.create("DetectorFloodWeighting") alg.setChild(True) alg.initialize() alg.setProperty("SolidAngleCorrection", True) signal_value = 2 in_ws = CreateSampleWorkspace(NumBanks=1, XUnit="Wavelength") alg.setProperty("InputWorkspace", in_ws) bands = [1,10] alg.setProperty("Bands", bands) # One band alg.setPropertyValue("OutputWorkspace", "dummy") alg.execute() out_ws = alg.getProperty("OutputWorkspace").value self.assertEqual(1, out_ws.blocksize()) self.assertEqual("Wavelength", out_ws.getAxis(0).getUnit().unitID()) self.assertEqual(in_ws.getNumberHistograms(), out_ws.getNumberHistograms(), msg="Number of histograms should be unchanged.")
def setUp(self): # create sample workspace self.xmin = 2123.33867005 + 4005.75 self.xmax = 2123.33867005 + 7995.75 self._input_ws = CreateSampleWorkspace(Function="User Defined", UserDefinedFunction="name=LinearBackground, \ A0=0.3;name=Gaussian, PeakCentre=8190, Height=5, Sigma=75", NumBanks=2, BankPixelWidth=1, XMin=self.xmin, XMax=self.xmax, BinWidth=10.5, BankDistanceFromSample=4.0, SourceDistanceFromSample=1.4, OutputWorkspace="ws") lognames = "wavelength,TOF1" logvalues = "6.0,2123.33867005" AddSampleLogMultiple(self._input_ws, lognames, logvalues) # create EPP table self._table = CreateEmptyTableWorkspace(OutputWorkspace="epptable") self._table.addColumn(type="double", name="PeakCentre") table_row = {'PeakCentre': 8189.5} for i in range(2): self._table.addRow(table_row)
def test_simple(self): ws_in = CreateSampleWorkspace(WorkspaceType='Event', Function='Flat background', XUnit='Momentum', XMax=10, BinWidth=0.1) ws_out = CropWorkspaceForMDNorm(InputWorkspace=ws_in, XMin=1, XMax=6) self.assertEquals(ws_out.getNumberEvents(), ws_in.getNumberEvents()/2) self.assertTrue(ws_out.getSpectrum(1).getTofs().max()<=6.) self.assertTrue(ws_out.getSpectrum(1).getTofs().min()>=1.) self.assertTrue(ws_out.run().hasProperty('MDNorm_low')) self.assertTrue(ws_out.run().hasProperty('MDNorm_high')) self.assertTrue(ws_out.run().hasProperty('MDNorm_spectra_index')) self.assertEquals(ws_out.run().getProperty('MDNorm_low').value[0],1.) self.assertEquals(ws_out.run().getProperty('MDNorm_high').value[0],6.) self.assertEquals(ws_out.run().getProperty('MDNorm_spectra_index').value[-1],ws_out.getNumberHistograms()-1)
def setUp(self): input_ws = CreateSampleWorkspace( Function="User Defined", UserDefinedFunction="name=LinearBackground, " + "A0=0.3;name=Gaussian, PeakCentre=5, Height=10, Sigma=0.3", NumBanks=2, BankPixelWidth=1, XMin=0, XMax=10, BinWidth=0.1, BankDistanceFromSample=4.0) self._input_ws = input_ws self._table = FindEPP(input_ws, OutputWorkspace="table") AddSampleLog(self._input_ws, LogName='wavelength', LogText='4.0', LogType='Number', LogUnit='Angstrom') for i in range(input_ws.getNumberHistograms()): y = input_ws.dataY(i) y.fill(0.) y[51] = 100. e = input_ws.dataE(i) e.fill(0.) e[51] = 10.
def test_observeRename_calls_renameHandle_when_set_on_ads_and_a_workspace_is_renamed( self): CreateSampleWorkspace(OutputWorkspace="ws") self.fake_class.observeRename(True) self.fake_class.renameHandle = mock.MagicMock() RenameWorkspace(InputWorkspace="ws", OutputWorkspace="ws1") self.assertEqual(self.fake_class.renameHandle.call_count, 1)
def createSampleWorkspace(self): """ Create a dummy workspace that looks like a sample run""" #create a dummy workspace function = "name=Lorentzian,Amplitude=1,PeakCentre=5,FWHM=1" ws = CreateSampleWorkspace("Histogram", Function="User Defined", UserDefinedFunction=function, XMin=0, XMax=10, BinWidth=0.01, XUnit="DeltaE") ws = ScaleX(ws, -5, "Add") #shift to center on 0 ws = ScaleX(ws, 0.1) #scale to size LoadInstrument(ws, InstrumentName='IRIS', RewriteSpectraMap=True) return ws
def setUp(self): self.working_directory = tempfile.mkdtemp() self.ws1_name = "ws1" self.project_ext = ".mtdproj" ADS.addOrReplace(self.ws1_name, CreateSampleWorkspace(OutputWorkspace=self.ws1_name)) project_saver = projectsaver.ProjectSaver(self.project_ext) project_saver.save_project(workspace_to_save=[self.ws1_name], file_name=self.working_directory)
def runTest(self): HelperTestingClass.__init__(self) ws = CreateSampleWorkspace() SliceViewer(ws) AnalysisDataService.clear() self._qapp.sendPostedEvents() self.assert_no_toplevel_widgets()
def test_observeDelete_calls_deleteHandle_when_set_on_ads_and_a_workspace_is_deleted( self): CreateSampleWorkspace(OutputWorkspace="ws") self.fake_class.observeDelete(True) self.fake_class.deleteHandle = mock.MagicMock() ADS.remove("ws") self.assertEqual(self.fake_class.deleteHandle.call_count, 1)
def test_rename_workspace_relabels_curve_if_default_label(self): ws = CreateSampleWorkspace() self.ax.plot(ws, specNum=2) expected_name = "ws: spec 2" expected_new_name = "new_name: spec 2" ws_artist = self.ax.tracked_workspaces["ws"][0] artist = ws_artist._artists[0] self.assertEqual(artist.get_label(), expected_name) self.ax.rename_workspace(new_name="new_name", old_name="ws") self.assertEqual(artist.get_label(), expected_new_name)
def test_offer_save_does_something_if_saved_is_false(self): self.project._offer_save_message_box = mock.MagicMock(return_value=QMessageBox.Yes) self.project.save = mock.MagicMock(return_value=None) # Add something to the ads so __saved is set to false CreateSampleWorkspace(OutputWorkspace="ws1") self.assertEqual(self.project.offer_save(None), False) self.assertEqual(self.project.save.call_count, 1) self.assertEqual(self.project._offer_save_message_box.call_count, 1)
def _create_workspace(self, ws_2D=True, sample=True, xAx=True, yAxSpec=True, yAxMt=True, instrument=True): """ create Workspace :param ws_2D: should workspace be 2D? :param sample: should workspace have sample logs? :param xAx: should x axis be DeltaE? :param yAxMt: should y axis be MomentumTransfer? :param yAxSpec: should y axis be SpectrumAxis? :param instrument: should workspace have a instrument? """ # Event Workspace if not ws_2D: ws = CreateSampleWorkspace("Event", "One Peak", XUnit="DeltaE") return ws if not xAx: ws = CreateWorkspace(DataX=self.data_x, DataY=self.data_y, DataE=np.sqrt(self.data_y), NSpec=1, UnitX="TOF") return ws if not instrument: ws = CreateWorkspace(DataX=self.data_x, DataY=self.data_y, DataE=np.sqrt(self.data_y), NSpec=1, UnitX="DeltaE") return ws if not yAxMt and not yAxSpec: ws = CreateWorkspace(DataX=self.data_x, DataY=self.data_y, DataE=np.sqrt(self.data_y), NSpec=1, UnitX="DeltaE") LoadInstrument(ws, True, InstrumentName="TOFTOF") ConvertSpectrumAxis(InputWorkspace=ws, OutputWorkspace=ws, Target="theta", EMode="Direct") return ws if not yAxSpec and yAxMt: ws = CreateWorkspace(DataX=self.data_x, DataY=self.data_y, DataE=np.sqrt(self.data_y), NSpec=1, UnitX="DeltaE") LoadInstrument(ws, True, InstrumentName="TOFTOF") self._add_all_sample_logs(ws) ConvertSpectrumAxis(InputWorkspace=ws, OutputWorkspace="ws2", Target ="ElasticQ", EMode="Direct") ws2 = mtd["ws2"] return ws2 if not sample: ws = CreateWorkspace(DataX=self.data_x, DataY=self.data_y, DataE=np.sqrt(self.data_y), NSpec=1, UnitX="DeltaE") LoadInstrument(ws, False, InstrumentName="TOFTOF") for i in range(ws.getNumberHistograms()): ws.getSpectrum(i).setDetectorID(i+1) return ws else: ws = CreateWorkspace(DataX=self.data_x, DataY=self.data_y, DataE=np.sqrt(self.data_y), NSpec=1, UnitX="DeltaE") LoadInstrument(ws, True, InstrumentName="TOFTOF") self._add_all_sample_logs(ws) return ws
def test_close_event(self): ws = CreateSampleWorkspace() pres = SliceViewer(ws) self.assert_widget_created() pres.view.close() pres = None QApplication.sendPostedEvents() self.assert_no_toplevel_widgets()
def test_observeAll_calls_anyChangeHandle_when_set_on_ads_clear(self): self.fake_class.observeAll(True) CreateSampleWorkspace(OutputWorkspace="ws") expected_count = 1 # Will replace first workspace ADS.clear() expected_count += 1 self.assertEqual(self.fake_class.anyChangeHandle.call_count, expected_count)
def setUp(self): self.ws_widget = WorkspaceWidget(QMainWindow()) mat_ws = CreateSampleWorkspace() table_ws = CreateEmptyTableWorkspace() group_ws = GroupWorkspaces([mat_ws, table_ws]) single_val_ws = CreateSingleValuedWorkspace(5, 6) self.w_spaces = [mat_ws, table_ws, group_ws, single_val_ws] self.ws_names = ['MatWS', 'TableWS', 'GroupWS', 'SingleValWS'] for ws_name, ws in zip(self.ws_names, self.w_spaces): self.ws_widget._ads.add(ws_name, ws)
def test_that_reset_to_default_groups_creates_correct_groups_and_pairs_for_single_period_data(self): workspace = CreateSampleWorkspace() LoadInstrument(workspace, InstrumentName="EMU", RewriteSpectraMap=True) self.context.reset_group_and_pairs_to_default(workspace, 'EMU', 'longitudanal', 1) self.assertEquals(self.context.group_names, ['fwd', 'bwd']) self.assertEquals(self.context.pair_names, ['long']) for group in self.context.groups: self.assertEquals(group.periods, [1])
def createPhononWS(self, T, en, e_units): fn = 'name=Gaussian, PeakCentre=' + str(en) + ', Height=1, Sigma=0.5;' fn += 'name=Gaussian, PeakCentre=-' + str(en) + ', Height=' + str( np.exp(-en * 11.6 / T)) + ', Sigma=0.5;' ws = CreateSampleWorkspace(binWidth=0.1, XMin=-25, XMax=25, XUnit=e_units, Function='User Defined', UserDefinedFunction=fn) LoadInstrument(ws, InstrumentName='MARI', RewriteSpectraMap=True) with self.assertRaises(RuntimeError): ws_DOS = ComputeIncoherentDOS(ws) ws = SofQW(ws, [0, 0.05, 8], 'Direct', 25) qq = np.arange(0, 8, 0.05) + 0.025 for i in range(ws.getNumberHistograms()): ws.setY(i, ws.readY(i) * qq[i]**2) ws.setE(i, ws.readE(i) * qq[i]**2) return ws
def test_no_raise_with_supported_workspace(self): ws = MockWorkspace() expected_name = "TEST_WORKSPACE" ws.name = Mock(return_value=expected_name) # no need to assert anything - if the constructor raises the test will fail MatrixWorkspaceDisplayModel(ws) ws = CreateSampleWorkspace(NumBanks=1, BankPixelWidth=4, NumEvents=10) MatrixWorkspaceDisplayModel(ws)
def test_simple(self): ws_in = CreateSampleWorkspace(WorkspaceType='Event', Function='Flat background', XUnit='Momentum', XMax=10, BinWidth=0.1) ws_out = CropWorkspaceForMDNorm(InputWorkspace=ws_in, XMin=1, XMax=6) self.assertEquals(ws_out.getNumberEvents(), ws_in.getNumberEvents() / 2) self.assertTrue(ws_out.getSpectrum(1).getTofs().max() <= 6.) self.assertTrue(ws_out.getSpectrum(1).getTofs().min() >= 1.) self.assertTrue(ws_out.run().hasProperty('MDNorm_low')) self.assertTrue(ws_out.run().hasProperty('MDNorm_high')) self.assertTrue(ws_out.run().hasProperty('MDNorm_spectra_index')) self.assertEquals(ws_out.run().getProperty('MDNorm_low').value[0], 1.) self.assertEquals(ws_out.run().getProperty('MDNorm_high').value[0], 6.) self.assertEquals( ws_out.run().getProperty('MDNorm_spectra_index').value[-1], ws_out.getNumberHistograms() - 1)
def test_is_colorbar(self): """Verify the functionality of _is_colorbar, which determines whether a set of axes is a colorbar.""" ws = CreateSampleWorkspace() fig = plt.figure() fig = functions.plot_surface([ws], fig=fig) axes = fig.get_axes() # First set of axes is the surface plot self.assertFalse(WorkbenchNavigationToolbar._is_colorbar(axes[0])) # Second set of axes is the colorbar self.assertTrue(WorkbenchNavigationToolbar._is_colorbar(axes[1]))
def test_colorbar_limits_not_default_values_on_surface_plot_with_monitor(self): ws = CreateSampleWorkspace(NumMonitors=1) fig = plt.figure() plot_surface([ws], fig=fig) ax = fig.get_axes() cmin, cmax = ax[0].collections[0].get_clim() # the colorbar limits default to +-0.1 when it can't find max and min of array self.assertNotEqual(cmax, 0.1) self.assertNotEqual(cmin, -0.1)
def setUp(self): """ Creates a sample workspace for testing. """ sample = CreateSampleWorkspace(Function='User Defined', UserDefinedFunction='name=ExpDecay,Height=1,Lifetime=6', NumBanks=5, BankPixelWidth=1, XUnit='QSquared', XMin=0.0, XMax=5.0, BinWidth=0.1) self._ws = sample
def test_observeAll_calls_anyChangeHandle_when_set_on_ads_group_updated(self): self.fake_class.observeAll(True) CreateSampleWorkspace(OutputWorkspace="ws1") expected_count = 1 CreateSampleWorkspace(OutputWorkspace="ws2") expected_count += 1 CreateSampleWorkspace(OutputWorkspace="ws3") expected_count += 1 GroupWorkspaces(InputWorkspaces="ws1,ws2", OutputWorkspace="NewGroup") # One for grouping the workspace expected_count += 1 # One for adding it to the ADS expected_count += 1 # Will update group ADS.addToGroup("NewGroup", "ws3") expected_count += 1 self.assertEqual(self.fake_class.anyChangeHandle.call_count, expected_count)
def test_plot_limits_are_not_changed_when_plotting_fit_lines_autoscale_true( self): fig, canvas, _ = self._create_and_plot_matrix_workspace() ax_limits = fig.get_axes()[0].axis() canvas.draw() widget = self._create_widget(canvas=canvas) fit_ws_name = "fit_ws" CreateSampleWorkspace(OutputWorkspace=fit_ws_name) widget.fitting_done_slot(fit_ws_name) self.assertEqual(ax_limits, fig.get_axes()[0].axis())
def test_returns_merged_name_if_present(self): state = mock.MagicMock() workspaces = ['Sample', 'Transmission', 'Direct'] monitors = ['monitor1'] reduction_package = ReductionPackage(state, workspaces, monitors) merged_workspace = CreateSampleWorkspace(Function='Flat background', NumBanks=1, BankPixelWidth=1, NumEvents=1, XMin=1, XMax=14, BinWidth=2) lab_workspace = CreateSampleWorkspace(Function='Flat background', NumBanks=1, BankPixelWidth=1, NumEvents=1, XMin=1, XMax=14, BinWidth=2) hab_workspace = CreateSampleWorkspace(Function='Flat background', NumBanks=1, BankPixelWidth=1, NumEvents=1, XMin=1, XMax=14, BinWidth=2) reduction_package.reduced_merged = merged_workspace reduction_package.reduced_lab = lab_workspace reduction_package.reduced_hab = hab_workspace reduction_packages = [reduction_package] names_to_save = get_all_names_to_save(reduction_packages) self.assertEqual(names_to_save, set(['merged_workspace']))
def test_execute_single_with_solid_angle(self): alg = AlgorithmManager.create("DetectorFloodWeighting") alg.setChild(True) alg.initialize() alg.setProperty("SolidAngleCorrection", True) signal_value = 2 in_ws = CreateSampleWorkspace(NumBanks=1, XUnit="Wavelength") alg.setProperty("InputWorkspace", in_ws) bands = [1, 10] alg.setProperty("Bands", bands) # One band alg.setPropertyValue("OutputWorkspace", "dummy") alg.execute() out_ws = alg.getProperty("OutputWorkspace").value self.assertEqual(1, out_ws.blocksize()) self.assertEqual("Wavelength", out_ws.getAxis(0).getUnit().unitID()) self.assertEqual(in_ws.getNumberHistograms(), out_ws.getNumberHistograms(), msg="Number of histograms should be unchanged.")
def runTest(self): HelperTestingClass.__init__(self) ws = CreateSampleWorkspace() pres = SliceViewer(ws) ConvertToDistribution(ws) self._qapp.sendPostedEvents() self.assert_no_toplevel_widgets() self.assertEqual(pres.ads_observer, None)
def setUp(self): ws = CreateSampleWorkspace(XUnit="Wavelength", NumBanks=1, Function="One Peak") shape = FindDetectorsInShape( Workspace=ws, ShapeXML='<infinite-cylinder id="asbsolute_scale">' '<centre x="0.0" y="0.0" z="0.0" /> <axis x="0.0" y="0.0" z="1.0" />' '<radius val="0.05" /></infinite-cylinder>') self.pixels_in_shape = len(shape)
def test_get_wksp_index_and_spec_num_error_with_none(self): """ Test getting the WorkspaceIndex and Spectrum Number for a Workspace This test checks that an error is shown when neither spectrum number nor workspace index is passed in """ ws = CreateSampleWorkspace() axis = MantidAxType.SPECTRUM # doesn't matter for this test self.assertRaises(RuntimeError, funcs._get_wksp_index_and_spec_num, ws, axis)
def _create_workspace(self, run_number, prefix='', suffix=''): name = prefix + str(run_number) + suffix ws = CreateSampleWorkspace(WorkspaceType='Histogram', NumBanks=1, NumMonitors=2, BankPixelWidth=2, XMin=200, OutputWorkspace=name) AddSampleLog(Workspace=ws, LogName='run_number', LogText=str(run_number))
def test_pcolor_mesh_from_names_gets_colorbar_scale_from_ConfigService( self, mock_ConfigService): ws = CreateSampleWorkspace() fig = pcolormesh_from_names([ws]) mock_ConfigService.getString.assert_any_call( 'plots.images.ColorBarScale') self.assertTrue( isinstance(fig.gca().images[0].colorbar.norm, matplotlib.colors.LogNorm))
def test_context_menu_correctly_disables_and_enables_overplot_options(self, mock_can_overplot): mock_can_overplot.return_value = False ws = CreateSampleWorkspace() mock_plot = mock.MagicMock() presenter = MatrixWorkspaceDisplay(ws, plot=mock_plot) view = presenter.view table = view.currentWidget() context_menu = view.setup_bin_context_menu(table) actions = context_menu.actions() self.assertEqual(actions[6].isEnabled(), False) self.assertEqual(actions[7].isEnabled(), False) mock_can_overplot.return_value = True context_menu = view.setup_bin_context_menu(table) actions = context_menu.actions() self.assertEqual(actions[6].isEnabled(), True) self.assertEqual(actions[7].isEnabled(), True) presenter.close(ws.name())
def test_context_has_expected_function_when_overplotting(self, mock_can_overplot): mock_can_overplot.return_value = True ws = CreateSampleWorkspace() mock_plot = mock.MagicMock() presenter = MatrixWorkspaceDisplay(ws, plot=mock_plot) view = presenter.view table = view.currentWidget() table.selectColumn(1) context_menu = view.setup_bin_context_menu(table) actions = context_menu.actions() # check triggering action 6 & 7 calls plot actions[6].trigger() presenter.plot.assert_called_with(mock.ANY, wksp_indices=mock.ANY, errors=False, overplot=True, plot_kwargs=mock.ANY) actions[7].trigger() presenter.plot.assert_called_with(mock.ANY, wksp_indices=mock.ANY, errors=True, overplot=True, plot_kwargs=mock.ANY) presenter.close(ws.name())
def create_hkl_ws(): hkl_ws = CreateMDWorkspace(Dimensions=3, Extents='-10,10,-9,9,-8,8', Names='A,B,C', Units='r.l.u.,r.l.u.,r.l.u.', Frames='HKL,HKL,HKL', OutputWorkspace='hkl_ws') expt_info = CreateSampleWorkspace() hkl_ws.addExperimentInfo(expt_info) SetUB(hkl_ws, 1, 1, 1, 90, 90, 90) return hkl_ws
class MatrixWorkspaceDisplayDecoderTest(GuiTest): def setUp(self): self.ws = CreateSampleWorkspace(OutputWorkspace="ws") self.decoder = MatrixWorkspaceDisplayDecoder() def test_decoder_returns_view(self): decoded_object = self.decoder.decode(MATRIXWORKSPACEDISPLAY_DICT) self.assertEqual(decoded_object.__class__, StatusBarView) self.assertEqual(decoded_object.presenter.__class__, MatrixWorkspaceDisplay) def test_decoder_returns_workspace(self): view = self.decoder.decode(MATRIXWORKSPACEDISPLAY_DICT) self.assertEqual(self.ws.name(), view.presenter.model._ws.name())
def test_binary_ops_with_workspaces_not_in_ADS(self): ws = CreateSampleWorkspace(StoreInADS=False) initialY = ws.readY(0)[0] ws_ads = CreateSampleWorkspace(StoreInADS=True) result1 = ws + ws self.assertTrue(mtd.doesExist('result1')) result2 = ws + ws_ads self.assertTrue(mtd.doesExist('result2')) result3 = ws_ads + ws self.assertTrue(mtd.doesExist('result3')) result4 = ws_ads + ws_ads self.assertTrue(mtd.doesExist('result4')) result5 = ws + 1 self.assertTrue(mtd.doesExist('result5')) result6 = 1 + ws self.assertTrue(mtd.doesExist('result6')) result7 = ws_ads + 1 self.assertTrue(mtd.doesExist('result7')) result8 = 1 + ws_ads self.assertTrue(mtd.doesExist('result8')) ws += 1 self.assertFalse(mtd.doesExist('ws')) ws_ads += 1 self.assertTrue(mtd.doesExist('ws_ads'))
def setUp(self): if self._raw_ws is None: ws = CreateSampleWorkspace() ws_mon = CreateSampleWorkspace() ws.setMonitorWorkspace(ws_mon) self.__class__._raw_ws = ws
class CorrectTOFTest(unittest.TestCase): def setUp(self): # create sample workspace self.xmin = 2123.33867005 + 4005.75 self.xmax = 2123.33867005 + 7995.75 self._input_ws = CreateSampleWorkspace(Function="User Defined", UserDefinedFunction="name=LinearBackground, \ A0=0.3;name=Gaussian, PeakCentre=8190, Height=5, Sigma=75", NumBanks=2, BankPixelWidth=1, XMin=self.xmin, XMax=self.xmax, BinWidth=10.5, BankDistanceFromSample=4.0, SourceDistanceFromSample=1.4, OutputWorkspace="ws") lognames = "wavelength,TOF1" logvalues = "6.0,2123.33867005" AddSampleLogMultiple(self._input_ws, lognames, logvalues) # create EPP table self._table = CreateEmptyTableWorkspace(OutputWorkspace="epptable") self._table.addColumn(type="double", name="PeakCentre") table_row = {'PeakCentre': 8189.5} for i in range(2): self._table.addRow(table_row) def tearDown(self): for wsname in ['ws', 'epptable']: if AnalysisDataService.doesExist(wsname): run_algorithm("DeleteWorkspace", Workspace=wsname) def testCorrection(self): # tests that correction is done properly OutputWorkspaceName = "outputws1" alg_test = run_algorithm("CorrectTOF", InputWorkspace=self._input_ws, EPPTable=self._table, OutputWorkspace=OutputWorkspaceName) self.assertTrue(alg_test.isExecuted()) wsoutput = AnalysisDataService.retrieve(OutputWorkspaceName) velocity = h/(m_n*6.0e-10) t_el = 4.0e+6/velocity t_corr = np.arange(self.xmin, self.xmax + 1.0, 10.5) + t_el - (8189.5 - 2123.33867005) self.assertTrue(np.allclose(t_corr, wsoutput.readX(0))) #sdd = 4 self.assertTrue(np.allclose(t_corr + t_el, wsoutput.readX(1))) #sdd = 8 run_algorithm("DeleteWorkspace", Workspace=wsoutput) def testGroup(self): # tests whether the group of workspaces is accepted as an input ws2 = CloneWorkspace(self._input_ws) group = GroupWorkspaces([self._input_ws, ws2]) OutputWorkspaceName = "output_wsgroup" alg_test = run_algorithm("CorrectTOF", InputWorkspace='group', EPPTable=self._table, OutputWorkspace=OutputWorkspaceName) self.assertTrue(alg_test.isExecuted()) wsoutput = AnalysisDataService.retrieve(OutputWorkspaceName) self.assertTrue(isinstance(wsoutput, WorkspaceGroup)) self.assertEqual(2, wsoutput.getNumberOfEntries()) run_algorithm("DeleteWorkspace", Workspace=group) run_algorithm("DeleteWorkspace", Workspace=wsoutput) def testConvertUnits(self): # test whether CorrectTof+ConvertUnits+ConvertToDistribution will give the same result as TOFTOFConvertTOFToDeltaE OutputWorkspaceName = "outputws1" alg_test = run_algorithm("CorrectTOF", InputWorkspace=self._input_ws, EPPTable=self._table, OutputWorkspace=OutputWorkspaceName) self.assertTrue(alg_test.isExecuted()) wscorr = AnalysisDataService.retrieve(OutputWorkspaceName) # convert units, convert to distribution alg_cu = run_algorithm("ConvertUnits", InputWorkspace=wscorr, Target='DeltaE', EMode='Direct', EFixed=2.27, OutputWorkspace=OutputWorkspaceName+'_dE') ws_dE = AnalysisDataService.retrieve(OutputWorkspaceName+'_dE') alg_cd = run_algorithm("ConvertToDistribution", Workspace=ws_dE) # create reference data for X axis tof1 = 2123.33867005 dataX = self._input_ws.readX(0) - tof1 tel = 8189.5 - tof1 factor = m_n*1e+15/eV newX = 0.5*factor*16.0*(1/tel**2 - 1/dataX**2) # compare # self.assertEqual(newX[0], ws_dE.readX(0)[0]) self.assertTrue(np.allclose(newX, ws_dE.readX(0), atol=0.01)) # create reference data for Y axis and compare to the output tof = dataX[:-1] + 5.25 newY = self._input_ws.readY(0)*tof**3/(factor*10.5*16.0) # compare self.assertTrue(np.allclose(newY, ws_dE.readY(0), rtol=0.01)) run_algorithm("DeleteWorkspace", Workspace=ws_dE) run_algorithm("DeleteWorkspace", Workspace=wscorr)
def setUp(self): self.ws = CreateSampleWorkspace(OutputWorkspace="ws") self.decoder = MatrixWorkspaceDisplayDecoder()