def PyExec(self): # Process input data # get the list of input filenames runs = self.get_intput_filenames() # load and group data = self.load_and_group(runs) # check if normalization need to be performed # NOTE: the normalization will be skipped if no information regarding Vanadium is provided skipNormalization = self.getProperty("VanadiumIPTS").isDefault and \ self.getProperty("VanadiumRunNumber").isDefault and \ self.getProperty("VanadiumFile").isDefault and \ self.getProperty("VanadiumWorkspace").isDefault if skipNormalization: self.log().warning('No Vanadium data provided, skip normalization') else: # attempt to get the vanadium via file van_filename = self.get_va_filename() if van_filename is None: # try to load from memory norm = self.getProperty("VanadiumWorkspace").value else: norm = self.load_and_group([van_filename]) # normalize data = self.normalize( data, norm, self.getProperty("NormalizedBy").value.lower()) # cleanup # NOTE: if va is read from memory, we will keep it in case we need it later if van_filename is not None: DeleteWorkspace(norm) # setup output self.setProperty("OutputWorkspace", data) # cleanup DeleteWorkspace(data)
def testWithoutUncertainties(self): inwsname = 'MatchSpectraTest_withoutUncertainties' outwsname = inwsname + '_out' # never gets created for histogram in (True, False): self.__createWorkspace(inwsname, histogram, False) with self.assertRaises(RuntimeError): results = MatchSpectra(InputWorkspace=inwsname, OutputWorkspace=outwsname, ReferenceSpectrum=1, CalculateOffset=True, CalculateScale=True) DeleteWorkspace(Workspace=inwsname)
def create_or_update_bgsub_ws(self, ws_name, bg_params): ws = self._loaded_workspaces[ws_name] ws_bg = self._bg_sub_workspaces[ws_name] if not ws_bg or self._bg_params[ws_name] == [] or bg_params[ 1:] != self._bg_params[ws_name][1:]: background = self.estimate_background(ws_name, *bg_params[1:]) self._bg_params[ws_name] = bg_params bgsub_ws_name = ws_name + "_bgsub" bgsub_ws = Minus(LHSWorkspace=ws, RHSWorkspace=background, OutputWorkspace=bgsub_ws_name) self._bg_sub_workspaces[ws_name] = bgsub_ws DeleteWorkspace(background) else: logger.notice("Background workspace already calculated")
def case_restart_diff_order(self, order=None): """ The considered testing scenario looks as follows. First calculations are performed for self._quantum_order_event. Then calculations are performed for order (different quantum order event). In case order > self._quantum_order_event then S should be calculated. Otherwise, it will be loaded from an hdf file. :param order: number of quantum order event for which restart should be done. """ self.case_from_scratch() DeleteWorkspace(self._output_name) Abins(AbInitioProgram=self._ab_initio_program, VibrationalOrPhononFile=self._system_name + self._extension[self._ab_initio_program], TemperatureInKelvin=self._temperature, SampleForm=self._sample_form, Instrument=self._instrument_name, BinWidthInWavenumber=self._bin_width, Atoms=self._atoms, SumContributions=self._sum_contributions, Scale=self._scale, QuantumOrderEventsNumber=str(order), ScaleByCrossSection=self._cross_section_factor, OutputWorkspace=self._output_name)
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_temperature_from_sample_log(self): self._input_ws.mutableRun().addProperty('temperature', 0.0, True) outputWorkspaceName = "output_ws" EditInstrumentGeometry(self._input_ws, L2="4,8", Polar="0,15", Azimuthal="0,0", DetectorIDs="1,2") alg_test = run_algorithm("ComputeCalibrationCoefVan", VanadiumWorkspace=self._input_ws, EPPTable=self._table, OutputWorkspace=outputWorkspaceName) self.assertTrue(alg_test.isExecuted()) wsoutput = AnalysisDataService.retrieve(outputWorkspaceName) self._checkDWF(wsoutput, 0.0) DeleteWorkspace(wsoutput)
def testDoNotAdjustDetector(self): # Ensure detector position does not change when no offsets are given orig = LoadMD("HB3A_data.nxs", LoadHistory=False) orig_pos = orig.getExperimentInfo(0).getInstrument().getDetector( 1).getPos() result = HB3AAdjustSampleNorm(InputWorkspaces=orig, DetectorHeightOffset=0.0, DetectorDistanceOffset=0.0) new_pos = result.getExperimentInfo(0).getInstrument().getDetector( 1).getPos() # Verify detector adjustment self.__checkAdjustments(orig_pos, new_pos, 0.0, 0.0) DeleteWorkspace(orig, result)
def test_basicrun(self): OutputWorkspaceName = "outputws" alg_test = run_algorithm("TOFTOFConvertTofToDeltaE", InputWorkspace=self._input_ws, OutputWorkspace=OutputWorkspaceName) wsoutput = AnalysisDataService.retrieve(OutputWorkspaceName) # execution of algorithm self.assertTrue(alg_test.isExecuted()) # unit of output self.assertEqual(wsoutput.getAxis(0).getUnit().unitID(), "DeltaE") # shape of output compared to input self.assertEqual(wsoutput.getNumberHistograms(), self._input_ws.getNumberHistograms()) self.assertEqual(wsoutput.blocksize(), self._input_ws.blocksize()) DeleteWorkspace(wsoutput)
def __normalization(self, data, vanadium, load_files): if vanadium: norm_data = ReplicateMD(ShapeWorkspace=data, DataWorkspace=vanadium) norm_data = DivideMD(LHSWorkspace=data, RHSWorkspace=norm_data) elif load_files: norm_data = data else: norm_data = CloneMDWorkspace(data) if self.getProperty("ScaleByMotorStep").value: run = data.getExperimentInfo(0).run() scan_log = 'omega' if np.isclose(run.getTimeAveragedStd('phi'), 0.0) else 'phi' scan_axis = run[scan_log].value scan_step = (scan_axis[-1] - scan_axis[0]) / (scan_axis.size - 1) norm_data *= scan_step normaliseBy = self.getProperty("NormaliseBy").value monitors = np.asarray( data.getExperimentInfo(0).run().getProperty('monitor').value) times = np.asarray( data.getExperimentInfo(0).run().getProperty('time').value) if load_files and vanadium: DeleteWorkspace(data) if normaliseBy == "Monitor": scale = monitors elif normaliseBy == "Time": scale = times else: return norm_data if vanadium: if normaliseBy == "Monitor": scale /= vanadium.getExperimentInfo(0).run().getProperty( 'monitor').value[0] elif normaliseBy == "Time": scale /= vanadium.getExperimentInfo(0).run().getProperty( 'time').value[0] norm_data.setSignalArray(norm_data.getSignalArray() / scale) norm_data.setErrorSquaredArray(norm_data.getErrorSquaredArray() / scale**2) return norm_data
def __processFile(self, filename, wkspname, file_prog_start, determineCharacterizations): chunks = determineChunking(filename, self.chunkSize) self.log().information('Processing \'%s\' in %d chunks' % (filename, len(chunks))) prog_per_chunk_step = self.prog_per_file * 1./(6.*float(len(chunks))) # for better progress reporting - 6 steps per chunk # inner loop is over chunks for (j, chunk) in enumerate(chunks): prog_start = file_prog_start + float(j) * 5. * prog_per_chunk_step chunkname = "%s_c%d" % (wkspname, j) Load(Filename=filename, OutputWorkspace=chunkname, startProgress=prog_start, endProgress=prog_start+prog_per_chunk_step, **chunk) if determineCharacterizations: self.__determineCharacterizations(filename, chunkname, False) # updates instance variable determineCharacterizations = False prog_start += prog_per_chunk_step if self.filterBadPulses > 0.: FilterBadPulses(InputWorkspace=chunkname, OutputWorkspace=chunkname, LowerCutoff=self.filterBadPulses, startProgress=prog_start, endProgress=prog_start+prog_per_chunk_step) prog_start += prog_per_chunk_step # absorption correction workspace if self.absorption is not None and len(str(self.absorption)) > 0: ConvertUnits(InputWorkspace=chunkname, OutputWorkspace=chunkname, Target='Wavelength', EMode='Elastic') Divide(LHSWorkspace=chunkname, RHSWorkspace=self.absorption, OutputWorkspace=chunkname, startProgress=prog_start, endProgress=prog_start+prog_per_chunk_step) ConvertUnits(InputWorkspace=chunkname, OutputWorkspace=chunkname, Target='TOF', EMode='Elastic') prog_start += prog_per_chunk_step AlignAndFocusPowder(InputWorkspace=chunkname, OutputWorkspace=chunkname, startProgress=prog_start, endProgress=prog_start+2.*prog_per_chunk_step, **self.kwargs) prog_start += 2.*prog_per_chunk_step # AlignAndFocusPowder counts for two steps if j == 0: self.__updateAlignAndFocusArgs(chunkname) RenameWorkspace(InputWorkspace=chunkname, OutputWorkspace=wkspname) else: Plus(LHSWorkspace=wkspname, RHSWorkspace=chunkname, OutputWorkspace=wkspname, ClearRHSWorkspace=self.kwargs['PreserveEvents'], startProgress=prog_start, endProgress=prog_start+prog_per_chunk_step) DeleteWorkspace(Workspace=chunkname) if self.kwargs['PreserveEvents']: CompressEvents(InputWorkspace=wkspname, OutputWorkspace=wkspname)
def reduceToPowder(ws, OutputWorkspace, cal=None, target='Theta', XMin=10, XMax=135, NumberBins=2500, normaliseBy='Monitor'): ConvertSpectrumAxis(InputWorkspace=ws, Target=target, OutputWorkspace=OutputWorkspace) Transpose(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace) ResampleX(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace, XMin=XMin, XMax=XMax, NumberBins=NumberBins) if cal is not None: CopyInstrumentParameters(ws, cal) ConvertSpectrumAxis(InputWorkspace=cal, Target=target, OutputWorkspace='__cal') Transpose(InputWorkspace='__cal', OutputWorkspace='__cal') ResampleX(InputWorkspace='__cal', OutputWorkspace='__cal', XMin=XMin, XMax=XMax, NumberBins=NumberBins) Divide(LHSWorkspace=OutputWorkspace, RHSWorkspace='__cal', OutputWorkspace=OutputWorkspace) DeleteWorkspace('__cal') if normaliseBy == "Monitor": ws_monitor = mtd[ws].run().getProtonCharge() cal_monitor = mtd[cal].run().getProtonCharge() Scale(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace, Factor=cal_monitor / ws_monitor) elif normaliseBy == "Time": ws_duration = mtd[ws].run().getLogData('duration').value cal_duration = mtd[cal].run().getLogData('duration').value Scale(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace, Factor=cal_duration / ws_duration) return OutputWorkspace
def extract_cuts_matrix(workspace: MatrixWorkspace, xmin: float, xmax: float, ymin: float, ymax: float, xcut_name: str, ycut_name: str, log_algorithm_calls: bool = True): """ Assuming a MatrixWorkspace with vertical numeric axis, extract 1D cuts from the region defined by the given parameters :param workspace: A MatrixWorkspace with a vertical NumericAxis :param xmin: X min for bounded region :param xmax: X max for bounded region :param ymin: Y min for bounded region :param ymax: Y max for bounded region :param xcut_name: Name of the X cut. Empty indicates it should be skipped :param ycut_name: Name of the Y cut. Empty indicates it should be skipped :param log_algorithm_calls: Log the algorithm call or be silent """ tmp_crop_region = '__tmp_sv_region_extract' transpose = False roi = extract_roi_matrix(workspace, xmin, xmax, ymin, ymax, transpose, tmp_crop_region, log_algorithm_calls) # perform ycut first so xcut can reuse tmp workspace for rebinning if necessary if ycut_name: Rebin(InputWorkspace=roi, OutputWorkspace=ycut_name, Params=[xmin, xmax - xmin, xmax], EnableLogging=log_algorithm_calls) Transpose(InputWorkspace=ycut_name, OutputWorkspace=ycut_name, EnableLogging=log_algorithm_calls) if xcut_name: if not roi.isCommonBins(): # rebin to a common grid using the resolution from the spectrum # with the lowest resolution to avoid overbinning roi = _rebin_to_common_grid(roi, xmin, xmax, log_algorithm_calls) SumSpectra(InputWorkspace=roi, OutputWorkspace=xcut_name, EnableLogging=log_algorithm_calls) try: DeleteWorkspace(tmp_crop_region, EnableLogging=log_algorithm_calls) except ValueError: pass
def test_view_does_not_close_on_other_workspace_deleted(self): ws = CreateSampleWorkspace() pres = SliceViewer(ws) other_ws = CreateSampleWorkspace() DeleteWorkspace(other_ws) QApplication.sendPostedEvents() # Strange behaviour between tests where views don't close properly means # we cannot use self.assert_widget_exists, as many instances of SliceViewerView # may be active at this time. As long as this view hasn't closed we are OK. self.assertTrue( pres.view in self.find_widgets_of_type(str(type(pres.view)))) self.assertNotEqual(pres.ads_observer, None) pres.view.close()
def test_remove_if_correctly_removes_lines_associated_with_multiple_workspaces(self): second_ws = CreateSampleWorkspace() line_ws2d_histo_spec_2 = self.ax.plot(self.ws2d_histo, specNum=2, linewidth=6)[0] line_ws2d_histo_spec_3 = self.ax.plot(self.ws2d_histo, specNum=3, linewidth=6)[0] line_second_ws = self.ax.plot(second_ws, specNum=5)[0] self.assertEqual(3, len(self.ax.lines)) is_empty = self.ax.remove_artists_if( lambda artist: artist.get_label() in ['ws2d_histo: 6', 'second_ws: spec 5']) self.assertEqual(1, len(self.ax.lines)) self.assertTrue(line_ws2d_histo_spec_2 not in self.ax.lines) self.assertTrue(line_ws2d_histo_spec_3 in self.ax.lines) self.assertTrue(line_second_ws not in self.ax.lines) self.assertEqual(len(self.ax.tracked_workspaces), 1) self.assertFalse(is_empty) DeleteWorkspace(second_ws)
def testInputFail(self): signal = range(0, 1000) error = range(0, 1000) samplews = CreateMDHistoWorkspace(Dimensionality=3, SignalInput=signal, ErrorInput=error, Extents='-3,3,-3,3,-3,3', NumberOfBins='10,10,10', Names='x,y,z', Units='MomentumTransfer,EnergyTransfer,EnergyTransfer') # A MDHisto WS with no experiment info should fail with self.assertRaises(RuntimeError): HB3AAdjustSampleNorm(InputWorkspaces=samplews, DetectorHeightOffset=0.0, DetectorDistanceOffset=0.0, OutputWorkspace="__tmpout", Wavelength=2.0) DeleteWorkspace(samplews)
def runTest(self): HelperTestingClass.__init__(self) ws = CreateSampleWorkspace() pres = SliceViewer(ws) other_ws = CreateSampleWorkspace() DeleteWorkspace(other_ws) self._qapp.sendPostedEvents() # Strange behaviour between tests where views don't close properly means # we cannot use self.assert_widget_exists, as many instances of SliceViewerView # may be active at this time. As long as this view hasn't closed we are OK. self.assertTrue(pres.view in self.find_widgets_of_type(str(type(pres.view)))) self.assertNotEqual(pres.ads_observer, None) pres.view.close()
def test_sum(self): outputWorkspaceName = "output_ws" alg_test = run_algorithm("ComputeCalibrationCoefVan", VanadiumWorkspace=self._input_ws, EPPTable=self._table, OutputWorkspace=outputWorkspaceName) self.assertTrue(alg_test.isExecuted()) wsoutput = AnalysisDataService.retrieve(outputWorkspaceName) # check whether sum is calculated correctly, for theta=0, dwf=1 y_sum = sum(self._input_ws.readY(0)[27:75]) e_sum = np.sqrt(sum(np.square(self._input_ws.readE(0)[27:75]))) self.assertAlmostEqual(y_sum, wsoutput.readY(0)[0]) self.assertAlmostEqual(e_sum, wsoutput.readE(0)[0]) DeleteWorkspace(wsoutput)
def test_average_over_multiple_histograms(self): # Two histograms, center bin boundaries are aligned at -0.12. # X-axis widths are multiples of the final bin width so # rebinning results in full bins only. binWidths = numpy.array([0.3, 0.1, 0.8, 0.9, 0.2, 0.4]) xs1 = self._make_boundaries(-0.42, binWidths[:3]) xs2 = self._make_boundaries(-1.02, binWidths[3:]) xs = numpy.concatenate((xs1, xs2)) ys = numpy.zeros(len(xs) - 2) ws = CreateWorkspace(DataX=xs, DataY=ys, NSpec=2) X = -0.1 params = self._make_algorithm_params(ws, X) binWidth = self._run_algorithm(params) expectedWidth = 0.5 * (binWidths[1] + binWidths[-2]) # Average! self.assertAlmostEqual(binWidth, expectedWidth) DeleteWorkspace(ws)
def test_output(self): outputWorkspaceName = "output_ws" alg_test = run_algorithm("ComputeCalibrationCoefVan", VanadiumWorkspace=self._input_ws, EPPTable=self._table, OutputWorkspace=outputWorkspaceName) self.assertTrue(alg_test.isExecuted()) wsoutput = AnalysisDataService.retrieve(outputWorkspaceName) # Output = Vanadium ws self.assertEqual(wsoutput.getRun().getLogData('run_title').value, self._input_ws.getRun().getLogData('run_title').value) # Size of output workspace self.assertEqual(wsoutput.getNumberHistograms(), self._input_ws.getNumberHistograms()) DeleteWorkspace(wsoutput) return
def test_dwf_using_default_temperature(self): outputWorkspaceName = "output_ws" # change theta to make dwf != 1 EditInstrumentGeometry(self._input_ws, L2="4,8", Polar="0,15", Azimuthal="0,0", DetectorIDs="1,2") alg_test = run_algorithm("ComputeCalibrationCoefVan", VanadiumWorkspace=self._input_ws, EPPTable=self._table, OutputWorkspace=outputWorkspaceName) self.assertTrue(alg_test.isExecuted()) wsoutput = AnalysisDataService.retrieve(outputWorkspaceName) self._checkDWF(wsoutput, 293.0) DeleteWorkspace(wsoutput)
def load_workspace_from_filename(filename, input_properties=DEFAULT_INPUTS, output_properties=DEFAULT_OUTPUTS): try: alg, psi_data = create_load_algorithm(filename, input_properties) alg.execute() except: alg, psi_data = create_load_algorithm( filename.split(os.sep)[-1], input_properties) alg.execute() workspace = AnalysisDataService.retrieve( alg.getProperty("OutputWorkspace").valueAsStr) if is_workspace_group(workspace): # handle multi-period data load_result = _get_algorithm_properties(alg, output_properties) load_result["OutputWorkspace"] = [ MuonWorkspaceWrapper(ws) for ws in workspace.getNames() ] run = get_run_from_multi_period_data(workspace) deadtime_tables = AnalysisDataService.retrieve( load_result["DeadTimeTable"]).getNames() load_result["DataDeadTimeTable"] = deadtime_tables[0] for table in deadtime_tables[1:]: DeleteWorkspace(Workspace=table) load_result["FirstGoodData"] = round( load_result["FirstGoodData"] - load_result['TimeZero'], 2) UnGroupWorkspace(load_result["DeadTimeTable"]) load_result["DeadTimeTable"] = None UnGroupWorkspace(workspace.name()) else: # single period data load_result = _get_algorithm_properties(alg, output_properties) load_result["OutputWorkspace"] = [ MuonWorkspaceWrapper(load_result["OutputWorkspace"]) ] run = int(workspace.getRunNumber()) load_result["DataDeadTimeTable"] = load_result["DeadTimeTable"] load_result["DeadTimeTable"] = None load_result["FirstGoodData"] = round( load_result["FirstGoodData"] - load_result['TimeZero'], 2) return load_result, run, filename, psi_data
def testAdjustDetector(self): # Test a slight adjustment of the detector position height_adj = 0.75 dist_adj = 0.25 orig = LoadMD("HB3A_data.nxs", LoadHistory=False) # Get the original detector position before adjustment orig_pos = orig.getExperimentInfo(0).getInstrument().getDetector(1).getPos() result = HB3AAdjustSampleNorm(InputWorkspaces=orig, DetectorHeightOffset=height_adj, DetectorDistanceOffset=dist_adj) # Get the updated detector position new_pos = result.getExperimentInfo(0).getInstrument().getDetector(1).getPos() # Verify detector adjustment self.__checkAdjustments(orig_pos, new_pos, height_adj, dist_adj) DeleteWorkspace(orig, result)
def testTable(self): # tests that correct table is created OutputWorkspaceName = "outputws1" alg_test = run_algorithm("FindEPP", InputWorkspace=self._input_ws, OutputWorkspace=OutputWorkspaceName, Version=1) self.assertTrue(alg_test.isExecuted()) wsoutput = AnalysisDataService.retrieve(OutputWorkspaceName) self.assertEqual(2, wsoutput.rowCount()) self.assertEqual(9, wsoutput.columnCount()) columns = [ 'WorkspaceIndex', 'PeakCentre', 'PeakCentreError', 'Sigma', 'SigmaError', 'Height', 'HeightError', 'chiSq', 'FitStatus' ] self.assertEqual(columns, wsoutput.getColumnNames()) DeleteWorkspace(wsoutput)
def _save(self, runnumber, basename, norm): if not self.getProperty("SaveData").value: return saveDir = self.getProperty("OutputDirectory").value.strip() if len(saveDir) <= 0: self.log().notice('Using default save location') saveDir = os.path.join(self.get_IPTS_Local(runnumber), 'shared', 'data') self.log().notice('Writing to \'' + saveDir + '\'') if norm == 'None': SaveNexusProcessed(InputWorkspace='WS_red', Filename=os.path.join(saveDir, 'nexus', basename + '.nxs')) SaveAscii(InputWorkspace='WS_red', Filename=os.path.join(saveDir, 'd_spacing', basename + '.dat')) ConvertUnits(InputWorkspace='WS_red', OutputWorkspace='WS_tof', Target="TOF", AlignBins=False) else: SaveNexusProcessed(InputWorkspace='WS_nor', Filename=os.path.join(saveDir, 'nexus', basename + '.nxs')) SaveAscii(InputWorkspace='WS_nor', Filename=os.path.join(saveDir, 'd_spacing', basename + '.dat')) ConvertUnits(InputWorkspace='WS_nor', OutputWorkspace='WS_tof', Target="TOF", AlignBins=False) SaveGSS(InputWorkspace='WS_tof', Filename=os.path.join(saveDir, 'gsas', basename + '.gsa'), Format='SLOG', SplitFiles=False, Append=False, ExtendedHeader=True) SaveFocusedXYE(InputWorkspace='WS_tof', Filename=os.path.join(saveDir, 'fullprof', basename + '.dat'), SplitFiles=True, Append=False) DeleteWorkspace(Workspace='WS_tof')
def __determineCharacterizations(self, filename, wkspname): useCharTable = self.__isCharacterizationsNeeded() needToLoadCal = self.__needToLoadCal() # something needs to use the workspace and it needs to not already be in memory loadFile = (useCharTable or needToLoadCal) and (not mtd.doesExist(wkspname)) # input workspace is only needed to find a row in the characterizations table tempname = None if loadFile: if useCharTable or needToLoadCal: tempname = '__%s_temp' % wkspname # set the loader for this file try: # MetaDataOnly=True is only supported by LoadEventNexus loader = self.__createLoader(filename, tempname, MetaDataOnly=True) loader.execute() # get the underlying loader name if we used the generic one if self.__loaderName == 'Load': self.__loaderName = loader.getPropertyValue('LoaderName') except RuntimeError: # give up and load the whole file - this can be expensive Load(OutputWorkspace=tempname, Filename=filename) else: tempname = wkspname # assume it is already loaded # some bit of data has been loaded so use it to get the characterizations self.__setupCalibration(tempname) # put together argument list for determining characterizations args = dict(ReductionProperties=self.getProperty('ReductionProperties').valueAsStr) for name in PROPS_FOR_PD_CHARACTER: prop = self.getProperty(name) if not prop.isDefault: args[name] = prop.value if tempname is not None: args['InputWorkspace'] = tempname if useCharTable: args['Characterizations'] = self.charac if useCharTable: PDDetermineCharacterizations(**args) if loadFile and (useCharTable or needToLoadCal): DeleteWorkspace(Workspace=tempname)
def __determineCharacterizations(self, filename, wkspname): tempname = '__%s_temp' % wkspname Load(Filename=filename, OutputWorkspace=tempname, MetaDataOnly=True) # put together argument list args = dict(InputWorkspace=tempname, ReductionProperties=self.getProperty( 'ReductionProperties').valueAsStr) for name in PROPS_FOR_PD_CHARACTER: prop = self.getProperty(name) if not prop.isDefault: args[name] = prop.value if self.charac is not None: args['Characterizations'] = self.charac PDDetermineCharacterizations(**args) DeleteWorkspace(Workspace=tempname)
def dynamicsusceptibility(workspace, temperature, outputName=None, zeroEnergyEpsilon=1e-6): """Convert :math:`S(Q,E)` to susceptibility :math:`\chi''(Q,E)`. #. If the X units are not in DeltaE, the workspace is transposed #. The Y data in *workspace* is multiplied by :math:`1 - e^{\Delta E / (kT)}` #. Y data in the bin closest to 0 meV and within -*zeroEnergyEpsilon* < :math:`\Delta E` < *zeroEnergyEpsilon* is set to 0 #. If the input was transposed, transpose the output as well :param workspace: a :math:`S(Q,E)` workspace to convert :type workspace: :class:`mantid.api.MatrixWorkspace` :param temperature: temperature in Kelvin :type temperature: float :param outputName: name of the output workspace. If :class:`None`, the output will be given some generated name. :type outputName: str or None :param zeroEnergyEpsilon: if a bin center is within this value from 0, the bin's value is set to zero. :type zeroEnergyEpsilon: float :returns: a :class:`mantid.api.MatrixWorkspace` containing :math:`\chi''(Q,E)` """ workspace = _normws(workspace) horAxis = workspace.getAxis(0) horUnit = horAxis.getUnit().unitID() doTranspose = horUnit != 'DeltaE' if outputName is None: outputName = 'CHIofQW_{}'.format(str(workspace)) if doTranspose: workspace = Transpose(workspace, OutputWorkspace='__transposed_SofQW_', EnableLogging=False) c = 1e-3 * constants.e / constants.k / temperature outWS = OneMinusExponentialCor(workspace, OutputWorkspace=outputName, C=c, Operation='Multiply', EnableLogging=False) _removesingularity(outWS, zeroEnergyEpsilon) if doTranspose: outWS = Transpose(outWS, OutputWorkspace=outputName, EnableLogging=False) DeleteWorkspace('__transposed_SofQW_', EnableLogging=False) outWS.setYUnit("Dynamic susceptibility") return outWS
def loadUBFiles(self, ubFiles, omegaHand, phiHand, omegaLogName, phiLogName): """ load the ub files and update the :param ubFiles: list of paths to saved UB files :param omegaHand: handedness of omega rotation (ccw/cw) :param phiHand: handedness of phi rotation (ccw/cw) :param omegaLogName: name of log entry for omega angle :param phiLogName: name of log entry for phi angle :return: matUB: list containing the UB for each run :return: omega: array of omega values from log of each run :return: phiRef: array of nominal phi values from log of each run """ matUB = [] # container to hold UB matrix arrays omega = np.zeros( len(ubFiles)) # rot around vertical axis (assumed to be correct) phiRef = np.zeros( len(ubFiles)) # rot around gonio axis (needs to be refined) for irun in range(0, len(ubFiles)): # get rotation angles from logs (handedness given in input) # these rotation matrices are defined in right-handed coordinate system (i.e. omegaHand = 1 etc.) _, fname = path.split(ubFiles[irun]) dataPath = FileFinder.findRuns(fname.split('.mat')[0])[0] tmpWS = CreateSampleWorkspace(StoreInADS=False) if dataPath[-4:] == ".raw": # assume log is kept separately in a .log file with same path LoadLog(Workspace=tmpWS, Filename="".join(dataPath[:-4] + '.log')) elif dataPath[-4:] == '.nxs': # logs are kept with data in nexus file LoadNexusLogs(Workspace=tmpWS, Filename=dataPath) # read omega and phi (in RH coords) omega[irun] = omegaHand * tmpWS.getRun().getLogData( omegaLogName).value[0] phiRef[irun] = phiHand * tmpWS.getRun().getLogData( phiLogName).value[0] # load UB LoadIsawUB(InputWorkspace=tmpWS, Filename=ubFiles[irun], CheckUMatrix=True) tmpUB = tmpWS.sample().getOrientedLattice().getUB() # permute axes to use IPNS convention (as in saved .mat file) matUB += [tmpUB[[2, 0, 1], :]] DeleteWorkspace(tmpWS) return matUB, omega, phiRef
def determineChunking(filename, chunkSize): chunks = DetermineChunking(Filename=filename, MaxChunkSize=chunkSize, OutputWorkspace='chunks') strategy = [] for row in chunks: strategy.append(row) # For table with no rows if len(strategy) == 0: strategy.append({}) # delete chunks workspace chunks = str(chunks) DeleteWorkspace(Workspace='chunks') return strategy
def test_get_masked_det_ids(self): # Arrange test_workspace_for_masked_det_ids = CreateSampleWorkspace("Histogram") MaskDetectors(Workspace=test_workspace_for_masked_det_ids, DetectorList=[100, 102, 104]) # Act masked_det_ids = list( get_masked_det_ids(test_workspace_for_masked_det_ids)) # Assert self.assertTrue(100 in masked_det_ids) self.assertTrue(102 in masked_det_ids) self.assertTrue(104 in masked_det_ids) self.assertEqual(len(masked_det_ids), 3) # Clean up DeleteWorkspace(test_workspace_for_masked_det_ids)