def _applyIncidentEnergyCalibration(ws, eiWS, wsNames, report, algorithmLogging): """Update incident energy and wavelength in the sample logs.""" originalEnergy = ws.getRun().getLogData('Ei').value originalWavelength = ws.getRun().getLogData('wavelength').value energy = eiWS.readY(0)[0] wavelength = UnitConversion.run('Energy', 'Wavelength', energy, 0, 0, 0, Direct, 5) AddSampleLog(Workspace=ws, LogName='Ei', LogText=str(energy), LogType='Number', NumberType='Double', LogUnit='meV', EnableLogging=algorithmLogging) AddSampleLog(Workspace=ws, Logname='wavelength', LogText=str(wavelength), LogType='Number', NumberType='Double', LogUnit='Angstrom', EnableLogging=algorithmLogging) report.notice("Applied Ei calibration to '" + str(ws) + "'.") report.notice('Original Ei: {} new Ei: {}.'.format(originalEnergy, energy)) report.notice('Original wavelength: {} new wavelength {}.'.format( originalWavelength, wavelength)) return ws
def _applyIncidentEnergyCalibration(ws, wsType, eiWS, wsNames, report, algorithmLogging): """Update incident energy and wavelength in the sample logs.""" originalEnergy = ws.getRun().getLogData('Ei').value originalWavelength = ws.getRun().getLogData('wavelength').value energy = eiWS.readY(0)[0] wavelength = UnitConversion.run('Energy', 'Wavelength', energy, 0, 0, 0, Direct, 5) if wsType == common.WS_CONTENT_DETS: calibratedWSName = wsNames.withSuffix('incident_energy_calibrated_detectors') elif wsType == common.WS_CONTENT_MONS: calibratedWSName = wsNames.withSuffix('incident_energy_calibrated_monitors') else: raise RuntimeError('Unknown workspace content type') calibratedWS = CloneWorkspace(InputWorkspace=ws, OutputWorkspace=calibratedWSName, EnableLogging=algorithmLogging) AddSampleLog(Workspace=calibratedWS, LogName='Ei', LogText=str(energy), LogType='Number', NumberType='Double', LogUnit='meV', EnableLogging=algorithmLogging) AddSampleLog(Workspace=calibratedWS, Logname='wavelength', LogText=str(wavelength), LogType='Number', NumberType='Double', LogUnit='Angstrom', EnableLogging=algorithmLogging) report.notice("Applied Ei calibration to '" + str(ws) + "'.") report.notice('Original Ei: {} new Ei: {}.'.format(originalEnergy, energy)) report.notice('Original wavelength: {} new wavelength {}.'.format(originalWavelength, wavelength)) return calibratedWS
def calc(pixelID): out = np.zeros((y, x)) L2 = ws.getInstrument().getDetector(pixelID).getDistance( ws.getInstrument().getSample()) twoTheta = ws.getDetector(pixelID).getTwoTheta(samplePos, beamDirection) counts = ws.getEventList(pixelID).getNumberEvents() #total_counts+=counts print 'PixelID =', pixelID, 'Count at pixel =', counts, 'Total counts = ', total_counts, '2Theta = ', twoTheta events = ws.getEventList(pixelID) n = events.getNumberEvents() pulse = events.getPulseTimes() tofs = events.getTofs() tdc_index = 0 for event in range(n): while pulse[event] > chopper_tdc[tdc_index]: tdc_index += 1 yyy = (chopper_tdc[tdc_index] - pulse[event]).total_microseconds() % chopper_per x_q = UnitConversion.run(src_unit, dest_unit, tofs[event], L1, L2, twoTheta, emode, efixed) xxx = int(x_q / x_bin_size) for pk in range(y): ij = ((yyy - pk * bin_size) / chopper_per * 360.) % 360 if np.searchsorted(sequence_sum, ij) % 2 == 1: fact = 0.5 else: fact = -0.5 out[pk, xxx] += fact return out
def calc(pixelID): out=np.zeros((y,x)) L2=ws.getInstrument().getDetector(pixelID).getDistance(ws.getInstrument().getSample()) twoTheta=ws.getDetector(pixelID).getTwoTheta(samplePos,beamDirection) counts=ws.getEventList(pixelID).getNumberEvents() #total_counts+=counts print 'PixelID =',pixelID,'Count at pixel =',counts,'Total counts = ',total_counts,'2Theta = ',twoTheta events=ws.getEventList(pixelID) n=events.getNumberEvents() pulse = events.getPulseTimes() tofs = events.getTofs() tdc_index=0 for event in range(n): while pulse[event]>chopper_tdc[tdc_index]: tdc_index+=1 yyy=(chopper_tdc[tdc_index]-pulse[event]).total_microseconds()%chopper_per x_q=UnitConversion.run(src_unit,dest_unit,tofs[event],L1,L2,twoTheta,emode,efixed) xxx=int(x_q/x_bin_size) for pk in range(y): ij = ((yyy-pk*bin_size)/chopper_per*360.)%360 if np.searchsorted(sequence_sum,ij)%2==1: fact = 0.5 else: fact = -0.5 out[pk,xxx]+=fact return out
def eiWavelengthUpdateEvent(self): if self.masterDict['instrument'] == 'WAND\u00B2': ei = UnitConversion.run('Wavelength', 'Energy', self.masterDict['Ei'], 0, 0, 0, Elastic, 0) offset = ei * 0.01 lowerBound = - offset upperBound = offset self.dimensionWidget.set_editMin4(lowerBound) self.dimensionWidget.set_editMax4(upperBound)
def _wavelengthToTOF(self, x, ws, beamCentreIndex): """Return x converted from wavelength to time of flight units.""" instrument = ws.getInstrument() samplePos = instrument.getSample().getPos() sourcePos = instrument.getSource().getPos() l1 = (samplePos - sourcePos).norm() centreDet = ws.getDetector(beamCentreIndex) detPos = centreDet.getPos() l2 = (detPos - samplePos).norm() return UnitConversion.run('Wavelength', 'TOF' , x, l1, l2, 0., DeltaEModeType.Elastic, 0.)
def test_run_accepts_string_units(self): src_unit = "Wavelength" src_value = 1.5 dest_unit = "Momentum" l1 = l2 = theta = efixed = 0.0 emode = DeltaEModeType.Indirect; expected = 2.0*math.pi/src_value result = UnitConversion.run(src_unit, dest_unit, src_value, l1, l2, theta, emode, efixed) self.assertAlmostEqual(result, expected, 12)
def PyExec(self): runs = self.getProperty("Filename").value if not runs: ipts = self.getProperty("IPTS").value runs = ['/HFIR/HB2C/IPTS-{}/nexus/HB2C_{}.nxs.h5'.format(ipts, run) for run in self.getProperty("RunNumbers").value] wavelength = self.getProperty("wavelength").value outWS = self.getPropertyValue("OutputWorkspace") group_names = [] for run in runs: LoadEventNexus(Filename=run, OutputWorkspace='__tmp_load', LoadMonitors=True, EnableLogging=False) Integration(InputWorkspace='__tmp_load', OutputWorkspace='__tmp_load', EnableLogging=False) if self.getProperty("ApplyMask").value: MaskBTP('__tmp_load', Pixel='1,2,511,512', EnableLogging=False) if mtd['__tmp_load'].getRunNumber() > 26600: # They changed pixel mapping and bank name order here MaskBTP('__tmp_load', Bank='1', Tube='479-480', EnableLogging=False) MaskBTP('__tmp_load', Bank='8', Tube='1-2', EnableLogging=False) else: MaskBTP('__tmp_load', Bank='8', Tube='475-480', EnableLogging=False) mtd['__tmp_load'].getAxis(0).setUnit("Wavelength") w = [wavelength-0.001, wavelength+0.001] for idx in range(mtd['__tmp_load'].getNumberHistograms()): mtd['__tmp_load'].setX(idx, w) SetGoniometer('__tmp_load', Axis0="HB2C:Mot:s1,0,1,0,1", EnableLogging=False) AddSampleLog('__tmp_load', LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText=str(mtd['__tmp_load'+'_monitors'].getNumberEvents()), EnableLogging=False) DeleteWorkspace('__tmp_load'+'_monitors', EnableLogging=False) AddSampleLog('__tmp_load', LogName="Wavelength", LogType='Number', NumberType='Double', LogText=str(wavelength), EnableLogging=False) AddSampleLog('__tmp_load', LogName="Ei", LogType='Number', NumberType='Double', LogText=str(UnitConversion.run('Wavelength', 'Energy', wavelength, 0, 0, 0, Elastic, 0)), EnableLogging=False) if len(runs) == 1: RenameWorkspace('__tmp_load', outWS, EnableLogging=False) else: outName = outWS+"_"+str(mtd['__tmp_load'].getRunNumber()) group_names.append(outName) RenameWorkspace('__tmp_load', outName, EnableLogging=False) if len(runs) > 1: GroupWorkspaces(group_names, OutputWorkspace=outWS, EnableLogging=False) self.setProperty('OutputWorkspace', outWS)
def test_run_accepts_params_version(self): src_unit = "Wavelength" src_value = 1.5 dest_unit = "Momentum" l1 = l2 = theta = efixed = 0.0 emode = DeltaEModeType.Indirect; expected = 2.0*math.pi/src_value params = UnitParametersMap() params[UnitParams.l2] = l2 params[UnitParams.twoTheta] = theta # Haven't got a dictionary to convert automatically into std::unordered_map yet #params = {UnitParams.l2: l2, UnitParams.twoTheta: theta} result = UnitConversion.run(src_unit, dest_unit, src_value, l1, emode, params) self.assertAlmostEqual(result, expected, 12)
def _to_spectrum_axis(self, workspace_in, workspace_out, mask, instrument_donor=None): target = self.getProperty("Target").value wavelength = self.getProperty("Wavelength").value e_fixed = UnitConversion.run('Wavelength', 'Energy', wavelength, 0, 0, 0, Elastic, 0) ExtractUnmaskedSpectra( InputWorkspace=workspace_in, OutputWorkspace=workspace_out, MaskWorkspace=mask, EnableLogging=False, ) if isinstance(mtd[workspace_out], IEventWorkspace): Integration( InputWorkspace=workspace_out, OutputWorkspace=workspace_out, EnableLogging=False, ) if instrument_donor: CopyInstrumentParameters( InputWorkspace=instrument_donor, OutputWorkspace=workspace_out, EnableLogging=False, ) ConvertSpectrumAxis( InputWorkspace=workspace_out, OutputWorkspace=workspace_out, Target=target, EFixed=e_fixed, EnableLogging=False, ) Transpose( InputWorkspace=workspace_out, OutputWorkspace=workspace_out, EnableLogging=False, ) return workspace_out
def PyExec(self): filename = self.getProperty("Filename").value wavelength = self.getProperty("wavelength").value outWS = self.getPropertyValue("OutputWorkspace") LoadEventNexus(Filename=filename, OutputWorkspace=outWS, LoadMonitors=True) Integration(InputWorkspace=outWS, OutputWorkspace=outWS) if self.getProperty("ApplyMask").value: MaskBTP(outWS, Bank='8', Tube='449-480') MaskBTP(outWS, Pixel='1,2,511,512') mtd[outWS].getAxis(0).setUnit("Wavelength") w = [wavelength - 0.001, wavelength + 0.001] for idx in range(mtd[outWS].getNumberHistograms()): mtd[outWS].setX(idx, w) SetGoniometer(outWS, Axis0="HB2C:Mot:s1,0,1,0,1") AddSampleLog(outWS, LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText=str(mtd[outWS + '_monitors'].getNumberEvents())) DeleteWorkspace(outWS + '_monitors') AddSampleLog(outWS, LogName="Wavelength", LogType='Number', NumberType='Double', LogText=str(wavelength)) AddSampleLog(outWS, LogName="Ei", LogType='Number', NumberType='Double', LogText=str( UnitConversion.run('Wavelength', 'Energy', wavelength, 0, 0, 0, Elastic, 0))) self.setProperty('OutputWorkspace', outWS)
def _applyIncidentEnergyCalibration(ws, eiWS, wsNames, report, algorithmLogging): """Update incident energy and wavelength in the sample logs.""" originalEnergy = ws.getRun().getLogData('Ei').value originalWavelength = ws.getRun().getLogData('wavelength').value energy = eiWS.readY(0)[0] wavelength = UnitConversion.run('Energy', 'Wavelength', energy, 0, 0, 0, Direct, 5) AddSampleLog(Workspace=ws, LogName='Ei', LogText=str(energy), LogType='Number', NumberType='Double', LogUnit='meV', EnableLogging=algorithmLogging) AddSampleLog(Workspace=ws, Logname='wavelength', LogText=str(wavelength), LogType='Number', NumberType='Double', LogUnit='Angstrom', EnableLogging=algorithmLogging) report.notice("Applied Ei calibration to '" + str(ws) + "'.") report.notice('Original Ei: {} new Ei: {}.'.format(originalEnergy, energy)) report.notice('Original wavelength: {} new wavelength {}.'.format(originalWavelength, wavelength)) return ws
def updateFigure(self): # noqa: C901 # pylint: disable=too-many-branches if self.updatedInstrument or self.progress_canceled: self.progress_canceled = False # get goniometer settings first gonioAxis0values = numpy.arange( self.masterDict['gonioMinvals'][0], self.masterDict['gonioMaxvals'][0] + 0.1 * self.masterDict['gonioSteps'][0], self.masterDict['gonioSteps'][0]) gonioAxis1values = numpy.arange( self.masterDict['gonioMinvals'][1], self.masterDict['gonioMaxvals'][1] + 0.1 * self.masterDict['gonioSteps'][1], self.masterDict['gonioSteps'][1]) gonioAxis2values = numpy.arange( self.masterDict['gonioMinvals'][2], self.masterDict['gonioMaxvals'][2] + 0.1 * self.masterDict['gonioSteps'][2], self.masterDict['gonioSteps'][2]) self.iterations = len(gonioAxis0values) * len( gonioAxis1values) * len(gonioAxis2values) if self.iterations > 10: reply = QtWidgets.QMessageBox.warning( self, 'Goniometer', "More than 10 goniometer settings. This might be long.\n" "Are you sure you want to proceed?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.No: return if self.wg is not None: mantid.simpleapi.DeleteWorkspace(self.wg) instrumentName = self.masterDict['instrument'] if instrumentName == 'WAND\u00B2': instrumentName = 'WAND' mantid.simpleapi.LoadEmptyInstrument( mantid.api.ExperimentInfo.getInstrumentFilename( instrumentName), OutputWorkspace="__temp_instrument") if self.masterDict['instrument'] == 'HYSPEC': mantid.simpleapi.AddSampleLog(Workspace="__temp_instrument", LogName='msd', LogText='1798.5', LogType='Number Series') mantid.simpleapi.AddSampleLog(Workspace="__temp_instrument", LogName='s2', LogText=str( self.masterDict['S2']), LogType='Number Series') mantid.simpleapi.LoadInstrument(Workspace="__temp_instrument", RewriteSpectraMap=True, InstrumentName="HYSPEC") elif self.masterDict['instrument'] == 'EXED': mantid.simpleapi.RotateInstrumentComponent( Workspace="__temp_instrument", ComponentName='Tank', Y=1, Angle=str(self.masterDict['S2']), RelativeRotation=False) elif instrumentName == 'WAND': mantid.simpleapi.AddSampleLog(Workspace="__temp_instrument", LogName='HB2C:Mot:s2.RBV', LogText=str( self.masterDict['S2']), LogType='Number Series') mantid.simpleapi.AddSampleLog(Workspace="__temp_instrument", LogName='HB2C:Mot:detz.RBV', LogText=str( self.masterDict['DetZ']), LogType='Number Series') mantid.simpleapi.LoadInstrument(Workspace="__temp_instrument", RewriteSpectraMap=True, InstrumentName="WAND") # masking if 'maskFilename' in self.masterDict and len( self.masterDict['maskFilename'].strip()) > 0: try: __maskWS = mantid.simpleapi.Load( self.masterDict['maskFilename']) mantid.simpleapi.MaskDetectors( Workspace="__temp_instrument", MaskedWorkspace=__maskWS) except (ValueError, RuntimeError) as e: reply = QtWidgets.QMessageBox.critical( self, 'Error', "The following error has occurred in loading the mask:\n" + str(e) + "\nDo you want to continue without mask?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.No: return if self.masterDict['makeFast']: sp = list( range( mantid.mtd["__temp_instrument"].getNumberHistograms())) tomask = sp[1::4] + sp[2::4] + sp[3::4] mantid.simpleapi.MaskDetectors("__temp_instrument", SpectraList=tomask) progressDialog = QtWidgets.QProgressDialog(self) progressDialog.setMinimumDuration(0) progressDialog.setCancelButtonText("&Cancel") progressDialog.setRange(0, self.iterations) progressDialog.setWindowTitle("DGSPlanner progress") groupingStrings = self._create_goniometer_workspaces( gonioAxis0values, gonioAxis1values, gonioAxis2values, progressDialog) if groupingStrings is None: return progressDialog.close() mantid.simpleapi.DeleteWorkspace("__temp_instrument") self.wg = mantid.simpleapi.GroupWorkspaces( groupingStrings, OutputWorkspace="__temp_instrument") self.updatedInstrument = False # set the UB if self.updatedOL or not self.wg[0].sample().hasOrientedLattice(): mantid.simpleapi.SetUB(self.wg, UB=self.ol.getUB()) self.updatedOL = False # calculate coverage dimensions = ['Q1', 'Q2', 'Q3', 'DeltaE'] progressDialog = QtWidgets.QProgressDialog(self) progressDialog.setMinimumDuration(0) progressDialog.setCancelButtonText("&Cancel") progressDialog.setRange(0, self.iterations) progressDialog.setWindowTitle("DGSPlanner progress") if self.masterDict['instrument'] == 'WAND\u00B2': ei = UnitConversion.run('Wavelength', 'Energy', self.masterDict['Ei'], 0, 0, 0, Elastic, 0) else: ei = self.masterDict['Ei'] for i in range(self.iterations): progressDialog.setValue(i) progressDialog.setLabelText("Calculating orientation %d of %d..." % (i, self.iterations)) QtWidgets.qApp.processEvents() if progressDialog.wasCanceled(): self.progress_canceled = True progressDialog.close() return __mdws = mantid.simpleapi.CalculateCoverageDGS( self.wg[i], Q1Basis=self.masterDict['dimBasis'][0], Q2Basis=self.masterDict['dimBasis'][1], Q3Basis=self.masterDict['dimBasis'][2], IncidentEnergy=ei, Dimension1=dimensions[self.masterDict['dimIndex'][0]], Dimension1Min=float2Input(self.masterDict['dimMin'][0]), Dimension1Max=float2Input(self.masterDict['dimMax'][0]), Dimension1Step=float2Input(self.masterDict['dimStep'][0]), Dimension2=dimensions[self.masterDict['dimIndex'][1]], Dimension2Min=float2Input(self.masterDict['dimMin'][1]), Dimension2Max=float2Input(self.masterDict['dimMax'][1]), Dimension2Step=float2Input(self.masterDict['dimStep'][1]), Dimension3=dimensions[self.masterDict['dimIndex'][2]], Dimension3Min=float2Input(self.masterDict['dimMin'][2]), Dimension3Max=float2Input(self.masterDict['dimMax'][2]), Dimension4=dimensions[self.masterDict['dimIndex'][3]], Dimension4Min=float2Input(self.masterDict['dimMin'][3]), Dimension4Max=float2Input(self.masterDict['dimMax'][3])) if i == 0: intensity = __mdws.getSignalArray( )[:, :, 0, 0] * 1. # to make it writeable else: if self.colorButton.isChecked(): tempintensity = __mdws.getSignalArray()[:, :, 0, 0] intensity[numpy.where(tempintensity > 0)] = i + 1. else: tempintensity = __mdws.getSignalArray()[:, :, 0, 0] intensity[numpy.where(tempintensity > 0)] = 1. progressDialog.close() x = numpy.linspace( __mdws.getDimension(0).getMinimum(), __mdws.getDimension(0).getMaximum(), intensity.shape[0]) y = numpy.linspace( __mdws.getDimension(1).getMinimum(), __mdws.getDimension(1).getMaximum(), intensity.shape[1]) Y, X = numpy.meshgrid(y, x) xx, yy = self.tr(X, Y) Z = numpy.ma.masked_array(intensity, intensity == 0) Z = Z[:-1, :-1] # plotting if self.sender() is self.plotButton or self.needToClear: self.figure.clear() self.trajfig.clear() self.figure.add_subplot(self.trajfig) self.needToClear = False self.trajfig.pcolorfast(xx, yy, Z) if self.aspectButton.isChecked(): self.trajfig.set_aspect(1.) else: self.trajfig.set_aspect('auto') self.trajfig.set_xlabel(self.masterDict['dimNames'][0]) self.trajfig.set_ylabel(self.masterDict['dimNames'][1]) self.trajfig.grid(True) self.canvas.draw() mantid.simpleapi.DeleteWorkspace(__mdws)
def _fillTemplateTOFWorkspace(templateWS, bkgLevel): """Fill a TOF workspace with somewhat sane data.""" nHistograms = templateWS.getNumberHistograms() E_i = 23.0 nBins = 128 binWidth = 2.63 elasticIndex = int(nBins / 3) monitorElasticIndex = int(nBins / 2) xs = numpy.empty(nHistograms * (nBins + 1)) ys = numpy.empty(nHistograms * nBins) es = numpy.empty(nHistograms * nBins) spectrumInfo = templateWS.spectrumInfo() instrument = templateWS.getInstrument() l1 = spectrumInfo.l1() l2 = float(instrument.getStringParameter('l2')[0]) tofElastic = UnitConversion.run('Energy', 'TOF', E_i, l1, l2, 0.0, DeltaEModeType.Direct, 0.0) tofBegin = tofElastic - elasticIndex * binWidth monitorSampleDistance = 0.5 tofElasticMonitor = tofBegin + monitorElasticIndex * binWidth tofMonitorDetector = UnitConversion.run('Energy', 'TOF', E_i, monitorSampleDistance, l2, 0.0, DeltaEModeType.Direct, 0.0) elasticPeakSigma = nBins * binWidth * 0.03 elasticPeakHeight = 1723.0 bkgMonitor = 1 def fillBins(histogramIndex, elasticTOF, elasticPeakHeight, bkgLevel): xIndexOffset = histogramIndex * (nBins + 1) yIndexOffset = histogramIndex * nBins xs[xIndexOffset] = tofBegin - binWidth / 2 for binIndex in range(nBins): x = tofBegin + binIndex * binWidth xs[xIndexOffset + binIndex + 1] = x + binWidth / 2 y = round( _gaussian(x, elasticPeakHeight, elasticTOF, elasticPeakSigma)) + bkgLevel ys[yIndexOffset + binIndex] = y es[yIndexOffset + binIndex] = numpy.sqrt(y) for histogramIndex in range(0, nHistograms - 1): trueL2 = spectrumInfo.l2(histogramIndex) trueTOF = UnitConversion.run('Energy', 'TOF', E_i, l1, trueL2, 0.0, DeltaEModeType.Direct, 0.0) fillBins(histogramIndex, trueTOF, elasticPeakHeight, bkgLevel) fillBins(nHistograms - 1, tofElasticMonitor, 1623 * elasticPeakHeight, bkgMonitor) kwargs = { 'DataX': xs, 'DataY': ys, 'DataE': es, 'NSpec': nHistograms, 'ParentWorkspace': templateWS, 'child': True } alg = run_algorithm('CreateWorkspace', **kwargs) ws = alg.getProperty('OutputWorkspace').value ws.getAxis(0).setUnit('TOF') run = ws.run() run.addProperty('Ei', float(E_i), True) wavelength = UnitConversion.run('Energy', 'Wavelength', E_i, l1, l2, 0.0, DeltaEModeType.Direct, 0.0) run.addProperty('wavelength', float(wavelength), True) pulseInterval = \ tofMonitorDetector + (monitorElasticIndex - elasticIndex) * binWidth run.addProperty('pulse_interval', float(pulseInterval * 1e-6), True) run.addProperty('Detector.elasticpeak', int(elasticIndex), True) kwargs = { 'Workspace': ws, 'LogName': 'monitor.monsum', 'LogText': str(1000), 'LogType': 'Number', 'NumberType': 'Int', 'child': True } run_algorithm('AddSampleLog', **kwargs) kwargs = { 'Workspace': ws, 'ParameterName': 'default-incident-monitor-spectrum', 'ParameterType': 'Number', 'Value': str(98305), 'child': True } run_algorithm('SetInstrumentParameter', **kwargs) return ws
def PyExec(self): runs = self.getProperty("Filename").value if not runs: ipts = self.getProperty("IPTS").value runs = [ '/HFIR/HB2C/IPTS-{}/nexus/HB2C_{}.nxs.h5'.format(ipts, run) for run in self.getProperty("RunNumbers").value ] wavelength = self.getProperty("wavelength").value outWS = self.getPropertyValue("OutputWorkspace") group_names = [] grouping = self.getProperty("Grouping").value if grouping == 'None': grouping = 1 else: grouping = 2 if grouping == '2x2' else 4 for i, run in enumerate(runs): data = np.zeros((512 * 480 * 8), dtype=np.int64) with h5py.File(run, 'r') as f: monitor_count = f['/entry/monitor1/total_counts'].value[0] run_number = f['/entry/run_number'].value[0] for b in range(8): data += np.bincount(f['/entry/bank' + str(b + 1) + '_events/event_id'].value, minlength=512 * 480 * 8) data = data.reshape((480 * 8, 512)) if grouping == 2: data = data[::2, ::2] + data[ 1::2, ::2] + data[::2, 1::2] + data[1::2, 1::2] elif grouping == 4: data = (data[::4, ::4] + data[1::4, ::4] + data[2::4, ::4] + data[3::4, ::4] + data[::4, 1::4] + data[1::4, 1::4] + data[2::4, 1::4] + data[3::4, 1::4] + data[::4, 2::4] + data[1::4, 2::4] + data[2::4, 2::4] + data[3::4, 2::4] + data[::4, 3::4] + data[1::4, 3::4] + data[2::4, 3::4] + data[3::4, 3::4]) CreateWorkspace(DataX=[wavelength - 0.001, wavelength + 0.001], DataY=data, DataE=np.sqrt(data), UnitX='Wavelength', YUnitLabel='Counts', NSpec=1966080 // grouping**2, OutputWorkspace='__tmp_load', EnableLogging=False) LoadNexusLogs('__tmp_load', Filename=run, EnableLogging=False) AddSampleLog('__tmp_load', LogName="monitor_count", LogType='Number', NumberType='Double', LogText=str(monitor_count), EnableLogging=False) AddSampleLog('__tmp_load', LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText=str(monitor_count), EnableLogging=False) AddSampleLog('__tmp_load', LogName="Wavelength", LogType='Number', NumberType='Double', LogText=str(wavelength), EnableLogging=False) AddSampleLog('__tmp_load', LogName="Ei", LogType='Number', NumberType='Double', LogText=str( UnitConversion.run('Wavelength', 'Energy', wavelength, 0, 0, 0, Elastic, 0)), EnableLogging=False) AddSampleLog('__tmp_load', LogName="run_number", LogText=run_number, EnableLogging=False) if grouping > 1: # Fix detector IDs per spectrum before loading instrument __tmp_load = mtd['__tmp_load'] for n in range(__tmp_load.getNumberHistograms()): s = __tmp_load.getSpectrum(n) for i in range(grouping): for j in range(grouping): s.addDetectorID( int(n * grouping % 512 + n // (512 / grouping) * 512 * grouping + j + i * 512)) LoadInstrument('__tmp_load', InstrumentName='WAND', RewriteSpectraMap=False, EnableLogging=False) else: LoadInstrument('__tmp_load', InstrumentName='WAND', RewriteSpectraMap=True, EnableLogging=False) SetGoniometer('__tmp_load', Axis0="HB2C:Mot:s1,0,1,0,1", EnableLogging=False) if self.getProperty("ApplyMask").value: MaskBTP('__tmp_load', Pixel='1,2,511,512', EnableLogging=False) if mtd['__tmp_load'].getRunNumber( ) > 26600: # They changed pixel mapping and bank name order here MaskBTP('__tmp_load', Bank='1', Tube='479-480', EnableLogging=False) MaskBTP('__tmp_load', Bank='8', Tube='1-2', EnableLogging=False) else: MaskBTP('__tmp_load', Bank='8', Tube='475-480', EnableLogging=False) if len(runs) == 1: RenameWorkspace('__tmp_load', outWS, EnableLogging=False) else: outName = outWS + "_" + str(mtd['__tmp_load'].getRunNumber()) group_names.append(outName) RenameWorkspace('__tmp_load', outName, EnableLogging=False) if len(runs) > 1: GroupWorkspaces(group_names, OutputWorkspace=outWS, EnableLogging=False) self.setProperty('OutputWorkspace', outWS)
bin_size=10. # 10ms bins x_bin_size = 0.02 # A^-1 y = int(math.ceil( chopper_per/bin_size )) #x = int(math.ceil( 1e6/60/bin_size )) #out = np.zeros((y,x)) total_counts=0 #results = np.zeros((y,x)) src_unit = "TOF" dest_unit = "MomentumTransfer" efixed = 0 emode = DeltaEModeType.Elastic #UnitConversion.run(src_unit, dest_unit, src_value, l1, l2, twoTheta, emode, efixed) x = int((UnitConversion.run(src_unit, dest_unit, 3000, L1, ws.getInstrument().getDetector(0).getDistance(ws.getInstrument().getSample()), math.pi , emode, efixed)+1)/x_bin_size) results = np.zeros((y,x)) def calc(pixelID): out=np.zeros((y,x)) L2=ws.getInstrument().getDetector(pixelID).getDistance(ws.getInstrument().getSample()) twoTheta=ws.getDetector(pixelID).getTwoTheta(samplePos,beamDirection) counts=ws.getEventList(pixelID).getNumberEvents() #total_counts+=counts print 'PixelID =',pixelID,'Count at pixel =',counts,'Total counts = ',total_counts,'2Theta = ',twoTheta events=ws.getEventList(pixelID) n=events.getNumberEvents() pulse = events.getPulseTimes() tofs = events.getTofs() tdc_index=0 for event in range(n):
def convert_single_value_dSpacing_to_TOF(d, diff_consts_ws): diff_consts = get_diffractometer_constants_from_workspace(diff_consts_ws) # L1 = 0 is ignored when diff constants supplied tof = UnitConversion.run("dSpacing", "TOF", d, 0, DeltaEModeType.Elastic, diff_consts) return tof
def _convert_TOF_to_d(self, tof, ws_name): diff_consts = self._get_diff_constants(ws_name) return UnitConversion.run("TOF", "dSpacing", tof, 0, DeltaEModeType.Elastic, diff_consts) # L1=0 (ignored)
x_bin_size = 0.02 # A^-1 y = int(math.ceil(chopper_per / bin_size)) #x = int(math.ceil( 1e6/60/bin_size )) #out = np.zeros((y,x)) total_counts = 0 #results = np.zeros((y,x)) src_unit = "TOF" dest_unit = "MomentumTransfer" efixed = 0 emode = DeltaEModeType.Elastic #UnitConversion.run(src_unit, dest_unit, src_value, l1, l2, twoTheta, emode, efixed) x = int((UnitConversion.run( src_unit, dest_unit, 3000, L1, ws.getInstrument().getDetector(0).getDistance( ws.getInstrument().getSample()), math.pi, emode, efixed) + 1) / x_bin_size) results = np.zeros((y, x)) def calc(pixelID): out = np.zeros((y, x)) L2 = ws.getInstrument().getDetector(pixelID).getDistance( ws.getInstrument().getSample()) twoTheta = ws.getDetector(pixelID).getTwoTheta(samplePos, beamDirection) counts = ws.getEventList(pixelID).getNumberEvents() #total_counts+=counts print 'PixelID =', pixelID, 'Count at pixel =', counts, 'Total counts = ', total_counts, '2Theta = ', twoTheta events = ws.getEventList(pixelID) n = events.getNumberEvents()
def plot_tof_vs_d_from_calibration(diag_ws, ws_foc, dspacing, calibration): """ Plot fitted TOF vs expected d-spacing from diagnostic workspaces output from mantid.PDCalibration :param diag_ws: workspace object of group of diagnostic workspaces :param ws_foc: workspace object of focused data (post mantid.ApplyDiffCal with calibrated diff_consts) :param calibration: CalibrationInfo object used to determine subplot axes titles :return: """ # import inside func otherwise causes FindPeaksAutomaticTest to fail # as it checks that pyplot isn't in sys.modules from matplotlib.pyplot import subplots fitparam = ADS.retrieve(diag_ws.name() + "_fitparam").toDict() fiterror = ADS.retrieve(diag_ws.name() + "_fiterror").toDict() d_table = ADS.retrieve(diag_ws.name() + "_dspacing").toDict() dspacing = array(sorted(dspacing)) # PDCal sorts the dspacing list passed x0 = array(fitparam['X0']) x0_er = array(fiterror['X0']) ws_index = array(fitparam['wsindex']) nspec = len(set(ws_index)) si = ws_foc.spectrumInfo() ncols_per_fig = 4 # max number of spectra per figure window figs = [] for ispec in range(nspec): # extract data from tables detid = ws_foc.getSpectrum(ispec).getDetectorIDs()[0] irow = d_table['detid'].index(detid) valid = [ isfinite(d_table[key][irow]) for key in d_table if '@' in key ] # nan if fit unsuccessful ipks = ws_index == ispec # peak centres for this spectrum x, y, e = dspacing[valid], x0[ipks][valid], x0_er[ipks][valid] # get poly fit diff_consts = si.diffractometerConstants( ispec) # output is a UnitParametersMap yfit = array([ UnitConversion.run("dSpacing", "TOF", xpt, 0, DeltaEModeType.Elastic, diff_consts) for xpt in x ]) # plot polynomial fit to TOF vs dSpacing if ispec + 1 > len(figs) * ncols_per_fig: # create new figure ncols = ncols_per_fig if not nspec - ispec < ncols_per_fig else nspec % ncols_per_fig fig, ax = subplots(2, ncols, sharex=True, sharey='row', subplot_kw={'projection': 'mantid'}) ax = reshape( ax, (-1, 1) ) if ax.ndim == 1 else ax # to ensure is 2D matrix even if ncols==1 ax[0, 0].set_ylabel('Fitted TOF (\u03BCs)') ax[1, 0].set_ylabel('Residuals (\u03BCs)') figs.append(fig) icol = 0 # plot TOF vs d ax[0, icol].set_title(calibration.get_subplot_title(ispec)) ax[0, icol].errorbar(x, y, yerr=e, marker='o', markersize=3, capsize=2, ls='', color='b', label='Peak centres') ax[0, icol].plot(x, yfit, '-r', label='quadratic fit') # plot residuals ax[1, icol].errorbar(x, y - yfit, yerr=e, marker='o', markersize=3, capsize=2, ls='', color='b', label='resids') ax[1, icol].axhline(color='r', ls='-') ax[1, icol].set_xlabel('d-spacing (Ang)') icol += 1 # Format figs and show for fig in figs: fig.tight_layout() fig.show()
def inTOF(value, l1, l2): """Return the number (tof) converted to wavelength""" return UnitConversion.run('Wavelength', 'TOF', value, l1, l2, 0., DeltaEModeType.Elastic, 0.)
def PyExec(self): runs = self.getProperty("Filename").value if not runs: ipts = self.getProperty("IPTS").value runs = ['/HFIR/HB2C/IPTS-{}/nexus/HB2C_{}.nxs.h5'.format(ipts, run) for run in self.getProperty("RunNumbers").value] wavelength = self.getProperty("wavelength").value outWS = self.getPropertyValue("OutputWorkspace") group_names = [] grouping = self.getProperty("Grouping").value if grouping == 'None': grouping = 1 else: grouping = 2 if grouping == '2x2' else 4 for i, run in enumerate(runs): data = np.zeros((512*480*8),dtype=np.int64) with h5py.File(run, 'r') as f: monitor_count = f['/entry/monitor1/total_counts'].value[0] run_number = f['/entry/run_number'].value[0] for b in range(8): data += np.bincount(f['/entry/bank'+str(b+1)+'_events/event_id'].value,minlength=512*480*8) data = data.reshape((480*8, 512)) if grouping == 2: data = data[::2,::2] + data[1::2,::2] + data[::2,1::2] + data[1::2,1::2] elif grouping == 4: data = (data[::4,::4] + data[1::4,::4] + data[2::4,::4] + data[3::4,::4] + data[::4,1::4] + data[1::4,1::4] + data[2::4,1::4] + data[3::4,1::4] + data[::4,2::4] + data[1::4,2::4] + data[2::4,2::4] + data[3::4,2::4] + data[::4,3::4] + data[1::4,3::4] + data[2::4,3::4] + data[3::4,3::4]) CreateWorkspace(DataX=[wavelength-0.001, wavelength+0.001], DataY=data, DataE=np.sqrt(data), UnitX='Wavelength', YUnitLabel='Counts', NSpec=1966080//grouping**2, OutputWorkspace='__tmp_load', EnableLogging=False) LoadNexusLogs('__tmp_load', Filename=run, EnableLogging=False) AddSampleLog('__tmp_load', LogName="monitor_count", LogType='Number', NumberType='Double', LogText=str(monitor_count), EnableLogging=False) AddSampleLog('__tmp_load', LogName="gd_prtn_chrg", LogType='Number', NumberType='Double', LogText=str(monitor_count), EnableLogging=False) AddSampleLog('__tmp_load', LogName="Wavelength", LogType='Number', NumberType='Double', LogText=str(wavelength), EnableLogging=False) AddSampleLog('__tmp_load', LogName="Ei", LogType='Number', NumberType='Double', LogText=str(UnitConversion.run('Wavelength', 'Energy', wavelength, 0, 0, 0, Elastic, 0)), EnableLogging=False) AddSampleLog('__tmp_load', LogName="run_number", LogText=run_number, EnableLogging=False) if grouping > 1: # Fix detector IDs per spectrum before loading instrument __tmp_load = mtd['__tmp_load'] for n in range(__tmp_load.getNumberHistograms()): s=__tmp_load.getSpectrum(n) for i in range(grouping): for j in range(grouping): s.addDetectorID(int(n*grouping%512 + n//(512/grouping)*512*grouping + j + i*512)) LoadInstrument('__tmp_load', InstrumentName='WAND', RewriteSpectraMap=False, EnableLogging=False) else: LoadInstrument('__tmp_load', InstrumentName='WAND', RewriteSpectraMap=True, EnableLogging=False) SetGoniometer('__tmp_load', Axis0="HB2C:Mot:s1,0,1,0,1", EnableLogging=False) if self.getProperty("ApplyMask").value: MaskBTP('__tmp_load', Pixel='1,2,511,512', EnableLogging=False) if mtd['__tmp_load'].getRunNumber() > 26600: # They changed pixel mapping and bank name order here MaskBTP('__tmp_load', Bank='1', Tube='479-480', EnableLogging=False) MaskBTP('__tmp_load', Bank='8', Tube='1-2', EnableLogging=False) else: MaskBTP('__tmp_load', Bank='8', Tube='475-480', EnableLogging=False) if len(runs) == 1: RenameWorkspace('__tmp_load', outWS, EnableLogging=False) else: outName = outWS+"_"+str(mtd['__tmp_load'].getRunNumber()) group_names.append(outName) RenameWorkspace('__tmp_load', outName, EnableLogging=False) if len(runs) > 1: GroupWorkspaces(group_names, OutputWorkspace=outWS, EnableLogging=False) self.setProperty('OutputWorkspace', outWS)
def _fillTemplateTOFWorkspace(templateWS, bkgLevel): """Fill a TOF workspace with somewhat sane data.""" nHistograms = templateWS.getNumberHistograms() E_i = 23.0 nBins = 128 binWidth = 2.63 elasticIndex = int(nBins / 3) monitorElasticIndex = int(nBins / 2) xs = numpy.empty(nHistograms*(nBins+1)) ys = numpy.empty(nHistograms*nBins) es = numpy.empty(nHistograms*nBins) spectrumInfo = templateWS.spectrumInfo() instrument = templateWS.getInstrument() l1 = spectrumInfo.l1() l2 = float(instrument.getStringParameter('l2')[0]) tofElastic = UnitConversion.run('Energy', 'TOF', E_i, l1, l2, 0.0, DeltaEModeType.Direct, 0.0) tofBegin = tofElastic - elasticIndex * binWidth monitorSampleDistance = 0.5 tofElasticMonitor = tofBegin + monitorElasticIndex * binWidth tofMonitorDetector = UnitConversion.run('Energy', 'TOF', E_i, monitorSampleDistance, l2, 0.0, DeltaEModeType.Direct, 0.0) elasticPeakSigma = nBins * binWidth * 0.03 elasticPeakHeight = 1723.0 bkgMonitor = 1 def fillBins(histogramIndex, elasticTOF, elasticPeakHeight, bkgLevel): xIndexOffset = histogramIndex*(nBins+1) yIndexOffset = histogramIndex*nBins xs[xIndexOffset] = tofBegin - binWidth / 2 for binIndex in range(nBins): x = tofBegin + binIndex * binWidth xs[xIndexOffset+binIndex+1] = x + binWidth / 2 y = round(_gaussian(x, elasticPeakHeight, elasticTOF, elasticPeakSigma)) + bkgLevel ys[yIndexOffset+binIndex] = y es[yIndexOffset+binIndex] = numpy.sqrt(y) for histogramIndex in range(0, nHistograms - 1): trueL2 = spectrumInfo.l2(histogramIndex) trueTOF = UnitConversion.run('Energy', 'TOF', E_i, l1, trueL2, 0.0, DeltaEModeType.Direct, 0.0) fillBins(histogramIndex, trueTOF, elasticPeakHeight, bkgLevel) fillBins(nHistograms - 1, tofElasticMonitor, 1623 * elasticPeakHeight, bkgMonitor) kwargs = { 'DataX': xs, 'DataY': ys, 'DataE': es, 'NSpec': nHistograms, 'ParentWorkspace': templateWS, 'child': True } alg = run_algorithm('CreateWorkspace', **kwargs) ws = alg.getProperty('OutputWorkspace').value ws.getAxis(0).setUnit('TOF') kwargs = { 'Workspace': ws, 'LogName': 'Ei', 'LogText': str(E_i), 'LogType': 'Number', 'NumberType': 'Double', 'child': True } run_algorithm('AddSampleLog', **kwargs) wavelength = UnitConversion.run('Energy', 'Wavelength', E_i, l1, l2, 0.0, DeltaEModeType.Direct, 0.0) kwargs = { 'Workspace': ws, 'LogName': 'wavelength', 'LogText': str(float(wavelength)), 'LogType': 'Number', 'NumberType': 'Double', 'child': True } run_algorithm('AddSampleLog', **kwargs) pulseInterval = \ tofMonitorDetector + (monitorElasticIndex - elasticIndex) * binWidth kwargs = { 'Workspace': ws, 'LogName': 'pulse_interval', 'LogText': str(float(pulseInterval * 1e-6)), 'LogType': 'Number', 'NumberType': 'Double', 'child': True } run_algorithm('AddSampleLog', **kwargs) kwargs = { 'Workspace': ws, 'LogName': 'Detector.elasticpeak', 'LogText': str(elasticIndex), 'LogType': 'Number', 'NumberType': 'Int', 'child': True } run_algorithm('AddSampleLog', **kwargs) kwargs = { 'Workspace': ws, 'ParameterName': 'default-incident-monitor-spectrum', 'ParameterType': 'Number', 'Value': str(98305), 'child': True } run_algorithm('SetInstrumentParameter', **kwargs) return ws