def get_vanadium(self, detector_mask, m1, colltrans, exp, indir, metadata): """ This function returns either (vanadium_count, vanadium_monitor, None) or (None, None, vcorr) depending what type of file is provided by getProperty("Vanadium") """ if not self.getProperty("Normalise").value: return None, None, np.ones(44)[detector_mask] vanadium_filename = self.getProperty("Vanadium").value if vanadium_filename: if vanadium_filename.split('.')[-1] == 'dat': vanadium = np.genfromtxt(vanadium_filename) vanadium_count = vanadium[:, 5:49].sum(axis=0)[detector_mask] vanadium_monitor = vanadium[:, 3].sum() logger.notice( "Using vanadium data file: {}".format(vanadium_filename)) return vanadium_count, vanadium_monitor, None else: vcorr_filename = vanadium_filename else: # Find adjacent vcorr file # m1 is the monochromator angle # m1 = -4.375 -> Ge 117, 1.12 A # m1 = 0 -> Ge 115, 1.54 A # m1 = 9.45 -> Ge 113, 2.41 A # colltrans is the collimator position, whether in or out of the beam CONVENTION_2021_02 = np.datetime64(datetime.datetime(2021, 2, 23)) CONVENTION_2021_04 = np.datetime64(datetime.datetime(2021, 4, 25)) date_created = self.get_date(metadata) if date_created >= CONVENTION_2021_04: if np.isclose(m1, -4.375, atol=0.1): ge_peak = 117 elif np.isclose(m1, 0, atol=0.1): ge_peak = 115 else: ge_peak = 113 vcorr_filename = 'HB2A_{}__Ge_{}_{}_vcorr.txt'.format( exp, ge_peak, "OUT" if np.isclose(colltrans, 0, atol=0.1) else "IN") elif date_created >= CONVENTION_2021_02: # Convention after `CONVENTION_2021_02`. # colltrans = 0 -> OUT # colltrans = +/-80 -> IN vcorr_filename = 'HB2A_{}__Ge_{}_{}_vcorr.txt'.format( exp, 115 if np.isclose(m1, 0, atol=0.1) else 113, "OUT" if np.isclose(colltrans, 0, atol=0.1) else "IN") else: # Legacy convention. # colltrans = +/-80 -> OUT # colltrans = 0 -> IN vcorr_filename = 'HB2A_{}__Ge_{}_{}_vcorr.txt'.format( exp, 115 if np.isclose(m1, 0, atol=0.1) else 113, "IN" if np.isclose(colltrans, 0, atol=0.1) else "OUT") vcorr_filename = os.path.join(indir, vcorr_filename) logger.notice("Using vcorr file: {}".format(vcorr_filename)) if not os.path.isfile(vcorr_filename): raise RuntimeError( "Vanadium file {} does not exist".format(vcorr_filename)) return None, None, np.genfromtxt(vcorr_filename)[detector_mask]
def _calculate_energy(self, monitor_ws, grouped_ws, red_ws): """ Convert the input run to energy transfer @param monitor_ws :: name of the monitor workspace to divide by @param grouped_ws :: name of workspace with the detectors grouped @param red_ws :: name to call the reduced workspace """ x_range = self._monitor_range(monitor_ws) Scale(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Factor=0.001, Operation='Multiply') CropWorkspace(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Xmin=x_range[0], XMax=x_range[1]) ScaleX(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Factor=-x_range[0], Operation='Add') CropWorkspace(InputWorkspace=grouped_ws, OutputWorkspace=grouped_ws, Xmin=x_range[0], XMax=x_range[1]) ScaleX(InputWorkspace=grouped_ws, OutputWorkspace=grouped_ws, Factor=-x_range[0], Operation='Add') Divide(LHSWorkspace=grouped_ws, RHSWorkspace=monitor_ws, OutputWorkspace=grouped_ws) formula = self._energy_range(grouped_ws) ConvertAxisByFormula(InputWorkspace=grouped_ws, OutputWorkspace=red_ws, Axis='X', Formula=formula, AxisTitle='Energy transfer', AxisUnits='meV') if self._verbose: xnew = mtd[red_ws].readX(0) # energy array logger.notice('Energy range : %f to %f' % (xnew[0], xnew[-1])) DeleteWorkspace(grouped_ws) DeleteWorkspace(monitor_ws)
def IndirectTrans(inst, sfile,cfile,Verbose=False,Plot=False,Save=False): StartTime('Transmission') TransMon(inst,'Sam',sfile,Verbose) TransMon(inst,'Can',cfile,Verbose) samWS = inst + '_Sam' canWS = inst + '_Can' trWS = inst + '_Trans' Divide(LHSWorkspace=samWS, RHSWorkspace=canWS, OutputWorkspace=trWS) trans = np.average(mtd[trWS].readY(0)) transWS = inst + '_Transmission' workdir = config['defaultsave.directory'] group = samWS +','+ canWS +','+ trWS GroupWorkspaces(InputWorkspaces=group,OutputWorkspace=transWS) if Verbose: logger.notice('Transmission : '+str(trans)) path = os.path.join(workdir,transWS+'.nxs') if Save: SaveNexusProcessed(InputWorkspace=transWS, Filename=path) if Verbose: logger.notice('Output file created : '+path) if Plot: TransPlot(transWS) EndTime('Transmission')
def Iblock(a,first): #read Ascii block of Integers line1 = a[first] line2 = a[first+1] val = ExtractInt(line2) numb = val[0] lines=numb/10 last = numb-10*lines if line1.startswith('I'): error = '' else: error = 'NOT an I block starting at line ' +str(first) logger.notice('ERROR *** ' + error) sys.exit(error) ival = [] for m in range(0, lines): mm = first+2+m val = ExtractInt(a[mm]) for n in range(0, 10): ival.append(val[n]) mm += 1 val = ExtractInt(a[mm]) for n in range(0, last): ival.append(val[n]) mm += 1 return mm,ival #values as list
def ReadIbackGroup(a,first): #read Ascii block of spectrum values x = [] y = [] e = [] next = first line1 = a[next] next += 1 val = ExtractInt(a[next]) n1 = val[0] ngrp = val[2] if line1.startswith('S'): error = '' else: error = 'NOT an S block starting at line ' +str(first) logger.notice('ERROR *** ' + error) sys.exit(error) next += 1 next,Ival = Iblock(a,next) for m in range(0, len(Ival)): x.append(float(m)) yy = float(Ival[m]) y.append(yy) ee = math.sqrt(yy) e.append(ee) return next,x,y,e #values of x,y,e as lists
def PyExec(self): from IndirectDataAnalysis import furyfitMult workdir = config['defaultsave.directory'] inType = self.getProperty('InputType').value prefix = self.getProperty('Instrument').value ana = self.getProperty('Analyser').value RunNumb = self.getProperty('RunNumber').value xMax = self.getProperty('TimeMax').value filename = prefix + str(RunNumb) + '_' + ana plotOp = self.getProperty('Plot').value inWS = filename + '_iqt' if inType == 'File': spath = os.path.join(workdir, inWS + '.nxs') # path name for sample nxs file logger.notice('Input from File : ' + spath) LoadNexusProcessed(Filename=spath, OutputWorkspace=inWS) else: logger.notice('Input from Workspace : ' + inWS) CropWorkspace(InputWorkspace=inWS, OutputWorkspace=inWS, XMin=0.0, XMax=xMax) function = 'name=LinearBackground,A0=0.02,A1=0,ties=(A1=0);' function += 'name=UserFunction,Formula=Intensity*exp(-(x/Tau)^Beta),Intensity=0.98,Tau=0.02,Beta=0.8' furyfitMult(inWS, function, 'SSSS', 0.0, 0.2, False, plotOp, True)
def getWSprefix(wsname,runfile=None): '''Returns a string of the form '<ins><run>_<analyser><refl>_' on which all of our other naming conventions are built. The workspace is used to get the instrument parameters. If the runfile string is given it is expected to be a string with instrument prefix and run number. If it is empty then the workspace name is assumed to contain this information ''' if wsname == '': return '' if runfile is None: runfile = wsname ws = mtd[wsname] facility = config['default.facility'] if facility == 'ILL': instr = ws.getInstrument().getName() logger.notice('Facility is '+facility) prefix = instr + '_' + wsname[:-3] else: (instr, run) = getInstrRun(runfile) run_name = instr + run try: analyser = ws.getInstrument().getStringParameter('analyser')[0] reflection = ws.getInstrument().getStringParameter('reflection')[0] except IndexError: analyser = '' reflection = '' prefix = run_name + '_' + analyser + reflection + '_' return prefix
def startup(self, cycle='14_3'): user_data_directory = os.path.normpath(self.use_folder + cycle) self.set_data_directory(user_data_directory) logger.notice("Raw Data in : {}".format(user_data_directory)) user_data_processed = self.out_folder self.set_user_directory(directory=user_data_processed) logger.notice("Processed Data in : {}".format(user_data_processed))
def get_vanadium(self, detector_mask, m1, colltrans, exp, indir): """ This function returns either (vanadium_count, vanadium_monitor, None) or (None, None, vcorr) depending what type of file is provided by getProperty("Vanadium") """ if not self.getProperty("Normalise").value: return None, None, np.ones(44)[detector_mask] vanadium_filename = self.getProperty("Vanadium").value if vanadium_filename: if vanadium_filename.split('.')[-1] == 'dat': vanadium = np.genfromtxt(vanadium_filename) vanadium_count = vanadium[:, 5:49].sum(axis=0)[detector_mask] vanadium_monitor = vanadium[:, 3].sum() logger.notice("Using vanadium data file: {}".format(vanadium_filename)) return vanadium_count, vanadium_monitor, None else: vcorr_filename = vanadium_filename else: # Find adjacent vcorr file # m1 is the monochromator angle # m1 = 0 -> Ge 115, 1.54A # m1 = 9.45 -> Ge 113, 2.41A # colltrans is the collimator position, whether in or out of the beam # colltrans = 0 -> IN # colltrans = +/-80 -> OUT vcorr_filename = 'HB2A_{}__Ge_{}_{}_vcorr.txt'.format(exp, 115 if np.isclose(m1, 0, atol=0.1) else 113, "IN" if np.isclose(colltrans, 0, atol=0.1) else "OUT") vcorr_filename = os.path.join(indir, vcorr_filename) logger.notice("Using vcorr file: {}".format(vcorr_filename)) if not os.path.isfile(vcorr_filename): raise RuntimeError("Vanadium file {} does not exist".format(vcorr_filename)) return None, None, np.genfromtxt(vcorr_filename)[detector_mask]
def PyExec(self): in_ws = mtd[self.getPropertyValue('InputWorkspace')] out_ws_name = self.getPropertyValue('OutputWorkspace') out_ws = ms.CreateEmptyTableWorkspace(OutputWOrkspace=out_ws_name) out_ws.addColumn('str', 'statistic') stats = { 'standard_deviation': dict(), 'maximum': dict(), 'minimum': dict(), 'mean': dict(), 'median': dict(), } for name in in_ws.getColumnNames(): try: col_stats = _stats_to_dict( Stats.getStatistics( np.array([float(v) for v in in_ws.column(name)]))) for statname in stats.keys(): stats[statname][name] = col_stats[statname] out_ws.addColumn('float', name) except ValueError: logger.notice('Column \'%s\' is not numerical, skipping' % name) for name, stat in stats.items(): stat1 = dict(stat) stat1['statistic'] = name out_ws.addRow(stat1) self.setProperty('OutputWorkspace', out_ws_name)
def ReadWidthFile(readWidth,widthFile,numSampleGroups,Verbose): widthY = [] widthE = [] if readWidth: if Verbose: logger.notice('Width file is ' + widthFile) # read ascii based width file try: wfPath = FileFinder.getFullPath(widthFile) handle = open(wfPath, 'r') asc = [] for line in handle: line = line.rstrip() asc.append(line) handle.close() except Exception, e: raise ValueError('Failed to read width file') numLines = len(asc) if numLines == 0: raise ValueError('No groups in width file') if numLines != numSampleGroups: # check that no. groups are the same raise ValueError('Width groups (' +str(numLines) + ') not = Sample (' +str(numSampleGroups) +')')
def PyExec(self): in_ws = mtd[self.getPropertyValue('InputWorkspace')] out_ws_name = self.getPropertyValue('OutputWorkspace') out_ws = ms.CreateEmptyTableWorkspace(OutputWorkspace=out_ws_name) out_ws.addColumn('str', 'statistic') stats = { 'standard_deviation': dict(), 'maximum': dict(), 'minimum': dict(), 'mean': dict(), 'median': dict(), } for name in in_ws.getColumnNames(): try: col_stats = _stats_to_dict(Stats.getStatistics(np.array([float(v) for v in in_ws.column(name)]))) for statname in stats: stats[statname][name] = col_stats[statname] out_ws.addColumn('float', name) except ValueError: logger.notice('Column \'%s\' is not numerical, skipping' % name) for name, stat in iteritems(stats): stat1 = dict(stat) stat1['statistic'] = name out_ws.addRow(stat1) self.setProperty('OutputWorkspace', out_ws)
def read_mantidplot_project(self, file_name): """ :param file_name: String or string castable object; the file_name of the project :return: returns True if able to load the project, otherwise False Will attempt to read the project file in from the file_name that is given as a mantidplot project file. """ #Get the string inside the mantidworkspaces tags, allowing for whitespace at either end workspaces_pattern = r"<mantidworkspaces>\s*(.*?)\s*<\/mantidworkspaces>" try: with open(file_name) as f: full_text = f.read() ws_match = re.search(workspaces_pattern,full_text,re.DOTALL) if ws_match: #split by tab ws_list = ws_match.group(1).split('\t') if len(ws_list) > 1 and ws_list[0] == "WorkspaceNames": #the first entry is just an identification tag self.workspace_names = ws_list[1:] logger.notice("Loading workspaces from Mantidplot project file " + file_name) return True logger.warning("Mantidplot project file unable to be read") return False except Exception: logger.warning("Mantidplot project file unable to be loaded/read") return False
def createQaxis(inputWS): result = [] ws = mtd[inputWS] nHist = ws.getNumberHistograms() if ws.getAxis(1).isSpectra(): inst = ws.getInstrument() samplePos = inst.getSample().getPos() beamPos = samplePos - inst.getSource().getPos() for i in range(0,nHist): efixed = getEfixed(inputWS, i) detector = ws.getDetector(i) theta = getDetectorTwoTheta(detector, samplePos, beamPos) / 2 lamda = math.sqrt(81.787/efixed) q = 4 * math.pi * math.sin(theta) / lamda result.append(q) else: axis = ws.getAxis(1) msg = 'Creating Axis based on Detector Q value: ' if not axis.isNumeric(): msg += 'Input workspace must have either spectra or numeric axis.' logger.notice(msg) sys.exit(msg) if ( axis.getUnit().unitID() != 'MomentumTransfer' ): msg += 'Input must have axis values of Q' logger.notice(msg) sys.exit(msg) for i in range(0, nHist): result.append(float(axis.label(i))) return result
def ReadWidthFile(readWidth, widthFile, numSampleGroups, Verbose): widthY = [] widthE = [] if readWidth: if Verbose: logger.notice('Width file is ' + widthFile) # read ascii based width file try: wfPath = FileFinder.getFullPath(widthFile) handle = open(wfPath, 'r') asc = [] for line in handle: line = line.rstrip() asc.append(line) handle.close() except Exception, e: raise ValueError('Failed to read width file') numLines = len(asc) if numLines == 0: raise ValueError('No groups in width file') if numLines != numSampleGroups: # check that no. groups are the same raise ValueError('Width groups (' + str(numLines) + ') not = Sample (' + str(numSampleGroups) + ')')
def Fblock(a,first): #read Ascii block of Floats line1 = a[first] line2 = a[first+1] val = ExtractInt(line2) numb = val[0] lines=numb/5 last = numb-5*lines if line1.startswith('F'): error= '' else: error = 'NOT an F block starting at line ' +str(first) logger.notice('ERROR *** ' + error) sys.exit(error) fval = [] for m in range(0, lines): mm = first+2+m val = ExtractFloat(a[mm]) for n in range(0, 5): fval.append(val[n]) mm += 1 val = ExtractFloat(a[mm]) for n in range(0, last): fval.append(val[n]) mm += 1 return mm,fval #values as list
def TransMon(inst, type,file,verbose): if verbose: logger.notice('Raw file : '+file) LoadRaw(Filename=file,OutputWorkspace='__m1',SpectrumMin=1,SpectrumMax=1) LoadRaw(Filename=file,OutputWorkspace='__m2',SpectrumMin=2,SpectrumMax=2) LoadRaw(Filename=file,OutputWorkspace='__det',SpectrumMin=3,SpectrumMax=3) # Check for single or multiple time regimes MonTCBstart = mtd['__m1'].readX(0)[0] SpecTCBstart = mtd['__det'].readX(0)[0] DeleteWorkspace('__det') # delete monWS monWS = '__Mon' if (SpecTCBstart == MonTCBstart): monWS = UnwrapMon('__m1') # unwrap the monitor spectrum and convert to wavelength RenameWorkspace(InputWorkspace=monWS, OutputWorkspace='__Mon1') else: ConvertUnits(InputWorkspace='__m1', OutputWorkspace='__Mon1', Target="Wavelength") ConvertUnits(InputWorkspace='__m2', OutputWorkspace='__Mon2', Target="Wavelength") DeleteWorkspace('__m2') # delete monWS Xin = mtd['__Mon1'].readX(0) xmin1 = mtd['__Mon1'].readX(0)[0] xmax1 = mtd['__Mon1'].readX(0)[len(Xin)-1] Xin = mtd['__Mon2'].readX(0) xmin2 = mtd['__Mon2'].readX(0)[0] xmax2 = mtd['__Mon2'].readX(0)[len(Xin)-1] wmin = max(xmin1,xmin2) wmax = min(xmax1,xmax2) CropWorkspace(InputWorkspace='__Mon1', OutputWorkspace='__Mon1', XMin=wmin, XMax=wmax) RebinToWorkspace(WorkspaceToRebin='__Mon2', WorkspaceToMatch='__Mon1', OutputWorkspace='__Mon2') monWS = inst +'_'+ type Divide(LHSWorkspace='__Mon2', RHSWorkspace='__Mon1', OutputWorkspace=monWS) DeleteWorkspace('__Mon1') # delete monWS DeleteWorkspace('__Mon2') # delete monWS
def PyExec(self): run_f2py_compatibility_test() self.log().information('Jump input') inType = self.getPropertyValue('InputType') prefix = self.getPropertyValue('Instrument') ana = self.getPropertyValue('Analyser') prog = self.getPropertyValue('QLprogram') jump = self.getPropertyValue('Fit') fw = self.getPropertyValue('Width') sam = self.getPropertyValue('SamNumber') sname = prefix+sam+'_'+ana+'_'+prog cropOp = self.getProperty('CropQ') if cropOp: qmin = self.getPropertyValue('Qmin') qmax = self.getPropertyValue('Qmax') qrange = [qmin, qmax] else: qrange = [0.0, 5.0] verbOp = self.getProperty('Verbose') plotOp = self.getProperty('Plot') saveOp = self.getProperty('Save') workdir = config['defaultsave.directory'] if inType == 'File': path = os.path.join(workdir, sname+'_Parameters.nxs') # path name for nxs file LoadNexusProcessed(Filename=path, OutputWorkspace=sname+'_Parameters') message = 'Input from File : '+path else: message = 'Input from Workspace : '+sname if verbOp: logger.notice(message) Main.JumpRun(sname,jump,prog,fw,cropOp,qrange,verbOp,plotOp,saveOp)
def unwrap_monitor(workspace_name): """ Unwrap monitor if required based on value of Workflow.UnwrapMonitor parameter @param workspace_name Name of workspace @return True if the monitor was unwrapped """ from mantid.simpleapi import (UnwrapMonitor, RemoveBins, FFTSmooth) monitor_workspace_name = workspace_name + '_mon' instrument = mtd[monitor_workspace_name].getInstrument() # Determine if the monitor should be unwrapped try: unwrap = instrument.getStringParameter('Workflow.UnwrapMonitor')[0] if unwrap == 'Always': should_unwrap = True elif unwrap == 'BaseOnTimeRegime': mon_time = mtd[monitor_workspace_name].readX(0)[0] det_time = mtd[workspace_name].readX(0)[0] logger.notice(str(mon_time) + " " + str(det_time)) should_unwrap = mon_time == det_time else: should_unwrap = False except IndexError: should_unwrap = False logger.debug('Need to unwrap monitor for %s: %s' % (workspace_name, str(should_unwrap))) if should_unwrap: sample = instrument.getSample() sample_to_source = sample.getPos() - instrument.getSource().getPos() radius = mtd[workspace_name].getDetector(0).getDistance(sample) z_dist = sample_to_source.getZ() l_ref = z_dist + radius logger.debug('For workspace %s: radius=%d, z_dist=%d, l_ref=%d' % (workspace_name, radius, z_dist, l_ref)) _, join = UnwrapMonitor(InputWorkspace=monitor_workspace_name, OutputWorkspace=monitor_workspace_name, LRef=l_ref) RemoveBins(InputWorkspace=monitor_workspace_name, OutputWorkspace=monitor_workspace_name, XMin=join - 0.001, XMax=join + 0.001, Interpolation='Linear') try: FFTSmooth(InputWorkspace=monitor_workspace_name, OutputWorkspace=monitor_workspace_name, WorkspaceIndex=0, IgnoreXBins=True) except ValueError: raise ValueError('Uneven bin widths are not supported.') return should_unwrap
def load_multi_run_part(self, extension, run, panel): filename = self.get_file_name(run, extension) logger.notice("reading filename... {}".format(filename)) spectra_min, spectra_max = self.return_panel.get(panel) output1 = "w{0}-{1}".format(run, panel) simple.LoadRaw(Filename=filename, OutputWorkspace=output1, SpectrumMin=str(spectra_min), SpectrumMax=str(spectra_max), LoadLogFiles="0") return output1
def _post_process(self): """ Handles adding logs, saving and plotting. """ use_scale_factor = self._scale_factor == 1.0 AddSampleLog(Workspace=self._out_ws, LogName='scale', LogType='String', LogText=str(use_scale_factor)) if use_scale_factor: AddSampleLog(Workspace=self._out_ws, LogName='scale_factor', LogType='Number', LogText=str(self._scale_factor)) AddSampleLog(Workspace=self._out_ws, LogName='res_smoothing_applied', LogType='String', LogText=str(self._smooth)) AddSampleLog(Workspace=self._out_ws, LogName='back_start', LogType='Number', LogText=str(self._background[0])) AddSampleLog(Workspace=self._out_ws, LogName='back_end', LogType='Number', LogText=str(self._background[1])) rebin_params = self._rebin_string.split(',') if len(rebin_params) == 3: AddSampleLog(Workspace=self._out_ws, LogName='rebin_low', LogType='Number', LogText=rebin_params[0]) AddSampleLog(Workspace=self._out_ws, LogName='rebin_width', LogType='Number', LogText=rebin_params[1]) AddSampleLog(Workspace=self._out_ws, LogName='rebin_high', LogType='Number', LogText=rebin_params[2]) self.setProperty('OutputWorkspace', self._out_ws) if self._save: if self._verbose: logger.notice( "Resolution file saved to default save directory.") SaveNexusProcessed(InputWorkspace=self._out_ws, Filename=self._out_ws + '.nxs') if self._plot: from IndirectImport import import_mantidplot mtd_plot = import_mantidplot() mtd_plot.plotSpectrum(self._out_ws, 0)
def MomentStart(inType,sname,erange,factor,Verbose,Plot,Save): workdir = config['defaultsave.directory'] if inType == 'File': spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file logger.notice('Input from File : '+spath) LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) else: logger.notice('Input from Workspace : '+sname) MomentRun(sname,erange,factor,Verbose,Plot,Save)
def CheckSam(sam): if sam[1] <1e-8: error = 'Sample density is Zero' logger.notice('ERROR *** ' + error) sys.exit(error) if (sam[2]+sam[3]) <1e-8: error = 'Sample total scattering cross-section (scat+abs) is Zero' logger.notice('ERROR *** ' + error) sys.exit(error)
def PyExec(self): from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform if is_supported_f2py_platform(): import IndirectBayes as Main run_f2py_compatibility_test() self.log().information('Quest input') inType = self.getPropertyValue('InputType') prefix = self.getPropertyValue('Instrument') ana = self.getPropertyValue('Analyser') sam = self.getPropertyValue('SamNumber') rinType = self.getPropertyValue('ResInputType') res = self.getPropertyValue('ResNumber') elastic = self.getProperty('ElasticOption').value bgd = self.getPropertyValue('BackgroundOption') emin = self.getPropertyValue('EnergyMin') emax = self.getPropertyValue('EnergyMax') nbin = self.getPropertyValue('SamBinning') nbins = [nbin, 1] nbet = self.getProperty('NumberBeta').value nsig = self.getProperty('NumberSigma').value nbs = [nbet, nsig] sname = prefix+sam+'_'+ana + '_red' rname = prefix+res+'_'+ana + '_res' erange = [float(emin), float(emax)] if elastic: o_el = 1 else: o_el = 0 fitOp = [o_el, bgd, 0, 0] loopOp = self.getProperty('Sequence').value verbOp = self.getProperty('Verbose').value plotOp = self.getPropertyValue('Plot') saveOp = self.getProperty('Save').value workdir = config['defaultsave.directory'] if inType == 'File': spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) Smessage = 'Sample from File : '+spath else: Smessage = 'Sample from Workspace : '+sname if rinType == 'File': rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) Rmessage = 'Resolution from File : '+rpath else: Rmessage = 'Resolution from Workspace : '+rname if verbOp: logger.notice(Smessage) logger.notice(Rmessage) Main.QuestRun(sname,rname,nbs,erange,nbins,fitOp,loopOp,plotOp,saveOp)
def CheckSam(sam): if sam[1] < 1e-8: error = 'Sample density is Zero' logger.notice('ERROR *** ' + error) sys.exit(error) if (sam[2] + sam[3]) < 1e-8: error = 'Sample total scattering cross-section (scat+abs) is Zero' logger.notice('ERROR *** ' + error) sys.exit(error)
def PyExec(self): run_f2py_compatibility_test() self.log().information("Quest input") inType = self.getPropertyValue("InputType") prefix = self.getPropertyValue("Instrument") ana = self.getPropertyValue("Analyser") sam = self.getPropertyValue("SamNumber") rinType = self.getPropertyValue("ResInputType") res = self.getPropertyValue("ResNumber") elastic = self.getProperty("ElasticOption") bgd = self.getPropertyValue("BackgroundOption") emin = self.getPropertyValue("EnergyMin") emax = self.getPropertyValue("EnergyMax") nbin = self.getPropertyValue("SamBinning") nbins = [nbin, 1] nbet = self.getPropertyValue("NumberBeta") nsig = self.getPropertyValue("NumberSigma") nbs = [nbet, nsig] sname = prefix + sam + "_" + ana + "_red" rname = prefix + res + "_" + ana + "_res" erange = [float(emin), float(emax)] if elastic: o_el = 1 else: o_el = 0 if bgd == "Sloping": o_bgd = 2 if bgd == "Flat": o_bgd = 1 if bgd == "Zero": o_bgd = 0 fitOp = [o_el, o_bgd, 0, 0] loopOp = self.getProperty("Sequence") verbOp = self.getProperty("Verbose") plotOp = self.getPropertyValue("Plot") saveOp = self.getProperty("Save") workdir = config["defaultsave.directory"] if inType == "File": spath = os.path.join(workdir, sname + ".nxs") # path name for sample nxs file LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) Smessage = "Sample from File : " + spath else: Smessage = "Sample from Workspace : " + sname if rinType == "File": rpath = os.path.join(workdir, rname + ".nxs") # path name for res nxs file LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) Rmessage = "Resolution from File : " + rpath else: Rmessage = "Resolution from Workspace : " + rname if verbOp: logger.notice(Smessage) logger.notice(Rmessage) Main.QuestRun(sname, rname, nbs, erange, nbins, fitOp, loopOp, verbOp, plotOp, saveOp)
def C2Se(sname): prog = 'QSe' outWS = sname+'_Result' asc = readASCIIFile(sname+'.qse') lasc = len(asc) var = asc[3].split() #split line on spaces nspec = var[0] ndat = var[1] var = ExtractInt(asc[6]) first = 7 Xout = [] Yf = [] Ef = [] Yi = [] Ei = [] Yb = [] Eb = [] ns = int(nspec) dataX = np.array([]) dataY = np.array([]) dataE = np.array([]) for m in range(0,ns): first,Q,int0,fw,it,be = SeBlock(asc,first) Xout.append(Q) Yf.append(fw[0]) Ef.append(fw[1]) Yi.append(it[0]) Ei.append(it[1]) Yb.append(be[0]) Eb.append(be[1]) Vaxis = [] dataX = np.append(dataX,np.array(Xout)) dataY = np.append(dataY,np.array(Yi)) dataE = np.append(dataE,np.array(Ei)) nhist = 1 Vaxis.append('f1.Amplitude') dataX = np.append(dataX, np.array(Xout)) dataY = np.append(dataY, np.array(Yf)) dataE = np.append(dataE, np.array(Ef)) nhist += 1 Vaxis.append('f1.FWHM') dataX = np.append(dataX,np.array(Xout)) dataY = np.append(dataY,np.array(Yb)) dataE = np.append(dataE,np.array(Eb)) nhist += 1 Vaxis.append('f1.Beta') logger.notice('Vaxis=' + str(Vaxis)) CreateWorkspace(OutputWorkspace=outWS, DataX=dataX, DataY=dataY, DataE=dataE, Nspec=nhist, UnitX='MomentumTransfer', VerticalAxisUnit='Text', VerticalAxisValues=Vaxis, YUnitLabel='') return outWS
def CheckDensity(density,ncan): if density[0] < 1e-5: error = 'Sample density is zero' logger.notice('ERROR *** '+error) sys.exit(error) if ncan == 2: if density[1] < 1e-5: error = 'Can density is zero' logger.notice('ERROR *** '+error) sys.exit(error)
def restore_figure_data(self, fig, dic): self.restore_fig_properties(fig, dic["properties"]) axes_list = dic["axes"] for index, ax in enumerate(fig.axes): try: self.restore_fig_axes(ax, axes_list[index]) except IndexError as e: if not self.color_bar_remade: raise IndexError(e) except KeyError: logger.notice("Not adding data to blank axis.")
def sliceReadRawFile(fname, Verbose): if Verbose: logger.notice('Reading file :'+fname) #Load the raw file (dir, filename) = os.path.split(fname) (root, ext) = os.path.splitext(filename) Load(Filename=fname, OutputWorkspace=root, LoadLogFiles=False) return root
def CreateSqw(disp,coeff,grid,Verbose): CheckCoeff(disp,coeff) if Verbose: logger.notice('Dispersion is '+disp) logger.notice('Coefficients : '+str(coeff)) nq,dq,nw,dw = CheckQw(grid) q0,w0,e0 = CalcW0(nq,dq,disp,coeff) CreateWorkspace(OutputWorkspace=disp, DataX=q0, DataY=w0, DataE=e0,\ Nspec=1, UnitX='MomentumTransfer') nw2 = 2*nw+1 nel= nw+1 CalcSqw(q0,nw2,nel,dw,w0)
def _save_output(self): """ Save the output workspace to the user's default working directory """ from IndirectCommon import getDefaultWorkingDirectory workdir = getDefaultWorkingDirectory() file_path = os.path.join(workdir, self._output_workspace + '.nxs') SaveNexusProcessed(InputWorkspace=self._output_workspace, Filename=file_path) if self._verbose: logger.notice('Output file : ' + file_path)
def MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,Verbose,Plot,Save): StartTime('Muscat Function') workdir = config['defaultsave.directory'] sname = sname+'_red' spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file LoadNexusProcessed(FileName=spath, OutputWorkspace=sname) sqw = 'S(Q,w)' CreateSqw(disp,coeff,grid,Verbose) if Verbose: logger.notice('Sample run : '+spath) logger.notice('S(Q,w) from : '+disp) MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save) EndTime('Muscat Function')
def SymmStart(inType,sname,cut,Verbose,Plot,Save): StartTime('Symmetrise') workdir = config['defaultsave.directory'] if inType == 'File': spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file LoadNexusProcessed(FileName=spath, OutputWorkspace=sname) message = 'Input from File : '+spath else: message = 'Input from Workspace : '+sname if Verbose: logger.notice(message) SymmRun(sname,cut,Verbose,Plot,Save) EndTime('Symmetrise')
def CheckHistZero(inWS): nhist = mtd[inWS].getNumberHistograms() # no. of hist/groups in WS if nhist == 0: error = 'Workspace '+inWS+' has NO histograms' logger.notice('ERROR *** ' + error) sys.exit(error) Xin = mtd[inWS].readX(0) ntc = len(Xin)-1 # no. points from length of x array if ntc == 0: error = 'Workspace '+inWS+' has NO points' logger.notice('ERROR *** ' + error) sys.exit(error) return nhist,ntc
def slice(inputfiles, calib, xRange, spec, suffix, Save=False, Verbose=False, Plot=False): StartTime('Slice') CheckXrange(xRange,'Time') workdir = config['defaultsave.directory'] outWSlist = [] useTwoRanges = (len(xRange) != 2) useCalib = (calib != '') calibWsName = '__calibration' #load the calibration file if useCalib: Load(Filename=calib, OutputWorkspace=calibWsName) if Verbose: logger.notice('Using Calibration file: %s' % calib) for index, file in enumerate(inputfiles): rawFile = sliceReadRawFile(file, Verbose) #only need to process the calib file once if(index == 0 and useCalib): sliceProcessCalib(rawFile, calibWsName, spec) sfile = sliceProcessRawFile(rawFile, calibWsName, useCalib, xRange, useTwoRanges, spec, suffix, Verbose) Transpose(InputWorkspace=sfile, OutputWorkspace=sfile) unit = mtd[sfile].getAxis(0).setUnit("Label") unit.setLabel("Spectrum Number", "") outWSlist.append(sfile) DeleteWorkspace(rawFile) if Save: # path name for nxs file o_path = os.path.join(workdir, sfile+'.nxs') SaveNexusProcessed(InputWorkspace=sfile, Filename=o_path) if Verbose: logger.notice('Output file :'+o_path) if useCalib: DeleteWorkspace(Workspace=calibWsName) if Plot: try: graph = mp.plotSpectrum(sfile, 0) except RuntimeError, e: #User clicked cancel on plot so don't do anything pass
def read(self, number, panel, extension): if type(number) is int: filename = self.datafile logger.notice("will be reading filename...{}".format(filename)) spectra_min, spectra_max = self.return_panel_van.get(panel) if self.is_vanadium else \ self.return_panel.get(panel) if panel != 0: output = "w{0}-{1}".format(number, panel) else: output = "w{}".format(number) shared_load_files(extension, filename, output, spectra_max, spectra_min, False) if extension == "nxs_event": simple.LoadEventNexus(Filename=filename, OutputWorkspace=output, LoadMonitors='1') self.read_event_nexus(number, output, panel) if extension[:10] == "nxs_event_": label, tmin, tmax = split_string_event(extension) output = output + "_" + label if tmax == "end": simple.LoadEventNexus(Filename=filename, OutputWorkspace=output, FilterByTimeStart=tmin, LoadMonitors='1', MonitorsAsEvents='1', FilterMonByTimeStart=tmin) else: simple.LoadEventNexus(Filename=filename, OutputWorkspace=output, FilterByTimeStart=tmin, FilterByTimeStop=tmax, LoadMonitors='1', MonitorsAsEvents='1', FilterMonByTimeStart=tmin, FilterMonByTimeStop=tmax) self.read_event_nexus(number, output, panel) else: num_1, num_2 = split_run_string(number) output = "w{0}_{1}-{2}".format(num_1, num_2, panel) output1 = self.load_multi_run_part(extension, num_1, panel) output2 = self.load_multi_run_part(extension, num_2, panel) simple.MergeRuns(output1 + "," + output2, output) simple.DeleteWorkspace(output1) simple.DeleteWorkspace(output2) simple.ConvertUnits(InputWorkspace=output, OutputWorkspace=output, Target="Wavelength", Emode="Elastic") lmin, lmax = Wish.LAMBDA_RANGE simple.CropWorkspace(InputWorkspace=output, OutputWorkspace=output, XMin=lmin, XMax=lmax) monitor_run = "monitor{}".format(number) if monitor_run not in simple.mtd: monitor = self.process_incidentmon(number, extension, spline_terms=70) else: monitor = simple.mtd[monitor_run] simple.NormaliseToMonitor(InputWorkspace=output, OutputWorkspace=output + "norm1", MonitorWorkspace=monitor) simple.NormaliseToMonitor(InputWorkspace=output + "norm1", OutputWorkspace=output + "norm2", MonitorWorkspace=monitor, IntegrationRangeMin=0.7, IntegrationRangeMax=10.35) simple.DeleteWorkspace(output) simple.DeleteWorkspace(output + "norm1") simple.RenameWorkspace(InputWorkspace=output + "norm2", OutputWorkspace=output) simple.ConvertUnits(InputWorkspace=output, OutputWorkspace=output, Target="TOF", EMode="Elastic") simple.ReplaceSpecialValues(InputWorkspace=output, OutputWorkspace=output, NaNValue=0.0, NaNError=0.0, InfinityValue=0.0, InfinityError=0.0) return output
def MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): StartTime('Muscat Data') workdir = config['defaultsave.directory'] sname = sname+'_red' spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file LoadNexusProcessed(FileName=spath, OutputWorkspace=sname) sqw = sqw+'_sqw' qpath = os.path.join(workdir, sqw+'.nxs') # path name for S(Q,w) nxs file LoadNexusProcessed(FileName=qpath, OutputWorkspace=sqw) if Verbose: logger.notice('Sample run : '+spath) logger.notice('S(Q,w) file : '+qpath) MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save) EndTime('Muscat Data')
def CheckSize(size, geom, ncan, Verbose): if geom == 'cyl': if (size[1] - size[0]) < 1e-4: raise ValueError('Sample outer radius not > inner radius') else: if Verbose: message = 'Sam : inner radius = ' + str( size[0]) + ' ; outer radius = ' + str(size[1]) logger.notice(message) if geom == 'flt': if size[0] < 1e-4: raise ValueError('Sample thickness is zero') else: if Verbose: logger.notice('Sam : thickness = ' + str(size[0])) if ncan == 2: if geom == 'cyl': if (size[2] - size[1]) < 1e-4: raise ValueError('Can inner radius not > sample outer radius') else: if Verbose: message = 'Can : inner radius = ' + str( size[1]) + ' ; outer radius = ' + str(size[2]) logger.notice(message) if geom == 'flt': if size[1] < 1e-4: raise ValueError('Can thickness is zero') else: if Verbose: logger.notice('Can : thickness = ' + str(size[1]))
def PyExec(self): from IndirectCommon import StartTime, EndTime self._setup() StartTime('IndirectTransmissionMonitor') ws_basename = str(self._sample_ws_in) self._trans_mon(ws_basename, 'Sam', self._sample_ws_in) self._trans_mon(ws_basename, 'Can', self._can_ws_in) # Generate workspace names sam_ws = ws_basename + '_Sam' can_ws = ws_basename + '_Can' trans_ws = ws_basename + '_Trans' # Divide sample and can workspaces Divide(LHSWorkspace=sam_ws, RHSWorkspace=can_ws, OutputWorkspace=trans_ws) trans = numpy.average(mtd[trans_ws].readY(0)) AddSampleLog(Workspace=trans_ws, LogName='can_workspace', LogType='String', LogText=self._can_ws_in) # Group workspaces group = sam_ws + ',' + can_ws + ',' + trans_ws GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._out_ws) self.setProperty('OutputWorkspace', self._out_ws) if self._verbose: logger.notice('Transmission : ' + str(trans)) # Save the tranmissin workspace group to a nexus file if self._save: workdir = config['defaultsave.directory'] path = os.path.join(workdir, self._out_ws + '.nxs') SaveNexusProcessed(InputWorkspace=self._out_ws, Filename=path) if self._verbose: logger.notice('Output file created : ' + path) # Plot spectra from transmission workspace if self._plot: mtd_plot = import_mantidplot() mtd_plot.plotSpectrum(self._out_ws, 0) EndTime('IndirectTransmissionMonitor')
def CubicFit(inputWS, spec, Verbose=False): '''Uses the Mantid Fit Algorithm to fit a quadratic to the inputWS parameter. Returns a list containing the fitted parameter values.''' function = 'name=Quadratic, A0=1, A1=0, A2=0' fit = Fit(Function=function, InputWorkspace=inputWS, WorkspaceIndex=spec, CreateOutput=True, Output='Fit') table = mtd['Fit_Parameters'] A0 = table.cell(0,1) A1 = table.cell(1,1) A2 = table.cell(2,1) Abs = [A0, A1, A2] if Verbose: logger.notice('Group '+str(spec)+' of '+inputWS+' ; fit coefficients are : '+str(Abs)) return Abs
def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1, Suffix=''): workspaces = [] for file in rawfiles: ( dir, filename ) = os.path.split(file) ( name, ext ) = os.path.splitext(filename) try: if ( SpecMin == -1 ) and ( SpecMax == -1 ): Load(Filename=file, OutputWorkspace=name+Suffix, LoadLogFiles=False) else: Load(Filename=file, OutputWorkspace=name+Suffix, SpectrumMin=SpecMin, SpectrumMax=SpecMax, LoadLogFiles=False) workspaces.append(name+Suffix) except ValueError, message: logger.notice(message) sys.exit(message)
def ChangeAngles(inWS,instr,theta,Verbose): workdir = config['defaultsave.directory'] file = instr+'_angles.txt' path = os.path.join(workdir, file) if Verbose: logger.notice('Creating angles file : ' + path) handle = open(path, 'w') head = 'spectrum,theta' handle.write(head +" \n" ) for n in range(0,len(theta)): handle.write(str(n+1) +' '+ str(theta[n]) +"\n" ) if Verbose: logger.notice('Spectrum ' +str(n+1)+ ' = '+str(theta[n])) handle.close() UpdateInstrumentFromFile(Workspace=inWS, Filename=path, MoveMonitors=False, IgnorePhi=False, AsciiHeader=head)
def RejectZero(inWS,tot,Verbose): nin = mtd[inWS].getNumberHistograms() # no. of hist/groups in sam nout = 0 outWS = inWS[:-3]+'red' for n in range(0, nin): if tot[n] > 0: ExtractSingleSpectrum(InputWorkspace=inWS, OutputWorkspace='__tmp', WorkspaceIndex=n) if nout == 0: RenameWorkspace(InputWorkspace='__tmp', OutputWorkspace=outWS) else: ConjoinWorkspaces(InputWorkspace1=outWS, InputWorkspace2='__tmp',CheckOverlapping=False) nout += 1 else: if Verbose: logger.notice('** spectrum '+str(n+1)+' rejected')
def _plot(self): """ Plots results. """ if self._plot_type == 'spectra': from mantidplot import plotSpectrum num_spectra = mtd[self._plot_ws].getNumberHistograms() try: plotSpectrum(self._plot_ws, range(0, num_spectra)) except RuntimeError: logger.notice('Spectrum plotting canceled by user') if self._plot_type == 'contour': from mantidplot import importMatrixWorkspace plot_workspace = importMatrixWorkspace(self._plot_ws) plot_workspace.plotGraph2D()
def get_detector_mask(self, exp, indir): """Returns an anode mask""" detector_mask = np.ones(44, dtype=bool) if len(self.getProperty("ExcludeDetectors").value) == 0: exclude_filename = os.path.join(indir, 'HB2A_{}__exclude_detectors.txt'.format(exp)) if os.path.isfile(exclude_filename): with warnings.catch_warnings(): warnings.simplefilter("ignore") exclude_detectors = np.loadtxt(exclude_filename, ndmin=1, dtype=int) else: exclude_detectors=np.empty(0, dtype=int) else: exclude_detectors = np.array(self.getProperty("ExcludeDetectors").value) if len(exclude_detectors) > 0: logger.notice("Excluding anodes: {}".format(exclude_detectors)) detector_mask[exclude_detectors-1] = False return detector_mask
def PyExec(self): in_ws = mtd[self.getPropertyValue('InputWorkspace')] indices_list = self.getPropertyValue('ColumnIndices') out_ws_name = self.getPropertyValue('OutputWorkspace') column_names = in_ws.getColumnNames() # If column indices are not provided, then default to _ALL_ columns if len(indices_list) > 0: indices_list = [int(x) for x in indices_list.split(',')] else: indices_list = range(len(column_names)) out_ws = ms.CreateEmptyTableWorkspace(OutputWorkspace=out_ws_name) out_ws.addColumn('str', 'Statistic') stats = collections.OrderedDict([ ('StandardDev', collections.OrderedDict()), ('Minimum', collections.OrderedDict()), ('Median', collections.OrderedDict()), ('Maximum', collections.OrderedDict()), ('Mean', collections.OrderedDict()), ]) for index in indices_list: column_name = column_names[index] try: column_data = np.array([float(v) for v in in_ws.column(index)]) col_stats = _stats_to_dict(Stats.getStatistics(column_data)) for stat_name in stats: stats[stat_name][column_name] = col_stats[stat_name] out_ws.addColumn('float', column_name) except RuntimeError: logger.notice('Column \'%s\' is not numerical, skipping' % column_name) except: logger.notice('Column \'%s\' is not numerical, skipping' % column_name) for index, stat_name in iteritems(stats): stat = collections.OrderedDict(stat_name) stat['Statistic'] = index out_ws.addRow(stat) self.setProperty('OutputWorkspace', out_ws)