def _load_inst_parameters(self): """ Loads an empty VESUVIO instrument and attaches the necessary parameters as attributes """ isis = config.getFacility("ISIS") inst_name = "VESUVIO" inst_dir = config.getInstrumentDirectory() inst_file = os.path.join(inst_dir, inst_name + "_Definition.xml") __empty_vesuvio_ws = LoadEmptyInstrument(Filename=inst_file, EnableLogging=_LOGGING_) empty_vesuvio = __empty_vesuvio_ws.getInstrument() def to_int_list(str_param): """Return the list of numbers described by the string range""" elements = str_param.split("-") return range(int(elements[0]), int(elements[1]) + 1) # range goes x_l,x_h-1 # Attach parameters as attributes self._inst_prefix = isis.instrument(inst_name).shortName() parnames = empty_vesuvio.getParameterNames(False) for name in parnames: # Irritating parameter access doesn't let you query the type # so resort to trying try: parvalue = empty_vesuvio.getNumberParameter(name) except RuntimeError: parvalue = empty_vesuvio.getStringParameter(name) setattr(self, name, parvalue[0]) self._mon_spectra = [int(self.monitor_spectrum)] self._mon_index = self._mon_spectra[0] - 1 self._backward_spectra_list = to_int_list( self.backward_scatter_spectra) self._forward_spectra_list = to_int_list(self.forward_scatter_spectra) self._mon_scale = self.monitor_scale self._beta = self.double_diff_mixing self._tof_max = self.tof_max self._mon_tof_max = self.monitor_tof_max # Normalisation ranges def to_range_tuple(str_range): """Return a list of 2 floats giving the lower,upper range""" elements = str_range.split("-") return (float(elements[0]), float(elements[1])) self._back_mon_norm = to_range_tuple(self.backward_monitor_norm) self._back_period_sum1 = to_range_tuple(self.backward_period_sum1) self._back_period_sum2 = to_range_tuple(self.backward_period_sum2) self._back_foil_out_norm = to_range_tuple(self.backward_foil_out_norm) self._forw_mon_norm = to_range_tuple(self.forward_monitor_norm) self._forw_period_sum1 = to_range_tuple(self.forward_period_sum1) self._forw_period_sum2 = to_range_tuple(self.forward_period_sum2) self._forw_foil_out_norm = to_range_tuple(self.forward_foil_out_norm) DeleteWorkspace(__empty_vesuvio_ws, EnableLogging=_LOGGING_)
def _load_inst_parameters(self): """ Loads an empty VESUVIO instrument and attaches the necessary parameters as attributes """ isis = config.getFacility("ISIS") inst_name = "VESUVIO" inst_dir = config.getInstrumentDirectory() inst_file = os.path.join(inst_dir, inst_name + "_Definition.xml") __empty_vesuvio_ws = LoadEmptyInstrument(Filename=inst_file, EnableLogging=_LOGGING_) empty_vesuvio = __empty_vesuvio_ws.getInstrument() def to_int_list(str_param): """Return the list of numbers described by the string range""" elements = str_param.split("-") return range(int(elements[0]),int(elements[1]) + 1) # range goes x_l,x_h-1 # Attach parameters as attributes self._inst_prefix = isis.instrument(inst_name).shortName() parnames = empty_vesuvio.getParameterNames(False) for name in parnames: # Irritating parameter access doesn't let you query the type # so resort to trying try: parvalue = empty_vesuvio.getNumberParameter(name) except RuntimeError: parvalue = empty_vesuvio.getStringParameter(name) setattr(self, name, parvalue[0]) self._mon_spectra = [int(self.monitor_spectrum)] self._mon_index = self._mon_spectra[0] - 1 self._backward_spectra_list = to_int_list(self.backward_scatter_spectra) self._forward_spectra_list = to_int_list(self.forward_scatter_spectra) self._tau = self.dead_time_fraction self._mon_scale = self.monitor_scale self._beta = self.double_diff_mixing self._tof_max = self.tof_max self._mon_tof_max = self.monitor_tof_max # Normalisation ranges def to_range_tuple(str_range): """Return a list of 2 floats giving the lower,upper range""" elements = str_range.split("-") return (float(elements[0]),float(elements[1])) self._back_mon_norm = to_range_tuple(self.backward_monitor_norm) self._back_period_sum1 = to_range_tuple(self.backward_period_sum1) self._back_period_sum2 = to_range_tuple(self.backward_period_sum2) self._back_foil_out_norm = to_range_tuple(self.backward_foil_out_norm) self._forw_mon_norm = to_range_tuple(self.forward_monitor_norm) self._forw_period_sum1 = to_range_tuple(self.forward_period_sum1) self._forw_period_sum2 = to_range_tuple(self.forward_period_sum2) self._forw_foil_out_norm = to_range_tuple(self.forward_foil_out_norm) DeleteWorkspace(__empty_vesuvio_ws,EnableLogging=_LOGGING_)
def _load_param_file(self, inst_name): InstrumentParameters.instrument_name = inst_name if IS_IN_MANTIDPLOT: idf_loc = config.getInstrumentDirectory() idf_pattern = os.path.join(idf_loc, "%s_Definition*.xml") % inst_name import glob idf_files = glob.glob(idf_pattern) emptyInst = LoadEmptyInstrument(Filename=str(idf_files[0])) InstrumentParameters._instrument = emptyInst.getInstrument() AnalysisDataService.remove(str(emptyInst)) # Don't need to keep workspace
def test_get_set_matrix_workspace(self): ws = LoadEmptyInstrument(InstrumentName='ENGIN-X', OutputWorkspace='ws') LoadParameterFile(Workspace=ws, Filename='ENGIN-X_Parameters.xml') axis = ws.getAxis(0) unit = axis.getUnit() axis.setUnit("TOF") func = FunctionFactory.Instance().createPeakFunction("BackToBackExponential") func.setParameter(3, 24000) # set centre func.setMatrixWorkspace(ws, 800, 0.0, 0.0) # calculate A,B,S self.assertTrue(func.isExplicitlySet(1))
def setUp(self) -> None: # Neutron counts along a tube counts = [50, 122, 118, 197, 414, 545, 1026, 1767, 3242, 7132, 16232, 34663, 52842, 59767, 58638, 55250, 47723, 47400, 54642, 56830, 57664, 57563, 57398, 57438, 57370, 57386, 57447, 56951, 57258, 56195, 52775, 46106, 48802, 54698, 57072, 57876, 57754, 57712, 57800, 57837, 57606, 57398, 57038, 56504, 54408, 49406, 44668, 50911, 55364, 55906, 56175, 56612, 56375, 56179, 56265, 56329, 56497, 56131, 55034, 52618, 46515, 44466, 51293, 54234, 54961, 55219, 54601, 54359, 54866, 54839, 54474, 54031, 54064, 53431, 50619, 44013, 45435, 52264, 54087, 55002, 54589, 54568, 53516, 53285, 52656, 52676, 52420, 52375, 51837, 47664, 41643, 45292, 51215, 52851, 53284, 53421, 52999, 52985, 52596, 52799, 52658, 51894, 51504, 50154, 44435, 39820, 45640, 49871, 50920, 51190, 51091, 51448, 50937, 50927, 50773, 51173, 50819, 50110, 48138, 42389, 39823, 46671, 50037, 50013, 50840, 50400, 50138, 49500, 50616, 49890, 49853, 49548, 48731, 45211, 39185, 39270, 45409, 47628, 48348, 48652, 48025, 48518, 48915, 48351, 48486, 48391, 47793, 47079, 43590, 37528, 40016, 45604, 47259, 47710, 47252, 47687, 47145, 47453, 47409, 47294, 46735, 46170, 45028, 40783, 35924, 40234, 44613, 45660, 45921, 45125, 45544, 45482, 45261, 45326, 45547, 44914, 44966, 43711, 39302, 35101, 39600, 44185, 45054, 44538, 44443, 44617, 44509, 44589, 44806, 45078, 44265, 44053, 42055, 36702, 35192, 40304, 42712, 42910, 42992, 43593, 44157, 43675, 43442, 43348, 43668, 42447, 42193, 39349, 33887, 34026, 38630, 40354, 40798, 40866, 40592, 40593, 40645, 40507, 40316, 40256, 40068, 39481, 37928, 33034, 31521, 36298, 38938, 39451, 39544, 39479, 39624, 39471, 39300, 39197, 38777, 39288, 39163, 37350, 33507, 31309, 36124, 38921, 30633, 14932, 5370, 2069, 955, 545, 329, 216, 157, 82, 49, 54, 25, 10] # Calibrated Y-coordinates y = [-0.342, -0.338, -0.335, -0.331, -0.328, -0.324, -0.320, -0.317, -0.313, -0.310, -0.306, -0.303, -0.299, -0.296, -0.292, -0.289, -0.285, -0.282, -0.278, -0.275, -0.271, -0.268, -0.264, -0.261, -0.257, -0.254, -0.250, -0.247, -0.243, -0.240, -0.236, -0.232, -0.229, -0.225, -0.222, -0.218, -0.215, -0.211, -0.208, -0.204, -0.201, -0.197, -0.194, -0.190, -0.187, -0.183, -0.180, -0.176, -0.173, -0.169, -0.166, -0.162, -0.159, -0.155, -0.152, -0.148, -0.144, -0.141, -0.137, -0.134, -0.130, -0.127, -0.123, -0.120, -0.116, -0.113, -0.109, -0.106, -0.102, -0.099, -0.095, -0.092, -0.088, -0.085, -0.081, -0.078, -0.074, -0.071, -0.067, -0.064, -0.060, -0.056, -0.053, -0.049, -0.046, -0.042, -0.039, -0.035, -0.032, -0.028, -0.025, -0.021, -0.018, -0.014, -0.011, -0.007, -0.004, -0.000, 0.003, 0.007, 0.010, 0.014, 0.017, 0.021, 0.024, 0.028, 0.032, 0.035, 0.039, 0.042, 0.046, 0.049, 0.053, 0.056, 0.060, 0.063, 0.067, 0.070, 0.074, 0.077, 0.081, 0.084, 0.088, 0.091, 0.095, 0.098, 0.102, 0.105, 0.109, 0.112, 0.116, 0.120, 0.123, 0.127, 0.130, 0.134, 0.137, 0.141, 0.144, 0.148, 0.151, 0.155, 0.158, 0.162, 0.165, 0.169, 0.172, 0.176, 0.179, 0.183, 0.186, 0.190, 0.193, 0.197, 0.200, 0.204, 0.208, 0.211, 0.215, 0.218, 0.222, 0.225, 0.229, 0.232, 0.236, 0.239, 0.243, 0.246, 0.250, 0.253, 0.257, 0.260, 0.264, 0.267, 0.271, 0.274, 0.278, 0.281, 0.285, 0.288, 0.292, 0.296, 0.299, 0.303, 0.306, 0.310, 0.313, 0.317, 0.320, 0.324, 0.327, 0.331, 0.334, 0.338, 0.341, 0.345, 0.348, 0.352, 0.355, 0.359, 0.362, 0.366, 0.369, 0.373, 0.376, 0.380, 0.384, 0.387, 0.391, 0.394, 0.398, 0.401, 0.405, 0.408, 0.412, 0.415, 0.419, 0.422, 0.426, 0.429, 0.433, 0.436, 0.440, 0.443, 0.447, 0.450, 0.454, 0.457, 0.461, 0.464, 0.468, 0.472, 0.475, 0.479, 0.482, 0.486, 0.489, 0.493, 0.496, 0.500, 0.503, 0.507, 0.510, 0.514, 0.517, 0.521, 0.524, 0.528, 0.531, 0.535, 0.538, 0.542, 0.545, 0.549, 0.552, 0.556] # Create a workspace with an uncalibrated tube bank42/sixteenpack/tube8 workspace = LoadEmptyInstrument(InstrumentName='CORELLI', MakeEventWorkspace=False, OutputWorkspace='uncalibrated') # the workspace index for the first pixel in bank87/sixteenpack/tube12 is 355075 for pixel_index in range(256): workspace.dataY(355075 + pixel_index)[:] = counts[pixel_index] self.workspace = 'uncalibrated' self.table = 'calibTable' self.calibrated_y = y
def runTest(self): # apply the calibration to a reference CORELLI instrument self.ws_reference = "ws_ref" self.ws_calbrated = "ws_cal" LoadEmptyInstrument(Filename="CORELLI_Definition.xml", OutputWorkspace=self.ws_reference) ConvertToEventWorkspace(InputWorkspace=self.ws_reference, OutputWorkspace=self.ws_calbrated) self.generate_calitab() CorelliCalibrationApply(Workspace=self.ws_calbrated, CalibrationTable=self.cali_table_name) # ensure that the calibration application take place _ws_ref = mtd[self.ws_reference] _ws_cal = mtd[self.ws_calbrated] rst, _ = CompareWorkspaces(_ws_ref, _ws_cal) if rst is True: raise ValueError("The Calibration is not applied to workspace") # get the target ws self.get_target_instrument() _ws_tgt = mtd[self.ws_target] # check if the calibrated workspace matches the target rst, msg = CompareWorkspaces(_ws_tgt, _ws_cal) # NOTE: # Currently comparing the two workspace will yield False even if the implementation # is exactly the same as the C++ counter parts. # Given that this is just a place holder for more comprehensive systemtest onece # the upstream calibration algorithm is complete, we are skipping the checking here. print(msg)
def _table_to_workspace( input_workspace: Union[str, TableWorkspace], output_workspace: Optional[str] = None) -> MaskWorkspace: r""" @brief Convert a CORELLI calibration mask table to a MaskWorkspace :param input_workspace : the table containing the detector ID's for the masked detectors :param output_workspace : name of the output MaskWorkspace :return: handle to the MaskWorkspace """ table_handle = mtd[str(input_workspace)] detectors_masked = table_handle.column(0) # list of masked detectors if output_workspace is None: output_workspace = str(input_workspace) LoadEmptyInstrument(InstrumentName='CORELLI', OutputWorkspace=output_workspace) ClearMaskFlag(Workspace=output_workspace) # for good measure MaskDetectors( Workspace=output_workspace, DetectorList=detectors_masked) # output_workspace is a Workspace2D # output_workspace is converted to a MaskWorkspace, where the Y-values of the spectra are now either 0 or 1 ExtractMask(InputWorkspace=output_workspace, OutputWorkspace=output_workspace) return mtd[output_workspace]
def _create_peaks_workspace(self): """Create a dummy peaks workspace""" path = FileFinder.getFullPath( "IDFs_for_UNIT_TESTING/MINITOPAZ_Definition.xml") inst = LoadEmptyInstrument(Filename=path) ws = CreatePeaksWorkspace(inst, 0) DeleteWorkspace(inst) SetUB(ws, 1, 1, 1, 90, 90, 90) # Add a bunch of random peaks that happen to fall on the # detetor bank defined in the IDF center_q = np.array([-5.1302, 2.5651, 3.71809]) qs = [] for i in np.arange(0, 1, 0.1): for j in np.arange(-0.5, 0, 0.1): q = center_q.copy() q[1] += j q[2] += i qs.append(q) # Add the peaks to the PeaksWorkspace with dummy values for intensity, # Sigma, and HKL for q in qs: peak = ws.createPeak(q) peak.setIntensity(100) peak.setSigmaIntensity(10) peak.setHKL(1, 1, 1) ws.addPeak(peak) return ws
def _get_instrument_structure(ws): """Returns the number of detectors and the number of detectors per tube in the currently processed instrument.""" instrument = ws.getInstrument().getName() if instrument in ['IN4', 'IN6']: self.log.warning( "Grouping pattern cannot be provided for IN4 and IN6.") return "" tmp_inst = '{}_tmp'.format(instrument) LoadEmptyInstrument(InstrumentName=instrument, OutputWorkspace=tmp_inst) tmp_mon_inst = 'mon_{}'.format(tmp_inst) ExtractMonitors(InputWorkspace=tmp_inst, DetectorWorkspace=tmp_inst, MonitorWorkspace=tmp_mon_inst) n_monitors = mtd[tmp_mon_inst].getNumberHistograms() n_tubes = 0 for comp in mtd[tmp_inst].componentInfo(): if len(comp.detectorsInSubtree) > 1 and comp.hasParent: n_tubes += 1 n_tubes -= n_monitors if instrument == 'IN5': # there is an extra bank that contains all of the tubes n_tubes -= 1 n_pixels = mtd[tmp_inst].getNumberHistograms() n_pixels_per_tube = int(n_pixels / n_tubes) DeleteWorkspace(Workspace=tmp_inst) DeleteWorkspace(Workspace=tmp_mon_inst) return n_pixels, n_pixels_per_tube
def test_duplicate_monitor_names(): from mantid.simpleapi import LoadEmptyInstrument ws = LoadEmptyInstrument( InstrumentName='POLARIS', StoreInADS=False) # Has many monitors named 'monitor' da = scn.mantid.from_mantid(ws) assert da.attrs['monitor_1'].value.attrs['spectrum'].value == 1 assert da.attrs['monitor_13'].value.attrs['spectrum'].value == 13 assert da.attrs['monitor_14'].value.attrs['spectrum'].value == 14
def _load_indirect_instrument(instr, parameters): from mantid.simpleapi import LoadEmptyInstrument, \ LoadParameterFile, AddSampleLog, config # Create a workspace from an indirect instrument out = LoadEmptyInstrument(InstrumentName=instr) if instr in parameters: LoadParameterFile(out, Filename=os.path.join( config.getInstrumentDirectory(), parameters[instr])) if not out.run().hasProperty('EMode'): # EMode would usually get attached via data loading # We skip that so have to apply manually AddSampleLog(out, LogName='EMode', LogText='Indirect', LogType='String') return out
def load_component_info_to_2d(geometry_file, sizes, advanced_geometry=False): """Load geometry information from a mantid Instrument Definition File or a NeXuS file containing instrument geometry. and reshape into 2D physical dimensions. This function requires mantid-framework to be installed :param geometry_file: IDF or NeXus file :param sizes: Dict of dim to size for output :return Dataset containing items for positions, rotations and shapes :raises ImportError if mantid cannot be imported :raises ValueError if sizes argument invalid """ from mantid.simpleapi import LoadEmptyInstrument ws = LoadEmptyInstrument(Filename=geometry_file, StoreInADS=False) source_pos, sample_pos = scn.mantid.make_component_info(ws) geometry = sc.Dataset() geometry["source_position"] = source_pos geometry["sample_position"] = sample_pos pos, rot, shp = scn.mantid.get_detector_properties( ws, source_pos, sample_pos, spectrum_dim='spectrum', advanced_geometry=advanced_geometry) pos_shape = pos.shape[0] reshape_volume = reduce(operator.mul, sizes.values(), 1) if not pos_shape == reshape_volume: raise ValueError( f'file contains {pos_shape} spectra, but you are attempting\ to reshape to an output with volume\ {reshape_volume} via sizes argument') fold_args = { 'dim': 'spectrum', 'dims': sizes.keys(), 'shape': sizes.values() } pos2d = sc.fold(pos, **fold_args) geometry["position"] = pos2d if rot is not None: rot2d = sc.fold(rot, **fold_args) geometry["rotation"] = rot2d if shp is not None: shp2d = sc.fold(shp, **fold_args) geometry["shape"] = shp2d # Could be upgraded, but logic complex for mapping to fields of vector # We therefore limit the element coord generation to x, y, z only if set(sizes.keys()).issubset({'x', 'y', 'z'}): for u, v in zip(sizes.keys(), reversed(list(sizes.keys()))): geometry[u] = getattr(pos2d.fields, u)[v, 0] return geometry
def runTest(self): ws = LoadEmptyInstrument(InstrumentName='WISH') UB = np.array([[-0.00601763, 0.07397297, 0.05865706], [0.05373321, 0.050198, -0.05651455], [-0.07822144, 0.0295911, -0.04489172]]) SetUB(ws, UB=UB) self._peaks = PredictPeaks(ws, WavelengthMin=0.1, WavelengthMax=100, OutputWorkspace='peaks') # We specifically want to check peak -5 -1 -7 exists, so filter for it self._filtered = FilterPeaks(self._peaks, "h^2+k^2+l^2", 75, '=', OutputWorkspace='filtered') SaveIsawPeaks(self._peaks, Filename='WISHSXReductionPeaksTest.peaks')
def setUp(self): # load empty instrument so can create a peak table self.ws = LoadEmptyInstrument(InstrumentName='SXD', OutputWorkspace='sxd') ub = np.array([[-0.00601763, 0.07397297, 0.05865706], [0.05373321, 0.050198, -0.05651455], [-0.07822144, 0.0295911, -0.04489172]]) SetUB(self.ws, UB=ub) PredictPeaks(self.ws, WavelengthMin=1, WavelengthMax=1.1, MinDSpacing=1, MaxDSPacing=1.1, OutputWorkspace='test') # 8 peaks PredictSatellitePeaks(Peaks='test', SatellitePeaks='test_sat', ModVector1='0,0,0.33', MaxOrder=1) self.peaks = CombinePeaksWorkspaces(LHSWorkspace='test_sat', RHSWorkspace='test', OutputWorkspace='test')
def runTest(self): prefix = 'mU6g7vP92_' # pseudo-random string to prefix workspace names LoadAscii(Filename='SNAP_51984_peakcenters_tof.dat', Separator='Tab', Unit='Dimensionless', OutputWorkspace=prefix + 'peak_centers') LoadEmptyInstrument(InstrumentName='SNAP', OutputWorkspace=prefix + 'snap') with capture_logs(level='debug') as logs: AlignComponents(PeakCentersTofTable=prefix + 'peak_centers', PeakPositions='1.3143, 1.3854,1.6967, 1.8587, 2.0781', AdjustmentsTable=prefix + 'adjustments', DisplacementsTable=prefix + 'displacements', InputWorkspace=prefix + 'snap', OutputWorkspace=prefix + 'snap_modified', FitSourcePosition=False, FitSamplePosition=False, ComponentList='Column1', XPosition=False, YPosition=False, ZPosition=True, AlphaRotation=False, BetaRotation=False, GammaRotation=False) assert 'First and last detectorID for Column1 are 0, 196607' in logs.getvalue() # Clean up workspaces temporary = ['peak_centers', 'snap', 'adjustments', 'displacements', 'snap_modified'] DeleteWorkspaces([prefix + suffix for suffix in temporary])
def runTest(self): # Load Empty Instrument ws = LoadEmptyInstrument(InstrumentName='WISH', OutputWorkspace='WISH') axis = ws.getAxis(0) axis.setUnit("TOF") # need this to add peak to table # CreatePeaksWorkspace with peaks in specific detectors peaks = CreatePeaksWorkspace(InstrumentWorkspace=ws, NumberOfPeaks=0, OutputWorkspace='peaks') AddPeak(PeaksWorkspace=peaks, RunWorkspace=ws, TOF=20000, DetectorID=1707204, Height=521, BinCount=0) # pixel in first tube in panel 1 AddPeak(PeaksWorkspace=peaks, RunWorkspace=ws, TOF=20000, DetectorID=1400510, Height=1, BinCount=0) # pixel at top of a central tube in panel 1 AddPeak(PeaksWorkspace=peaks, RunWorkspace=ws, TOF=20000, DetectorID=1408202, Height=598, BinCount=0) # pixel in middle of bank 1 (not near edge) AddPeak(PeaksWorkspace=peaks, RunWorkspace=ws, TOF=20000, DetectorID=1100173, Height=640, BinCount=0) # pixel in last tube of panel 1 (next to panel 2) # create dummy MD workspace for integration (don't need data as checking peak shape) MD = CreateMDWorkspace(Dimensions='3', Extents='-1,1,-1,1,-1,1', Names='Q_lab_x,Q_lab_y,Q_lab_z', Units='U,U,U', Frames='QLab,QLab,QLab', SplitInto='2', SplitThreshold='50') # Integrate peaks masking all pixels at tube end (built into IntegratePeaksMD) self._peaks_pixels = IntegratePeaksMD(InputWorkspace=MD, PeakRadius='0.02', PeaksWorkspace=peaks, IntegrateIfOnEdge=False, OutputWorkspace='peaks_pixels', MaskEdgeTubes=False) # Apply masking to specific tubes next to beam in/out (subset of all edge tubes) and integrate again MaskBTP(Workspace='peaks', Bank='5-6', Tube='152') MaskBTP(Workspace='peaks', Bank='1,10', Tube='1') self._peaks_pixels_beamTubes = IntegratePeaksMD( InputWorkspace='MD', PeakRadius='0.02', PeaksWorkspace=peaks, IntegrateIfOnEdge=False, OutputWorkspace='peaks_pixels_beamTubes', MaskEdgeTubes=False) # Integrate masking all edge tubes self._peaks_pixels_edgeTubes = IntegratePeaksMD( InputWorkspace='MD', PeakRadius='0.02', PeaksWorkspace='peaks', IntegrateIfOnEdge=False, OutputWorkspace='peaks_pixels_edgeTubes', MaskEdgeTubes=True)
from mantid.simpleapi import LoadDiffCal, mtd, LoadEmptyInstrument, CalculateDIFC, MaskBTP, CloneWorkspace, SaveDiffCal, ApplyCalibration import matplotlib.pyplot as plt import tube import numpy as np import numpy.ma as ma tube.readCalibrationFile( 'CalibTable', '/SNS/users/rwp/corelli/tube_calibration/CalibTableNew.txt') corelli = LoadEmptyInstrument(InstrumentName='CORELLI') corelli = CalculateDIFC(corelli) difc0 = corelli.extractY().flatten() ApplyCalibration('corelli', 'CalibTable') corelli = CalculateDIFC(corelli) difc = corelli.extractY().flatten() plt.plot(difc / difc0) plt.show() LoadDiffCal( Filename='../cal_Si_C60/cal_Si2_47327-47334_TubeCal_sum16_mask_lt_2.cal', InstrumentName='CORELLI', WorkspaceName='si') MaskBTP(Workspace='si_mask', Pixel="1-16,241-256") LoadDiffCal( Filename='../cal_Si_C60/cal_C60_2_47367-47382_TubeCal_sum16_mask_lt_2.h5', InstrumentName='CORELLI', WorkspaceName='c60') MaskBTP(Workspace='c60_mask', Pixel="1-16,241-256")
#!/usr/bin/python2 from __future__ import print_function from mantid.simpleapi import LoadEmptyInstrument, MoveInstrumentComponent, mtd import numpy as np LoadEmptyInstrument(Filename='/SNS/users/rwp/CORELLI_Definition_91.07cm.xml', OutputWorkspace='ws') ws = mtd['ws'] #[x,_,z] = mtd['ws'].getInstrument().getComponentByName('CORELLI/bank46/sixteenpack/tube3/pixel128').getPos() #[_,y,_] = mtd['ws'].getInstrument().getComponentByName('CORELLI/bank46/sixteenpack/tube3').getPos() #MoveInstrumentComponent('ws', ComponentName='CORELLI/bank46/sixteenpack/tube3/pixel128', X=x, Y=y, Z=z, RelativePosition=False) def pixel(A, E1, E2, x): return 255 * A * (x - E1) / (E2 - E1 + (A - 1) * (x - E1)) with open('curvefitmain.txt', "r") as f: lines = f.readlines() lengths = [] for line in lines: if not 'channel' in line: continue _, channel, _, roc, _, A, _, E1, _, E2 = line.split() channel = float(channel) roc = float(roc) A = float(A) E1 = float(E1) E2 = float(E2) lengths.append(E2 - E1)
class FindGlobalBMatrixTest(unittest.TestCase): def setUp(self): # load empty instrument so can create a peak table self.ws = LoadEmptyInstrument(InstrumentName='SXD', OutputWorkspace='empty_SXD') axis = self.ws.getAxis(0) axis.setUnit("TOF") def tearDown(self): AnalysisDataService.clear() def test_finds_average_lattice_parameter(self): # create two peak tables with UB corresponding to different lattice constant, a peaks1 = CreatePeaksWorkspace(InstrumentWorkspace=self.ws, NumberOfPeaks=0, OutputWorkspace="SXD_peaks1") UB = np.diag([1.0 / 3.9, 0.25, 0.1]) # alatt = [3.9, 4, 10] SetUB(peaks1, UB=UB) peaks2 = CreatePeaksWorkspace(InstrumentWorkspace=self.ws, NumberOfPeaks=0, OutputWorkspace="SXD_peaks2") UB = np.diag([1.0 / 4.1, 0.25, 0.1]) # alatt = [4.1, 4, 10] SetUB(peaks2, UB=UB) # Add some peaks add_peaksHKL([peaks1, peaks2], range(0, 3), range(0, 3), 4) FindGlobalBMatrix(PeakWorkspaces=[peaks1, peaks2], a=4.1, b=4.2, c=10, alpha=88, beta=88, gamma=89, Tolerance=0.15) # check lattice - should have average a=4.0 self.assert_lattice([peaks1, peaks2], 4.0, 4.0, 10.0, 90.0, 90.0, 90.0, delta_latt=5e-2, delta_angle=2.5e-1) self.assert_matrix([peaks1], getBMatrix(peaks2), getBMatrix, delta=1e-10) # should have same B matrix self.assert_matrix([peaks1, peaks2], np.eye(3), getUMatrix, delta=5e-2) def test_handles_inaccurate_goniometer(self): peaks1 = CreatePeaksWorkspace(InstrumentWorkspace=self.ws, NumberOfPeaks=0, OutputWorkspace="SXD_peaks3") peaks2 = CloneWorkspace(InputWorkspace=peaks1, OutputWorkspace="SXD_peaks4") # set different gonio on each run rot = 5 SetGoniometer(Workspace=peaks1, Axis0=f'{-rot},0,1,0,1') SetGoniometer(Workspace=peaks2, Axis0=f'{rot},0,1,0,1') # Add peaks at QLab corresponding to slightly different gonio rotations UB = np.diag([0.25, 0.25, 0.1]) # alatt = [4,4,10] for h in range(0, 3): for k in range(0, 3): hkl = np.array([h, k, 4]) qlab = 2 * np.pi * np.matmul( np.matmul(getR(-(rot + 1), [0, 1, 0]), UB), hkl) pk = peaks1.createPeak(qlab) peaks1.addPeak(pk) qlab = 2 * np.pi * np.matmul( np.matmul(getR(rot + 1, [0, 1, 0]), UB), hkl) pk = peaks2.createPeak(qlab) peaks2.addPeak(pk) FindGlobalBMatrix(PeakWorkspaces=[peaks1, peaks2], a=4.15, b=3.95, c=10, alpha=88, beta=88, gamma=89, Tolerance=0.15) # check lattice - shouldn't be effected by error in goniometer self.assert_lattice([peaks1, peaks2], 4.0, 4.0, 10.0, 90.0, 90.0, 90.0, delta_latt=2e-2, delta_angle=2.5e-1) self.assert_matrix([peaks1], getBMatrix(peaks2), getBMatrix, delta=1e-10) # should have same B matrix self.assert_matrix([peaks1, peaks2], np.eye(3), getUMatrix, delta=5e-2) def test_requires_more_than_one_peak_workspace(self): peaks1 = CreatePeaksWorkspace(InstrumentWorkspace=self.ws, NumberOfPeaks=0, OutputWorkspace="SXD_peaks4") UB = np.diag([0.25, 0.25, 0.1]) SetUB(peaks1, UB=UB) # Add some peaks add_peaksHKL([peaks1], range(0, 3), range(0, 3), 4) alg = create_algorithm('FindGlobalBMatrix', PeakWorkspaces=[peaks1], a=4.1, b=4.2, c=10, alpha=88, beta=88, gamma=89, Tolerance=0.15) with self.assertRaises(RuntimeError): alg.execute() def test_peak_workspaces_need_at_least_six_peaks_each(self): peaks1 = CreatePeaksWorkspace(InstrumentWorkspace=self.ws, NumberOfPeaks=0, OutputWorkspace="SXD_peaks5") UB = np.diag([0.25, 0.25, 0.1]) SetUB(peaks1, UB=UB) # Add 5 peaks add_peaksHKL([peaks1], range(0, 5), [0], 4) peaks2 = CloneWorkspace(InputWorkspace=peaks1, OutputWorkspace="SXD_peaks6") alg = create_algorithm('FindGlobalBMatrix', PeakWorkspaces=[peaks1, peaks2], a=4.1, b=4.2, c=10, alpha=88, beta=88, gamma=89, Tolerance=0.15) with self.assertRaises(RuntimeError): alg.execute() def test_performs_correct_transform_to_ensure_consistent_indexing(self): # create peaks tables peaks1 = CreatePeaksWorkspace(InstrumentWorkspace=self.ws, NumberOfPeaks=0, OutputWorkspace="SXD_peaks7") UB = np.diag([0.2, 0.25, 0.1]) SetUB(peaks1, UB=UB) # Add some peaks add_peaksHKL([peaks1], range(0, 3), range(0, 3), 4) # Clone ws and transform peaks2 = CloneWorkspace(InputWorkspace=peaks1, OutputWorkspace="SXD_peaks8") peaks2.removePeak( 0) # peaks1 will have most peaks indexed so will used as reference transform = np.array([[0, 1, 0], [1, 0, 0], [0, 0, -1]]) TransformHKL(PeaksWorkspace=peaks2, HKLTransform=transform, FindError=False) FindGlobalBMatrix(PeakWorkspaces=[peaks1, peaks2], a=4.15, b=3.95, c=10, alpha=88, beta=88, gamma=89, Tolerance=0.15) # check lattice - shouldn't be effected by error in goniometer self.assert_lattice([peaks1, peaks2], 5.0, 4.0, 10.0, 90.0, 90.0, 90.0, delta_latt=5e-2, delta_angle=2.5e-1) self.assert_matrix([peaks1], getBMatrix(peaks2), getBMatrix, delta=1e-10) # should have same B matrix self.assert_matrix([peaks1, peaks2], np.eye(3), getUMatrix, delta=5e-2) def assert_lattice(self, ws_list, a, b, c, alpha, beta, gamma, delta_latt=2e-2, delta_angle=2.5e-1): for ws in ws_list: cell = ws.sample().getOrientedLattice() self.assertAlmostEqual(cell.a(), a, delta=delta_latt) self.assertAlmostEqual(cell.b(), b, delta=delta_latt) self.assertAlmostEqual(cell.c(), c, delta=delta_latt) self.assertAlmostEqual(cell.alpha(), alpha, delta=delta_angle) self.assertAlmostEqual(cell.beta(), beta, delta=delta_angle) self.assertAlmostEqual(cell.gamma(), gamma, delta=delta_angle) def assert_matrix(self, ws_list, ref_mat, extract_mat_func, delta=5e-2): for ws in ws_list: mat = extract_mat_func(ws) for ii in range(0, 3): for jj in range(0, 3): self.assertAlmostEqual(mat[ii, jj], ref_mat[ii, jj], delta=delta)
from mantid.simpleapi import LoadEmptyInstrument import subprocess import sys import numpy as np output = sys.argv[1] corelli = LoadEmptyInstrument(InstrumentName='CORELLI') inst = corelli.getInstrument() def make_fityk_cmd(run, bank, tube): fityk_cmd = """@0 < 'COR_{0}_{1}_{2}.txt' @0: A = a and not (-1 < x and x < 25.5) @0: A = a and not (229.5 < x and x < 256) $a = ~0.0 $b = ~282.0 $c = ~128.0 F += Lorentzian(height={3}, center=0.396*0.396*$a-0.396*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.3432*0.3432*$a-0.3432*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.2904*0.2904*$a-0.2904*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.2376*0.2376*$a-0.2376*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.1848*0.1848*$a-0.1848*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.132*0.132*$a-0.132*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.0792*0.0792*$a-0.0792*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.0264*0.0264*$a-0.0264*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.0264*0.0264*$a+0.0264*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.0792*0.0792*$a+0.0792*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.132*0.132*$a+0.132*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.1848*0.1848*$a+0.1848*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.2376*0.2376*$a+0.2376*$b+$c, hwhm=~1.28083) F += Lorentzian(height={3}, center=0.2904*0.2904*$a+0.2904*$b+$c, hwhm=~1.28083)
def get_target_instrument(self): self.ws_target = "ws_target" LoadEmptyInstrument(Filename="CORELLI_Definition.xml", OutputWorkspace=self.ws_target) ConvertToEventWorkspace(InputWorkspace=self.ws_target, OutputWorkspace=self.ws_target) # explicitly translate component TO designated location MoveInstrumentComponent( Workspace=self.ws_target, ComponentName="moderator", X=0, Y=0, Z=-19.9997, RelativePosition=False, ) MoveInstrumentComponent( Workspace=self.ws_target, ComponentName="sample-position", X=0, Y=0, Z=0, RelativePosition=False, ) MoveInstrumentComponent( Workspace=self.ws_target, ComponentName="bank7/sixteenpack", X=2.25637, Y=-0.814864, Z=-0.883485, RelativePosition=False, ) MoveInstrumentComponent( Workspace=self.ws_target, ComponentName="bank42/sixteenpack", X=2.58643, Y=0.0725628, Z=0.0868798, RelativePosition=False, ) MoveInstrumentComponent( Workspace=self.ws_target, ComponentName="bank57/sixteenpack", X=0.4545, Y=0.0788326, Z=2.53234, RelativePosition=False, ) # explicitly rotate component TO designated orientation RotateInstrumentComponent( Workspace=self.ws_target, ComponentName="bank7/sixteenpack", X=-0.0244456, Y=-0.99953, Z=-0.0184843, Angle=69.4926, RelativeRotation=False, ) RotateInstrumentComponent( Workspace=self.ws_target, ComponentName="bank42/sixteenpack", X=-0.011362, Y=-0.999935, Z=-0.000173303, Angle=91.8796, RelativeRotation=False, ) RotateInstrumentComponent( Workspace=self.ws_target, ComponentName="bank42/sixteenpack", X=-0.0158497, Y=-0.999694, Z=0.0189818, Angle=169.519, RelativeRotation=False, )
def setUp(self): # load empty instrument so can create a peak table self.ws = LoadEmptyInstrument(InstrumentName='SXD', OutputWorkspace='empty_SXD') axis = self.ws.getAxis(0) axis.setUnit("TOF")
from mantid.simpleapi import LoadEmptyInstrument, MaskBTP, SaveMask LoadEmptyInstrument(InstrumentName='CORELLI', OutputWorkspace='CORELLI') # Missing banks MaskBTP('CORELLI', Bank='1-6,29,30,62,63-68,91') # End of tubes MaskBTP('CORELLI', Pixel='1-15,242-256') # Beam center MaskBTP('CORELLI', Bank='58', Tube='13-16', Pixel='80-130') MaskBTP('CORELLI', Bank='59', Tube='1-4', Pixel='80-130') SaveMask('CORELLI', 'corelli_mask.xml')
def setUpClass(cls): sans2d_mask_ws = LoadEmptyInstrument(InstrumentName="SANS2D") loq_empty = LoadEmptyInstrument(InstrumentName="LOQ") cls._sans_original = sans2d_mask_ws cls._loq_original = loq_empty
from mantid.simpleapi import LoadEmptyInstrument, LoadIsawDetCal cor = LoadEmptyInstrument(InstrumentName='CORELLI') LoadIsawDetCal(cor, 'SCD_Grouped_calib.results') i = cor.getInstrument() def mapBankToABC(i): if i < 30: return "A" + str(i) elif i < 63: return "B" + str(i - 29) else: return "C" + str(i - 62) print "Location Xsci Ysci Zsci Xrot_sci Yrot_sci Zrot_sci" for bank in range(1, 92): b = i.getComponentByName("bank" + str(bank) + "/sixteenpack") x = b.getPos().getX() * 1000 y = b.getPos().getY() * 1000 z = b.getPos().getZ() * 1000 [beta, alpha, gamma] = b.getRotation().getEulerAngles("YXZ") print mapBankToABC(bank), x, y, z, alpha, beta, gamma
def runTest(self): # Na Mn Cl3 # R -3 H (148) # 6.592 6.592 18.585177 90 90 120 # UB/wavelength from /HFIR/HB3A/IPTS-25470/shared/autoreduce/HB3A_exp0769_scan0040.nxs ub = np.array([[1.20297e-01, 1.70416e-01, 1.43000e-04], [8.16000e-04, -8.16000e-04, 5.38040e-02], [1.27324e-01, -4.05110e-02, -4.81000e-04]]) wavelength = 1.553 # create fake MDEventWorkspace, similar to what is expected from exp769 after loading with HB3AAdjustSampleNorm MD_Q_sample = CreateMDWorkspace( Dimensions='3', Extents='-5,5,-5,5,-5,5', Names='Q_sample_x,Q_sample_y,Q_sample_z', Units='rlu,rlu,rlu', Frames='QSample,QSample,QSample') inst = LoadEmptyInstrument(InstrumentName='HB3A') AddTimeSeriesLog(inst, 'omega', '2010-01-01T00:00:00', 0.) AddTimeSeriesLog(inst, 'phi', '2010-01-01T00:00:00', 0.) AddTimeSeriesLog(inst, 'chi', '2010-01-01T00:00:00', 0.) MD_Q_sample.addExperimentInfo(inst) SetUB(MD_Q_sample, UB=ub) ol = OrientedLattice() ol.setUB(ub) sg = SpaceGroupFactory.createSpaceGroup("R -3") hkl = [] sat_hkl = [] for h in range(0, 6): for k in range(0, 6): for l in range(0, 11): if sg.isAllowedReflection([h, k, l]): if h == k == l == 0: continue q = V3D(h, k, l) q_sample = ol.qFromHKL(q) if not np.any(np.array(q_sample) > 5): hkl.append(q) FakeMDEventData( MD_Q_sample, PeakParams='1000,{},{},{},0.05'.format( *q_sample)) # satellite peaks at 0,0,+1.5 q = V3D(h, k, l + 1.5) q_sample = ol.qFromHKL(q) if not np.any(np.array(q_sample) > 5): sat_hkl.append(q) FakeMDEventData( MD_Q_sample, PeakParams='100,{},{},{},0.02'.format( *q_sample)) # satellite peaks at 0,0,-1.5 q = V3D(h, k, l - 1.5) q_sample = ol.qFromHKL(q) if not np.any(np.array(q_sample) > 5): sat_hkl.append(q) FakeMDEventData( MD_Q_sample, PeakParams='100,{},{},{},0.02'.format( *q_sample)) # Check that this fake workpsace gives us the expected UB peaks = FindPeaksMD(MD_Q_sample, PeakDistanceThreshold=1, OutputType='LeanElasticPeak') FindUBUsingFFT(peaks, MinD=5, MaxD=20) ShowPossibleCells(peaks) SelectCellOfType(peaks, CellType='Rhombohedral', Centering='R', Apply=True) OptimizeLatticeForCellType(peaks, CellType='Hexagonal', Apply=True) found_ol = peaks.sample().getOrientedLattice() self.assertAlmostEqual(found_ol.a(), 6.592, places=2) self.assertAlmostEqual(found_ol.b(), 6.592, places=2) self.assertAlmostEqual(found_ol.c(), 18.585177, places=2) self.assertAlmostEqual(found_ol.alpha(), 90) self.assertAlmostEqual(found_ol.beta(), 90) self.assertAlmostEqual(found_ol.gamma(), 120) # nuclear peaks predict = HB3APredictPeaks( MD_Q_sample, Wavelength=wavelength, ReflectionCondition='Rhombohedrally centred, obverse', SatellitePeaks=True, IncludeIntegerHKL=True) predict = HB3AIntegratePeaks(MD_Q_sample, predict, 0.25) self.assertEqual(predict.getNumberPeaks(), 66) # check that the found peaks are expected for n in range(predict.getNumberPeaks()): HKL = predict.getPeak(n).getHKL() self.assertTrue(HKL in hkl, msg=f"Peak {n} with HKL={HKL}") # magnetic peaks satellites = HB3APredictPeaks( MD_Q_sample, Wavelength=wavelength, ReflectionCondition='Rhombohedrally centred, obverse', SatellitePeaks=True, ModVector1='0,0,1.5', MaxOrder=1, IncludeIntegerHKL=False) satellites = HB3AIntegratePeaks(MD_Q_sample, satellites, 0.1) self.assertEqual(satellites.getNumberPeaks(), 80) # check that the found peaks are expected for n in range(satellites.getNumberPeaks()): HKL = satellites.getPeak(n).getHKL() self.assertTrue(HKL in sat_hkl, msg=f"Peak {n} with HKL={HKL}")
from mantid.simpleapi import LoadEmptyInstrument, AddSampleLog, LoadInstrument import resource m0 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss LoadEmptyInstrument( Filename='/SNS/users/rwp/wand/IDF/test4/WAND_Definition_fixed.xml', OutputWorkspace='wand_fixed') m1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss LoadEmptyInstrument( Filename='/SNS/users/rwp/wand/IDF/test4/WAND_Definition_2952.xml', OutputWorkspace='wand_rect_fixed') m2 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss LoadEmptyInstrument( Filename='/SNS/users/rwp/wand/IDF/test4/WAND_Definition.xml', OutputWorkspace='wand') m3 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss AddSampleLog('wand', LogName='HB2C:Mot:s2.RBV', LogText='17.57', LogType='Number Series') AddSampleLog('wand', LogName='HB2C:Mot:detz.RBV', LogText='7.05159', LogType='Number Series') m4 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss LoadInstrument('wand', Filename='/SNS/users/rwp/wand/IDF/test4/WAND_Definition.xml', RewriteSpectraMap=False) m5 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss print(m1 - m0)
def load_empty_instrument(instrument_name): sans_move_test_workspace = LoadEmptyInstrument( InstrumentName=instrument_name) return sans_move_test_workspace
logging.basicConfig(format="[%(levelname)s]%(asctime)s:%(message)s", level=logging.INFO) # lb_bank = 'bank' lb_8pack = 'eightpack' lb_pos = ['X', 'Y', 'Z'] df_survey = read_survey_measurements() logging.info("Load sanitized survey measurements.") logging.info(f"\n{df_survey.groupby(lb_bank)[lb_pos].mean()}") for bank_id in df_survey[lb_bank].unique(): logging.info( f"bank_{bank_id}\n{df_survey[df_survey[lb_bank]==bank_id][lb_pos]}" ) # logging.info("Loading VULCAN instrument definition.") vulcan = LoadEmptyInstrument(Filename="VULCAN_Definition_tmp.xml", OutputWorkspace="vulcan") compInfo = vulcan.componentInfo() detInfo = vulcan.detectorInfo() # -- Verify banks are in desired quadrants # # bank5 | bank4 # | bank 3 # bank1------------sample---------->(x) bank2 # bank6 | # v incident beam # (z) logging.info("Verify banks are in desired quadrants.") for name in ['bank1', 'bank2', 'bank3', 'bank4', 'bank5', 'bank6']: logging.info(f"Checking {name}") bank = getTubeIds(compInfo, name)
def _create_instrument(self, instrument_name='IN5'): LoadEmptyInstrument(InstrumentName=instrument_name, OutputWorkspace=self._TEST_WS_NAME) return mtd[self._TEST_WS_NAME]
num_pixel_ids += len(pixel_ids) # Use elements defined vs. just group IDs group_id_map = collections.OrderedDict() for k in groups_map.keys(): group_id_map[k] = k if args.elements: assert (len(group_id_map.keys()) == len(args.elements)) for gid, element in zip(group_ids, args.elements): group_id_map[gid] = element # Get instrument and detectors from mantid.simpleapi import LoadEmptyInstrument, mtd wksp = "instrument" LoadEmptyInstrument(InstrumentName="NOMAD", OutputWorkspace=wksp) instrument = mtd[wksp].getInstrument() # Output XYZ file with open(args.output, 'w') as f: f.write("{}\n\n".format(num_pixel_ids)) for group_id, pixel_ids in groups_map.items(): for pixel_idx in pixel_ids: x, y, z = instrument.getDetector(pixel_idx).getPos() print_args = { 'idx': pixel_idx, 'x': x, 'y': y, 'z': z, 'group_id': group_id_map[group_id] }