def test_advanced_geometry(self): # basic test that positions are approximately equal for detectors for # CNCS given advanced and basic geometry calculation routes x = scn.from_mantid(self.base_event_ws, advanced_geometry=False) y = scn.from_mantid(self.base_event_ws, advanced_geometry=True) assert np.all( np.isclose(x.coords['position'].values, y.coords['position'].values))
def test_extract_energy_inital_when_not_present(): from mantid.simpleapi import CreateSampleWorkspace from mantid.kernel import DeltaEModeType ws = CreateSampleWorkspace(StoreInADS=False) assert ws.getEMode() == DeltaEModeType.Elastic ds = scn.from_mantid(ws) assert "incident_energy" not in ds.coords
def test_attrs_with_dims(): from mantid.kernel import FloatArrayProperty import mantid.simpleapi as sapi dataX = [1, 2, 3] dataY = [1, 2, 3] ws = sapi.CreateWorkspace(DataX=dataX, DataY=dataY, NSpec=1, UnitX="Wavelength") # Time series property sapi.AddSampleLog(ws, 'attr0', LogText='1', LogType='Number Series') # Single value property sapi.AddSampleLog(ws, 'attr1', LogText='1', LogType='Number') # Array property (not time series) p = FloatArrayProperty('attr2', np.arange(10)) run = ws.mutableRun() run.addProperty('attr2', p, replace=True) ds = scn.from_mantid(ws) # Variable (single value) wrapped DataArray assert isinstance(ds.attrs['attr0'].value, sc.DataArray) assert 'time' in ds.attrs['attr0'].value.coords # Variable (single value) assert isinstance(ds.attrs['attr1'].value, int) # Variable (single value) wrapped Variable assert isinstance(ds.attrs['attr2'].value, sc.Variable) assert ds.attrs['attr2'].shape == [] # outer wrapper assert ds.attrs['attr2'].value.shape == [10] # inner held
def test_WorkspaceGroup_parsed_correctly(self): from mantid.simpleapi import (mtd, CreateSampleWorkspace, GroupWorkspaces) CreateSampleWorkspace(OutputWorkspace="ws1") CreateSampleWorkspace(OutputWorkspace="ws2") CreateSampleWorkspace(OutputWorkspace="ws3") GroupWorkspaces(InputWorkspaces="ws1,ws2,ws3", OutputWorkspace="NewGroup") converted_group = scn.from_mantid(mtd["NewGroup"]) converted_single = scn.from_mantid(mtd["ws1"]) assert len(converted_group) == 3 assert sc.identical(converted_group['ws1'], converted_single) mtd.clear()
def test_from_mask_workspace(): from mantid.simpleapi import LoadMask from os import path dir_path = path.dirname(path.realpath(__file__)) mask = LoadMask('HYS', path.join(dir_path, 'HYS_mask.xml')) da = scn.from_mantid(mask) assert da.data.dtype == sc.DType.bool assert da.dims == ['spectrum'] assert da.variances is None
def test_from_mantid_CreateWorkspace(self): import mantid.simpleapi as mantid dataX = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] dataY = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ws = mantid.CreateWorkspace(DataX=dataX, DataY=dataY, NSpec=4, UnitX="Wavelength") d = scn.from_mantid(ws) self.assertEqual(d.data.unit, sc.units.dimensionless)
def test_inelastic_unit_conversion(self): import mantid.simpleapi as mantid eventWS = self.base_event_ws ws_deltaE = mantid.ConvertUnits(eventWS, Target='DeltaE', EMode='Direct', EFixed=3) ref = scn.from_mantid(ws_deltaE) da = scn.from_mantid(eventWS) # Boost and Mantid use CODATA 2006. This test passes if we manually # change the implementation to use the old constants. Alternatively # we can correct for this by scaling L1^2 or L2^2, and this was also # confirmed in C++. Unfortunately only positions are accessible to # correct for this here, and due to precision issues with # dot/norm/sqrt this doesn't actually fix the test. We additionally # exclude low TOF region, and bump relative and absolute accepted # errors from 1e-8 to 1e-5. m_n_2006 = 1.674927211 m_n_2018 = 1.67492749804 e_2006 = 1.602176487 e_2018 = 1.602176634 scale = (m_n_2006 / m_n_2018) / (e_2006 / e_2018) da.coords['source_position'] *= np.sqrt(scale) da.coords['position'] *= np.sqrt(scale) low_tof = da.bins.constituents['data'].coords[ 'tof'] < 49000.0 * sc.units.us da.coords['incident_energy'] = 3.0 * sc.units.meV da = scn.convert(da, 'tof', 'energy_transfer', scatter=True) assert sc.all( sc.isnan(da.coords['energy_transfer']) | sc.isclose(da.coords['energy_transfer'], ref.coords['energy_transfer'], atol=1e-8 * sc.units.meV, rtol=1e-8 * sc.units.one)).value assert sc.all( low_tof | sc.isnan(da.bins.constituents['data'].coords['energy_transfer']) | sc.isclose( da.bins.constituents['data'].coords['energy_transfer'], ref.bins.constituents['data'].coords['energy_transfer'], atol=1e-5 * sc.units.meV, rtol=1e-5 * sc.units.one)).value
def absorption_correction(filename, lambda_binning=(0.7, 10.35, 5615), **mantid_args): """ This method is a straightforward wrapper exposing CylinderAbsorption through scipp CylinderAbsorption calculates an approximation of the attenuation due to absorption and single scattering in a 'cylindrical' shape. Requirements: - The instrument associated with the workspace must be fully defined. (This being a WISH-centric implementation is done with the predefined instr file) Parameters ---------- filename: Path to the file with data lambda_binning: min, max and number of steps for binning in wavelength mantid_args: additional arguments to be passed to Mantid's CylinderAbsorption method. Returns ------- Scipp dataset containing absorption correction in Wavelength units. """ # Create empty workspace with proper dimensions. workspace = simpleapi.LoadEventNexus(filename, MetaDataOnly=True, LoadMonitors=False, LoadLogs=False) workspace.getAxis(0).setUnit('Wavelength') # Rebin the resulting correction based on default WISH binning lambda_min, lambda_max, number_bins = lambda_binning bin_width = (lambda_max - lambda_min) / number_bins workspace = simpleapi.Rebin(workspace, params=[lambda_min, bin_width, lambda_max], FullBinsOnly=True) correction = simpleapi.CylinderAbsorption(workspace, **mantid_args) return scn.from_mantid(correction)
def test_extract_energy_final(): # Efinal is often stored in a non-default parameter file parameters = { 'IN16B': 'IN16B_silicon_311_Parameters.xml', 'IRIS': 'IRIS_mica_002_Parameters.xml', 'OSIRIS': 'OSIRIS_graphite_002_Parameters.xml', 'BASIS': 'BASIS_silicon_311_Parameters.xml' } unsupported = [ 'ZEEMANS', 'MARS', 'IN10', 'IN13', 'IN16', 'VISION', 'VESUVIO' ] for instr in _all_indirect(blacklist=unsupported): out = _load_indirect_instrument(instr, parameters) ds = scn.from_mantid(out) efs = ds.coords["final_energy"] assert not sc.all(sc.isnan(efs)).value assert efs.unit == sc.Unit("meV")
def test_time_series_log_extraction(): import mantid.simpleapi as sapi ws = sapi.CreateWorkspace(DataX=[0, 1], DataY=[1]) times = [ np.datetime64(t) for t in ['2021-01-01T00:00:00', '2021-01-01T00:30:00', '2021-01-01T00:50:00'] ] for i, t in enumerate(times): sapi.AddTimeSeriesLog(ws, Name='time_log', Time=str(t), Value=float(i)) da = scn.from_mantid(ws) assert da.attrs['time_log'].value.coords[ 'time'].dtype == sc.DType.datetime64 # check times assert sc.identical( sc.Variable(dims=['time'], values=np.array(times).astype('datetime64[ns]')), da.attrs['time_log'].value.coords['time']) # check values assert sc.identical(sc.Variable(dims=['time'], values=np.arange(3.)), da.attrs['time_log'].value.data) sapi.DeleteWorkspace(ws)
def test_load_mcstas_data(): import mantid.simpleapi as mantid wsg = mantid.LoadMcStas(scn.data.get_path('mcstas_sans.h5'), OutputWorkspace="test_mcstas_sans_wsg") ws = wsg[list(wsg.getNames()).index('EventData_test_mcstas_sans_wsg')] da = scn.from_mantid(ws) for i in range(ws.getNumberHistograms()): np.testing.assert_array_equal(da.coords['tof'].values, ws.readX(i)) spec = ws.getSpectrum(i) da_spec = da['tof', 0]['spectrum', i] bin_sizes = da_spec.bins.size() assert spec.getNumberEvents() == bin_sizes.value np.testing.assert_array_equal(spec.getTofs(), da_spec.bins.coords['tof'].values.values) np.testing.assert_array_equal( spec.getPulseTimesAsNumpy(), da_spec.bins.coords['pulse_time'].value.values) np.testing.assert_array_equal(spec.getWeights(), da_spec.bins.data.value.values)
from mantid.simpleapi import Load, LoadDiffCal import scippneutron as scn ws = Load('PG3_4844_event.nxs') ws = LoadDiffCal('PG3_golden.cal', InputWorkspace='ws', WorkspaceName='ws') cal = scn.from_mantid(ws[0]).rename_dims({'row': 'spectrum'}) cal['tzero'].unit = 'us' cal['difc'].unit = 'us/angstrom' cal['difa'].unit = 'us/(angstrom*angstrom)' cal.to_hdf5('PG3_4844_calibration.h5')
def test_from_mantid_LoadEmptyInstrument(self): import mantid.simpleapi as mantid ws = mantid.LoadEmptyInstrument(InstrumentName='PG3') scn.from_mantid(ws)