diff --git a/Code/Mantid/scripts/Inelastic/IndirectCommon.py b/Code/Mantid/scripts/Inelastic/IndirectCommon.py index 043c2717866c..d6147a76cc78 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectCommon.py +++ b/Code/Mantid/scripts/Inelastic/IndirectCommon.py @@ -4,48 +4,37 @@ from IndirectImport import import_mantidplot -import sys, platform, os.path, math, datetime, re +import os.path +import math +import datetime +import re import numpy as np import itertools + def StartTime(prog): logger.notice('----------') - message = 'Program ' + prog +' started @ ' + str(datetime.datetime.now()) + message = 'Program ' + prog + ' started @ ' + str(datetime.datetime.now()) logger.notice(message) + def EndTime(prog): - message = 'Program ' + prog +' ended @ ' + str(datetime.datetime.now()) + message = 'Program ' + prog + ' ended @ ' + str(datetime.datetime.now()) logger.notice(message) logger.notice('----------') -def loadInst(instrument): - ws = '__empty_' + instrument - if not mtd.doesExist(ws): - idf_dir = config['instrumentDefinition.directory'] - idf = idf_dir + instrument + '_Definition.xml' - LoadEmptyInstrument(Filename=idf, OutputWorkspace=ws) - -def loadNexus(filename): - ''' - Loads a Nexus file into a workspace with the name based on the - filename. Convenience function for not having to play around with paths - in every function. - ''' - name = os.path.splitext( os.path.split(filename)[1] )[0] - LoadNexus(Filename=filename, OutputWorkspace=name) - return name def getInstrRun(ws_name): - ''' + """ Get the instrument name and run number from a workspace. @param ws_name - name of the workspace @return tuple of form (instrument, run number) - ''' + """ ws = mtd[ws_name] run_number = str(ws.getRunNumber()) if run_number == '0': - #attempt to parse run number off of name + # Attempt to parse run number off of name match = re.match(r'([a-zA-Z]+)([0-9]+)', ws_name) if match: run_number = match.group(2) @@ -58,12 +47,13 @@ def getInstrRun(ws_name): instrument = instrument.lower() return instrument, run_number + def getWSprefix(wsname): - ''' + """ Returns a string of the form '__' on which all of our other naming conventions are built. The workspace is used to get the instrument parameters. - ''' + """ if wsname == '': return '' @@ -76,7 +66,7 @@ def getWSprefix(wsname): (instrument, run_number) = getInstrRun(wsname) if facility == 'ILL': - run_name = instrument + '_'+ run_number + run_name = instrument + '_' + run_number else: run_name = instrument + run_number @@ -94,10 +84,12 @@ def getWSprefix(wsname): return prefix + def getEfixed(workspace, detIndex=0): inst = mtd[workspace].getInstrument() return inst.getNumberParameter("efixed-val")[0] + def checkUnitIs(ws, unit_id, axis_index=0): """ Check that the workspace has the correct units by comparing @@ -105,10 +97,13 @@ def checkUnitIs(ws, unit_id, axis_index=0): """ axis = mtd[ws].getAxis(axis_index) unit = axis.getUnit() - return (unit.unitID() == unit_id) + return unit.unitID() == unit_id + -# Get the default save directory and check it's valid def getDefaultWorkingDirectory(): + """ + Get the default save directory and check it's valid. + """ workdir = config['defaultsave.directory'] if not os.path.isdir(workdir): @@ -116,19 +111,20 @@ def getDefaultWorkingDirectory(): return workdir + def createQaxis(inputWS): result = [] ws = mtd[inputWS] - nHist = ws.getNumberHistograms() + num_hist = 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): + sample_pos = inst.getSample().getPos() + beam_pos = sample_pos - inst.getSource().getPos() + for i in range(0, num_hist): efixed = getEfixed(inputWS, i) detector = ws.getDetector(i) - theta = detector.getTwoTheta(samplePos, beamPos) / 2 - lamda = math.sqrt(81.787/efixed) + theta = detector.getTwoTheta(sample_pos, beam_pos) / 2 + lamda = math.sqrt(81.787 / efixed) q = 4 * math.pi * math.sin(theta) / lamda result.append(q) else: @@ -137,25 +133,27 @@ def createQaxis(inputWS): if not axis.isNumeric(): msg += 'Input workspace must have either spectra or numeric axis.' raise ValueError(msg) - if ( axis.getUnit().unitID() != 'MomentumTransfer' ): + if axis.getUnit().unitID() != 'MomentumTransfer': msg += 'Input must have axis values of Q' raise ValueError(msg) - for i in range(0, nHist): + for i in range(0, num_hist): result.append(float(axis.label(i))) return result + def GetWSangles(inWS): - nhist = mtd[inWS].getNumberHistograms() # get no. of histograms/groups - sourcePos = mtd[inWS].getInstrument().getSource().getPos() - samplePos = mtd[inWS].getInstrument().getSample().getPos() - beamPos = samplePos - sourcePos + num_hist = mtd[inWS].getNumberHistograms() # get no. of histograms/groups + source_pos = mtd[inWS].getInstrument().getSource().getPos() + sample_pos = mtd[inWS].getInstrument().getSample().getPos() + beam_pos = sample_pos - source_pos angles = [] # will be list of angles - for index in range(0, nhist): + for index in range(0, num_hist): detector = mtd[inWS].getDetector(index) # get index - twoTheta = detector.getTwoTheta(samplePos, beamPos)*180.0/math.pi # calc angle - angles.append(twoTheta) # add angle + two_theta = detector.getTwoTheta(sample_pos, beam_pos) * 180.0 / math.pi # calc angle + angles.append(two_theta) # add angle return angles + def GetThetaQ(ws): """ Returns the theta and elastic Q for each spectrum in a given workspace. @@ -164,8 +162,8 @@ def GetThetaQ(ws): @returns A tuple containing a list of theta values and a list of Q values """ - eFixed = getEfixed(ws) - wavelas = math.sqrt(81.787 / eFixed) # Elastic wavelength + e_fixed = getEfixed(ws) + wavelas = math.sqrt(81.787 / e_fixed) # Elastic wavelength k0 = 4.0 * math.pi / wavelas axis = mtd[ws].getAxis(1) @@ -191,28 +189,40 @@ def GetThetaQ(ws): return theta, q + def ExtractFloat(data_string): - """ Extract float values from an ASCII string""" + """ + Extract float values from an ASCII string + """ values = data_string.split() values = map(float, values) return values + def ExtractInt(data_string): - """ Extract int values from an ASCII string""" + """ + Extract int values from an ASCII string + """ values = data_string.split() values = map(int, values) return values -def PadArray(inarray,nfixed): #pad a list to specified size - npt=len(inarray) - padding = nfixed-npt - outarray=[] + +def PadArray(inarray, nfixed): + """ + Pad a list to specified size. + """ + npt = len(inarray) + padding = nfixed - npt + outarray = [] outarray.extend(inarray) - outarray +=[0]*padding + outarray += [0] * padding return outarray -def CheckAnalysers(in1WS,in2WS): - '''Check workspaces have identical analysers and reflections + +def CheckAnalysers(in1WS, in2WS): + """ + Check workspaces have identical analysers and reflections Args: @param in1WS - first 2D workspace @@ -224,22 +234,24 @@ def CheckAnalysers(in1WS,in2WS): Raises: @exception Valuerror - workspaces have different analysers @exception Valuerror - workspaces have different reflections - ''' + """ ws1 = mtd[in1WS] - a1 = ws1.getInstrument().getStringParameter('analyser')[0] - r1 = ws1.getInstrument().getStringParameter('reflection')[0] + analyser_1 = ws1.getInstrument().getStringParameter('analyser')[0] + reflection_1 = ws1.getInstrument().getStringParameter('reflection')[0] ws2 = mtd[in2WS] - a2 = ws2.getInstrument().getStringParameter('analyser')[0] - r2 = ws2.getInstrument().getStringParameter('reflection')[0] - if a1 != a2: - raise ValueError('Workspace '+in1WS+' and '+in2WS+' have different analysers') - elif r1 != r2: - raise ValueError('Workspace '+in1WS+' and '+in2WS+' have different reflections') + analyser_2 = ws2.getInstrument().getStringParameter('analyser')[0] + reflection_2 = ws2.getInstrument().getStringParameter('reflection')[0] + if analyser_1 != analyser_2: + raise ValueError('Workspace %s and %s have different analysers' % (ws1, ws2)) + elif reflection_1 != reflection_2: + raise ValueError('Workspace %s and %s have different reflections' % (ws1, ws2)) else: - logger.information('Analyser is '+a1+r1) + logger.information('Analyser is %s, reflection %s' % (analyser_1, reflection_1)) + def CheckHistZero(inWS): - '''Retrieves basic info on a worskspace + """ + Retrieves basic info on a worskspace Checks the workspace is not empty, then returns the number of histogram and the number of X-points, which is the number of bin boundaries minus one @@ -248,25 +260,27 @@ def CheckHistZero(inWS): @param inWS 2D workspace Returns: - @return nhist - number of histograms in the workspace + @return num_hist - number of histograms in the workspace @return ntc - number of X-points in the first histogram, which is the number of bin boundaries minus one. It is assumed all histograms have the same number of X-points. Raises: @exception ValueError - Worskpace has no histograms - ''' - nhist = mtd[inWS].getNumberHistograms() # no. of hist/groups in WS - if nhist == 0: - raise ValueError('Workspace '+inWS+' has NO histograms') - Xin = mtd[inWS].readX(0) - ntc = len(Xin)-1 # no. points from length of x array + """ + num_hist = mtd[inWS].getNumberHistograms() # no. of hist/groups in WS + if num_hist == 0: + raise ValueError('Workspace ' + inWS + ' has NO histograms') + x_in = mtd[inWS].readX(0) + ntc = len(x_in) - 1 # no. points from length of x array if ntc == 0: - raise ValueError('Workspace '+inWS+' has NO points') - return nhist,ntc + raise ValueError('Workspace ' + inWS + ' has NO points') + return num_hist, ntc -def CheckHistSame(in1WS,name1,in2WS,name2): - '''Check workspaces have same number of histograms and bin boundaries + +def CheckHistSame(in1WS, name1, in2WS, name2): + """ + Check workspaces have same number of histograms and bin boundaries Args: @param in1WS - first 2D workspace @@ -280,49 +294,52 @@ def CheckHistSame(in1WS,name1,in2WS,name2): Raises: Valuerror: number of histograms is different Valuerror: number of bin boundaries in the histograms is different - ''' - nhist1 = mtd[in1WS].getNumberHistograms() # no. of hist/groups in WS1 - X1 = mtd[in1WS].readX(0) - xlen1 = len(X1) - nhist2 = mtd[in2WS].getNumberHistograms() # no. of hist/groups in WS2 - X2 = mtd[in2WS].readX(0) - xlen2 = len(X2) - if nhist1 != nhist2: # check that no. groups are the same - e1 = name1+' ('+in1WS+') histograms (' +str(nhist1) + ')' - e2 = name2+' ('+in2WS+') histograms (' +str(nhist2) + ')' - error = e1 + ' not = ' + e2 + """ + num_hist_1 = mtd[in1WS].getNumberHistograms() # no. of hist/groups in WS1 + x_1 = mtd[in1WS].readX(0) + x_len_1 = len(x_1) + num_hist_2 = mtd[in2WS].getNumberHistograms() # no. of hist/groups in WS2 + x_2 = mtd[in2WS].readX(0) + x_len_2 = len(x_2) + if num_hist_1 != num_hist_2: # Check that no. groups are the same + error_1 = '%s (%s) histograms (%d)' % (name1, in1WS, num_hist_1) + error_2 = '%s (%s) histograms (%d)' % (name2, in2WS, num_hist_2) + error = error_1 + ' not = ' + error_2 raise ValueError(error) - elif xlen1 != xlen2: - e1 = name1+' ('+in1WS+') array length (' +str(xlen1) + ')' - e2 = name2+' ('+in2WS+') array length (' +str(xlen2) + ')' - error = e1 + ' not = ' + e2 + elif x_len_1 != x_len_2: + error_1 = '%s (%s) array length (%d)' % (name1, in1WS, x_len_1) + error_2 = '%s (%s) array length (%d)' % (name2, in2WS, x_len_2) + error = error_1 + ' not = ' + error_2 raise ValueError(error) -def CheckXrange(x_range,type): - if not ( ( len(x_range) == 2 ) or ( len(x_range) == 4 ) ): + +def CheckXrange(x_range, type): + if not (len(x_range) == 2) or (len(x_range) == 4): raise ValueError(type + ' - Range must contain either 2 or 4 numbers') for lower, upper in zip(x_range[::2], x_range[1::2]): if math.fabs(lower) < 1e-5: - raise ValueError(type + ' - input minimum ('+str(lower)+') is Zero') + raise ValueError('%s - input minimum (%f) is zero' % (type, lower)) if math.fabs(upper) < 1e-5: - raise ValueError(type + ' - input maximum ('+str(upper)+') is Zero') + raise ValueError('%s - input maximum (%f) is zero' % (type, upper)) if upper < lower: - raise ValueError(type + ' - input max ('+str(upper)+') < min ('+str(lower)+')') + raise ValueError('%s - input maximum (%f) < minimum (%f)' % (type, upper, lower)) + -def CheckElimits(erange,Xin): - nx = len(Xin)-1 +def CheckElimits(erange, Xin): + len_x = len(Xin) - 1 if math.fabs(erange[0]) < 1e-5: - raise ValueError('Elimits - input emin ( '+str(erange[0])+' ) is Zero') + raise ValueError('Elimits - input emin (%f) is Zero' % (erange[0])) if erange[0] < Xin[0]: - raise ValueError('Elimits - input emin ( '+str(erange[0])+' ) < data emin ( '+str(Xin[0])+' )') + raise ValueError('Elimits - input emin (%f) < data emin (%f)' % (erange[0], Xin[0])) if math.fabs(erange[1]) < 1e-5: - raise ValueError('Elimits - input emax ( '+str(erange[1])+' ) is Zero') - if erange[1] > Xin[nx]: - raise ValueError('Elimits - input emax ( '+str(erange[1])+' ) > data emax ( '+str(Xin[nx])+' )') + raise ValueError('Elimits - input emax (%f) is Zero' % (erange[1])) + if erange[1] > Xin[len_x]: + raise ValueError('Elimits - input emax (%f) > data emax (%f)' % (erange[1], Xin[len_x])) if erange[1] < erange[0]: - raise ValueError('Elimits - input emax ( '+str(erange[1])+' ) < emin ( '+str(erange[0])+' )') + raise ValueError('Elimits - input emax (%f) < emin (%f)' % (erange[1], erange[0])) + def getInstrumentParameter(ws, param_name): """Get an named instrument parameter from a workspace. @@ -333,8 +350,8 @@ def getInstrumentParameter(ws, param_name): """ inst = mtd[ws].getInstrument() - #create a map of type parameters to functions. This is so we avoid writing lots of - #if statements becuase there's no way to dynamically get the type. + # Create a map of type parameters to functions. This is so we avoid writing lots of + # if statements becuase there's no way to dynamically get the type. func_map = {'double': inst.getNumberParameter, 'string': inst.getStringParameter, 'int': inst.getIntParameter, 'bool': inst.getBoolParameter} @@ -349,6 +366,7 @@ def getInstrumentParameter(ws, param_name): return param + def plotSpectra(ws, y_axis_title, indicies=[]): """ Plot a selection of spectra given a list of indicies @@ -362,14 +380,15 @@ def plotSpectra(ws, y_axis_title, indicies=[]): indicies = range(num_spectra) try: - mp = import_mantidplot() - plot = mp.plotSpectrum(ws, indicies, True) + mtd_plot = import_mantidplot() + plot = mtd_plot.plotSpectrum(ws, indicies, True) layer = plot.activeLayer() - layer.setAxisTitle(mp.Layer.Left, y_axis_title) + layer.setAxisTitle(mtd_plot.Layer.Left, y_axis_title) except RuntimeError: - #User clicked cancel on plot so don't do anything + # User clicked cancel on plot so don't do anything return + def plotParameters(ws, *param_names): """ Plot a number of spectra given a list of parameter names @@ -387,78 +406,80 @@ def plotParameters(ws, *param_names): if len(indicies) > 0: plotSpectra(ws, name, indicies) + def convertToElasticQ(input_ws, output_ws=None): - """ + """ Helper function to convert the spectrum axis of a sample to ElasticQ. @param input_ws - the name of the workspace to convert from @param output_ws - the name to call the converted workspace - """ + """ - if output_ws is None: - output_ws = input_ws + if output_ws is None: + output_ws = input_ws - axis = mtd[input_ws].getAxis(1) - if axis.isSpectra(): - e_fixed = getEfixed(input_ws) - ConvertSpectrumAxis(input_ws,Target='ElasticQ',EMode='Indirect',EFixed=e_fixed,OutputWorkspace=output_ws) + axis = mtd[input_ws].getAxis(1) + if axis.isSpectra(): + e_fixed = getEfixed(input_ws) + ConvertSpectrumAxis(input_ws, Target='ElasticQ', EMode='Indirect', EFixed=e_fixed, OutputWorkspace=output_ws) - elif axis.isNumeric(): - #check that units are Momentum Transfer - if axis.getUnit().unitID() != 'MomentumTransfer': - raise RuntimeError('Input must have axis values of Q') + elif axis.isNumeric(): + # Check that units are Momentum Transfer + if axis.getUnit().unitID() != 'MomentumTransfer': + raise RuntimeError('Input must have axis values of Q') + + CloneWorkspace(input_ws, OutputWorkspace=output_ws) + else: + raise RuntimeError('Input workspace must have either spectra or numeric axis.') - CloneWorkspace(input_ws, OutputWorkspace=output_ws) - else: - raise RuntimeError('Input workspace must have either spectra or numeric axis.') def transposeFitParametersTable(params_table, output_table=None): - """ + """ Transpose the parameter table created from a multi domain Fit. This function will make the output consistent with PlotPeakByLogValue. @param params_table - the parameter table output from Fit. @param output_table - name to call the transposed table. If omitted, the output_table will be the same as the params_table - """ - params_table = mtd[params_table] - - table_ws = '__tmp_table_ws' - table_ws = CreateEmptyTableWorkspace(OutputWorkspace=table_ws) - - param_names = params_table.column(0)[:-1] #-1 to remove cost function - param_values = params_table.column(1)[:-1] - param_errors = params_table.column(2)[:-1] - - #find the number of parameters per function - func_index = param_names[0].split('.')[0] - num_params = 0 - for i, name in enumerate(param_names): - if name.split('.')[0] != func_index: - num_params = i - break - - #create columns with parameter names for headers - column_names = ['.'.join(name.split('.')[1:]) for name in param_names[:num_params]] - column_error_names = [name + '_Err' for name in column_names] - column_names = zip(column_names, column_error_names) - table_ws.addColumn('double', 'axis-1') - for name, error_name in column_names: - table_ws.addColumn('double', name) - table_ws.addColumn('double', error_name) - - #output parameter values to table row - for i in xrange(0, params_table.rowCount()-1, num_params): - row_values = param_values[i:i+num_params] - row_errors = param_errors[i:i+num_params] - row = [value for pair in zip(row_values, row_errors) for value in pair] - row = [i/num_params] + row - table_ws.addRow(row) - - if output_table is None: - output_table = params_table.name() - - RenameWorkspace(table_ws.name(), OutputWorkspace=output_table) + """ + params_table = mtd[params_table] + + table_ws = '__tmp_table_ws' + table_ws = CreateEmptyTableWorkspace(OutputWorkspace=table_ws) + + param_names = params_table.column(0)[:-1] # -1 to remove cost function + param_values = params_table.column(1)[:-1] + param_errors = params_table.column(2)[:-1] + + # Find the number of parameters per function + func_index = param_names[0].split('.')[0] + num_params = 0 + for i, name in enumerate(param_names): + if name.split('.')[0] != func_index: + num_params = i + break + + # Create columns with parameter names for headers + column_names = ['.'.join(name.split('.')[1:]) for name in param_names[:num_params]] + column_error_names = [name + '_Err' for name in column_names] + column_names = zip(column_names, column_error_names) + table_ws.addColumn('double', 'axis-1') + for name, error_name in column_names: + table_ws.addColumn('double', name) + table_ws.addColumn('double', error_name) + + # Output parameter values to table row + for i in xrange(0, params_table.rowCount() - 1, num_params): + row_values = param_values[i:i + num_params] + row_errors = param_errors[i:i + num_params] + row = [value for pair in zip(row_values, row_errors) for value in pair] + row = [i / num_params] + row + table_ws.addRow(row) + + if output_table is None: + output_table = params_table.name() + + RenameWorkspace(table_ws.name(), OutputWorkspace=output_table) def search_for_fit_params(suffix, table_ws): @@ -472,7 +493,7 @@ def search_for_fit_params(suffix, table_ws): def convertParametersToWorkspace(params_table, x_column, param_names, output_name): - """ + """ Convert a parameter table output by PlotPeakByLogValue to a MatrixWorkspace. This will make a spectrum for each parameter name using the x_column vairable as the @@ -482,60 +503,61 @@ def convertParametersToWorkspace(params_table, x_column, param_names, output_nam @param x_column - the column in the table to use for the x values. @param parameter_names - list of parameter names to add to the workspace @param output_name - name to call the output workspace. - """ - #search for any parameters in the table with the given parameter names, - #ignoring their function index and output them to a workspace - workspace_names = [] - for param_name in param_names: - column_names = search_for_fit_params(param_name, params_table) - column_error_names = search_for_fit_params(param_name+'_Err', params_table) - param_workspaces = [] - for name, error_name in zip(column_names, column_error_names): - ConvertTableToMatrixWorkspace(params_table, x_column, name, error_name, OutputWorkspace=name) - param_workspaces.append(name) - workspace_names.append(param_workspaces) - - #transpose list of workspaces, ignoring unequal length of lists - #this handles the case where a parameter occurs only once in the whole workspace - workspace_names = map(list, itertools.izip_longest(*workspace_names)) - workspace_names = [filter(None, sublist) for sublist in workspace_names] - - #join all the parameters for each peak into a single workspace per peak - temp_workspaces = [] - for peak_params in workspace_names: - temp_peak_ws = peak_params[0] - for param_ws in peak_params[1:]: - ConjoinWorkspaces(temp_peak_ws, param_ws, False) - temp_workspaces.append(temp_peak_ws) - - #join all peaks into a single workspace - temp_workspace = temp_workspaces[0] - for temp_ws in temp_workspaces[1:]: - ConjoinWorkspaces(temp_workspace, temp_peak_ws, False) - - RenameWorkspace(temp_workspace, OutputWorkspace=output_name) - - #replace axis on workspaces with text axis - axis = TextAxis.create(mtd[output_name].getNumberHistograms()) - workspace_names = [name for sublist in workspace_names for name in sublist] - for i, name in enumerate(workspace_names): - axis.setLabel(i, name) - mtd[output_name].replaceAxis(1, axis) + """ + # Search for any parameters in the table with the given parameter names, + # ignoring their function index and output them to a workspace + workspace_names = [] + for param_name in param_names: + column_names = search_for_fit_params(param_name, params_table) + column_error_names = search_for_fit_params(param_name + '_Err', params_table) + param_workspaces = [] + for name, error_name in zip(column_names, column_error_names): + ConvertTableToMatrixWorkspace(params_table, x_column, name, error_name, OutputWorkspace=name) + param_workspaces.append(name) + workspace_names.append(param_workspaces) + + # Transpose list of workspaces, ignoring unequal length of lists + # this handles the case where a parameter occurs only once in the whole workspace + workspace_names = map(list, itertools.izip_longest(*workspace_names)) + workspace_names = [filter(None, sublist) for sublist in workspace_names] + + # Join all the parameters for each peak into a single workspace per peak + temp_workspaces = [] + for peak_params in workspace_names: + temp_peak_ws = peak_params[0] + for param_ws in peak_params[1:]: + ConjoinWorkspaces(temp_peak_ws, param_ws, False) + temp_workspaces.append(temp_peak_ws) + + # Join all peaks into a single workspace + temp_workspace = temp_workspaces[0] + for temp_ws in temp_workspaces[1:]: # TODO: fairly certain something is wrong here + ConjoinWorkspaces(temp_workspace, temp_peak_ws, False) + + RenameWorkspace(temp_workspace, OutputWorkspace=output_name) + + # Replace axis on workspaces with text axis + axis = TextAxis.create(mtd[output_name].getNumberHistograms()) + workspace_names = [name for sublist in workspace_names for name in sublist] + for i, name in enumerate(workspace_names): + axis.setLabel(i, name) + mtd[output_name].replaceAxis(1, axis) + def addSampleLogs(ws, sample_logs): - """ + """ Add a dictionary of logs to a workspace. The type of the log is inferred by the type of the value passed to the log. + @param ws - workspace to add logs too. @param sample_logs - dictionary of logs to append to the workspace. - """ - for key, value in sample_logs.iteritems(): - if isinstance(value, bool): - log_type = 'String' - elif isinstance(value, (int, long, float)): - log_type = 'Number' - else: - log_type = 'String' + """ + + for key, value in sample_logs.iteritems(): + if isinstance(value, (int, long, float)): + log_type = 'Number' + else: + log_type = 'String' - AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value)) + AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value)) diff --git a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py index ca7a18289489..6edb1ac5074b 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py @@ -1,5 +1,5 @@ from IndirectImport import import_mantidplot -mp = import_mantidplot() +MTD_PLOT = import_mantidplot() from IndirectCommon import * import math, re, os.path, numpy as np @@ -13,7 +13,9 @@ ############################################################################## def split(l, n): - #Yield successive n-sized chunks from l. + """ + Yield successive n-sized chunks from l. + """ for i in xrange(0, len(l), n): yield l[i:i+n] @@ -23,13 +25,13 @@ def segment(l, fromIndex, toIndex): def trimData(nSpec, vals, min, max): result = [] - chunkSize = len(vals) / nSpec + chunk_size = len(vals / nSpec) assert min >= 0, 'trimData: min is less then zero' - assert max <= chunkSize - 1, 'trimData: max is greater than the number of spectra' + assert max <= chunk_size - 1, 'trimData: max is greater than the number of spectra' assert min <= max, 'trimData: min is greater than max' - chunks = split(vals,chunkSize) + chunks = split(vals, chunk_size) for chunk in chunks: - seg = segment(chunk,min,max) + seg = segment(chunk, min, max) for val in seg: result.append(val) return result @@ -91,7 +93,7 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin logger.information('Fit type : Delta = ' + str(using_delta_func) + ' ; Lorentzians = ' + str(lorentzians)) logger.information('Background type : ' + bgd) - output_workspace = getWSprefix(inputWS) + 'conv_' + ftype + bgd + '_s' + str(specMin) + "_to_" + str(specMax) + output_workspace = '%sconv_%s%s_s%d_to_%d' % (getWSprefix(inputWS), ftype, bgd, specMin, specMax) #convert input workspace to get Q axis temp_fit_workspace = "__convfit_fit_ws" @@ -122,20 +124,28 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin axis.setUnit("MomentumTransfer") CopyLogs(InputWorkspace=inputWS, OutputWorkspace=wsname) - AddSampleLog(Workspace=wsname, LogName='convolve_members', LogType='String', LogText=str(convolve)) - AddSampleLog(Workspace=wsname, LogName="fit_program", LogType="String", LogText='ConvFit') - AddSampleLog(Workspace=wsname, LogName='background', LogType='String', LogText=str(bgd)) - AddSampleLog(Workspace=wsname, LogName='delta_function', LogType='String', LogText=str(using_delta_func)) - AddSampleLog(Workspace=wsname, LogName='lorentzians', LogType='String', LogText=str(lorentzians)) + AddSampleLog(Workspace=wsname, LogName='convolve_members', + LogType='String', LogText=str(convolve)) + AddSampleLog(Workspace=wsname, LogName="fit_program", + LogType="String", LogText='ConvFit') + AddSampleLog(Workspace=wsname, LogName='background', + LogType='String', LogText=str(bgd)) + AddSampleLog(Workspace=wsname, LogName='delta_function', + LogType='String', LogText=str(using_delta_func)) + AddSampleLog(Workspace=wsname, LogName='lorentzians', + LogType='String', LogText=str(lorentzians)) CopyLogs(InputWorkspace=wsname, OutputWorkspace=output_workspace + "_Workspaces") temp_correction = temperature is not None - AddSampleLog(Workspace=wsname, LogName='temperature_correction', LogType='String', LogText=str(temp_correction)) + AddSampleLog(Workspace=wsname, LogName='temperature_correction', + LogType='String', LogText=str(temp_correction)) if temp_correction: - AddSampleLog(Workspace=wsname, LogName='temperature_value', LogType='String', LogText=str(temperature)) + AddSampleLog(Workspace=wsname, LogName='temperature_value', + LogType='String', LogText=str(temperature)) - RenameWorkspace(InputWorkspace=output_workspace, OutputWorkspace=output_workspace + "_Parameters") + RenameWorkspace(InputWorkspace=output_workspace, + OutputWorkspace=output_workspace + "_Parameters") fit_workspaces = mtd[output_workspace + '_Workspaces'].getNames() for i, ws in enumerate(fit_workspaces): RenameWorkspace(ws, OutputWorkspace=output_workspace + '_' + str(i+specMin) + '_Workspace') @@ -159,178 +169,178 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin ############################################################################## def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None'): + StartTime('FuryFit') - StartTime('FuryFit') + fit_type = ftype[:-2] + logger.information('Option: ' + fit_type) + logger.information(func) - fit_type = ftype[:-2] - logger.information('Option: ' + fit_type) - logger.information(func) + tmp_fit_workspace = "__furyfit_fit_ws" + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx) - tmp_fit_workspace = "__furyfit_fit_ws" - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx) - - num_hist = mtd[inputWS].getNumberHistograms() - if spec_max is None: - spec_max = num_hist - 1 + num_hist = mtd[inputWS].getNumberHistograms() + if spec_max is None: + spec_max = num_hist - 1 - # name stem for generated workspace - output_workspace = getWSprefix(inputWS) + 'fury_' + ftype + str(spec_min) + "_to_" + str(spec_max) + # Name stem for generated workspace + output_workspace = '%sfury_%s%d_to_%d' % (getWSprefix(inputWS), ftype, spec_min, spec_max) - ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) - convertToElasticQ(tmp_fit_workspace) + ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) + convertToElasticQ(tmp_fit_workspace) - #build input string for PlotPeakByLogValue - input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)] - input_str = ';'.join(input_str) + # Build input string for PlotPeakByLogValue + input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)] + input_str = ';'.join(input_str) - PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func, - StartX=startx, EndX=endx, FitType='Sequential', CreateOutput=True) + PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func, + StartX=startx, EndX=endx, FitType='Sequential', CreateOutput=True) - #remove unsused workspaces - DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices') - DeleteWorkspace(output_workspace + '_Parameters') + # Remove unsused workspaces + DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices') + DeleteWorkspace(output_workspace + '_Parameters') - fit_group = output_workspace + '_Workspaces' - params_table = output_workspace + '_Parameters' - RenameWorkspace(output_workspace, OutputWorkspace=params_table) + fit_group = output_workspace + '_Workspaces' + params_table = output_workspace + '_Parameters' + RenameWorkspace(output_workspace, OutputWorkspace=params_table) - #create *_Result workspace - result_workspace = output_workspace + "_Result" - parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] - convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) + # Create *_Result workspace + result_workspace = output_workspace + "_Result" + parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] + convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) - #set x units to be momentum transfer - axis = mtd[result_workspace].getAxis(0) - axis.setUnit("MomentumTransfer") + # Set x units to be momentum transfer + axis = mtd[result_workspace].getAxis(0) + axis.setUnit("MomentumTransfer") - #process generated workspaces - wsnames = mtd[fit_group].getNames() - params = [startx, endx, fit_type] - for i, ws in enumerate(wsnames): - output_ws = output_workspace + '_%d_Workspace' % i - RenameWorkspace(ws, OutputWorkspace=output_ws) + # Process generated workspaces + wsnames = mtd[fit_group].getNames() + for i, ws in enumerate(wsnames): + output_ws = output_workspace + '_%d_Workspace' % i + RenameWorkspace(ws, OutputWorkspace=output_ws) - sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type, - 'intensities_constrained': intensities_constrained, 'beta_constrained': False} + sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type, + 'intensities_constrained': intensities_constrained, 'beta_constrained': False} - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) - addSampleLogs(fit_group, sample_logs) - addSampleLogs(result_workspace, sample_logs) + addSampleLogs(fit_group, sample_logs) + addSampleLogs(result_workspace, sample_logs) - if Save: - save_workspaces = [result_workspace, fit_group] - furyFitSaveWorkspaces(save_workspaces) + if Save: + save_workspaces = [result_workspace, fit_group] + furyFitSaveWorkspaces(save_workspaces) - if Plot != 'None' : - furyfitPlotSeq(result_workspace, Plot) + if Plot != 'None' : + furyfitPlotSeq(result_workspace, Plot) - EndTime('FuryFit') - return result_workspace + EndTime('FuryFit') + return result_workspace def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None'): - StartTime('FuryFit Multi') + StartTime('FuryFit Multi') - nHist = mtd[inputWS].getNumberHistograms() - output_workspace = getWSprefix(inputWS) + 'fury_1Smult_s0_to_' + str(nHist-1) + nHist = mtd[inputWS].getNumberHistograms() + output_workspace = getWSprefix(inputWS) + 'fury_1Smult_s0_to_' + str(nHist-1) - option = ftype[:-2] - logger.information('Option: '+option) - logger.information('Function: '+function) + option = ftype[:-2] + logger.information('Option: '+option) + logger.information('Function: '+function) - #prepare input workspace for fitting - tmp_fit_workspace = "__furyfit_fit_ws" - if spec_max is None: - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, - StartWorkspaceIndex=spec_min) - else: - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, - StartWorkspaceIndex=spec_min, EndWorkspaceIndex=spec_max) + #prepare input workspace for fitting + tmp_fit_workspace = "__furyfit_fit_ws" + if spec_max is None: + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, + XMin=startx, XMax=endx, + StartWorkspaceIndex=spec_min) + else: + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, + XMin=startx, XMax=endx, + StartWorkspaceIndex=spec_min, EndWorkspaceIndex=spec_max) - ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) - convertToElasticQ(tmp_fit_workspace) + ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) + convertToElasticQ(tmp_fit_workspace) - #fit multi-domian functino to workspace - multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace) - Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0, - Output=output_workspace, CreateOutput=True, **kwargs) + #fit multi-domian functino to workspace + multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace) + Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0, + Output=output_workspace, CreateOutput=True, **kwargs) - params_table = output_workspace + '_Parameters' - transposeFitParametersTable(params_table) + params_table = output_workspace + '_Parameters' + transposeFitParametersTable(params_table) - #set first column of parameter table to be axis values - ax = mtd[tmp_fit_workspace].getAxis(1) - axis_values = ax.extractValues() - for i, value in enumerate(axis_values): - mtd[params_table].setCell('axis-1', i, value) + #set first column of parameter table to be axis values + ax = mtd[tmp_fit_workspace].getAxis(1) + axis_values = ax.extractValues() + for i, value in enumerate(axis_values): + mtd[params_table].setCell('axis-1', i, value) - #convert parameters to matrix workspace - result_workspace = output_workspace + "_Result" - parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] - convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) + #convert parameters to matrix workspace + result_workspace = output_workspace + "_Result" + parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] + convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) - #set x units to be momentum transfer - axis = mtd[result_workspace].getAxis(0) - axis.setUnit("MomentumTransfer") + #set x units to be momentum transfer + axis = mtd[result_workspace].getAxis(0) + axis.setUnit("MomentumTransfer") - result_workspace = output_workspace + '_Result' - fit_group = output_workspace + '_Workspaces' + result_workspace = output_workspace + '_Result' + fit_group = output_workspace + '_Workspaces' - sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype, - 'intensities_constrained': intensities_constrained, 'beta_constrained': True} + sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype, + 'intensities_constrained': intensities_constrained, 'beta_constrained': True} - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) - addSampleLogs(result_workspace, sample_logs) - addSampleLogs(fit_group, sample_logs) + addSampleLogs(result_workspace, sample_logs) + addSampleLogs(fit_group, sample_logs) - DeleteWorkspace(tmp_fit_workspace) + DeleteWorkspace(tmp_fit_workspace) - if Save: - save_workspaces = [result_workspace] - furyFitSaveWorkspaces(save_workspaces) + if Save: + save_workspaces = [result_workspace] + furyFitSaveWorkspaces(save_workspaces) - if Plot != 'None': - furyfitPlotSeq(result_workspace, Plot) + if Plot != 'None': + furyfitPlotSeq(result_workspace, Plot) - EndTime('FuryFit Multi') - return result_workspace + EndTime('FuryFit Multi') + return result_workspace def createFuryMultiDomainFunction(function, input_ws): - multi= 'composite=MultiDomainFunction,NumDeriv=1;' - comp = '(composite=CompositeFunction,$domains=i;' + function + ');' + multi= 'composite=MultiDomainFunction,NumDeriv=1;' + comp = '(composite=CompositeFunction,$domains=i;' + function + ');' - ties = [] - kwargs = {} - num_spectra = mtd[input_ws].getNumberHistograms() - for i in range(0, num_spectra): - multi += comp - kwargs['WorkspaceIndex_' + str(i)] = i + ties = [] + kwargs = {} + num_spectra = mtd[input_ws].getNumberHistograms() + for i in range(0, num_spectra): + multi += comp + kwargs['WorkspaceIndex_' + str(i)] = i - if i > 0: - kwargs['InputWorkspace_' + str(i)] = input_ws + if i > 0: + kwargs['InputWorkspace_' + str(i)] = input_ws - #tie beta for every spectrum - tie = 'f%d.f1.Beta=f0.f1.Beta' % i - ties.append(tie) + #tie beta for every spectrum + tie = 'f%d.f1.Beta=f0.f1.Beta' % i + ties.append(tie) - ties = ','.join(ties) - multi += 'ties=(' + ties + ')' + ties = ','.join(ties) + multi += 'ties=(' + ties + ')' - return multi, kwargs + return multi, kwargs def furyFitSaveWorkspaces(save_workspaces): - workdir = getDefaultWorkingDirectory() - for ws in save_workspaces: - #save workspace to default directory - fpath = os.path.join(workdir, ws+'.nxs') - SaveNexusProcessed(InputWorkspace=ws, Filename=fpath) - logger.information(ws + ' output to file : '+fpath) + workdir = getDefaultWorkingDirectory() + for ws in save_workspaces: + #save workspace to default directory + fpath = os.path.join(workdir, ws+'.nxs') + SaveNexusProcessed(InputWorkspace=ws, Filename=fpath) + logger.information(ws + ' output to file : '+fpath) def furyfitPlotSeq(ws, plot): @@ -349,10 +359,10 @@ def furyfitPlotSeq(ws, plot): def msdfitPlotSeq(inputWS, xlabel): ws = mtd[inputWS+'_A1'] if len(ws.readX(0)) > 1: - msd_plot = mp.plotSpectrum(inputWS+'_A1',0,True) + msd_plot = MTD_PLOT.plotSpectrum(inputWS+'_A1',0,True) msd_layer = msd_plot.activeLayer() - msd_layer.setAxisTitle(mp.Layer.Bottom,xlabel) - msd_layer.setAxisTitle(mp.Layer.Left,'') + msd_layer.setAxisTitle(MTD_PLOT.Layer.Bottom,xlabel) + msd_layer.setAxisTitle(MTD_PLOT.Layer.Left,'') def msdfit(ws, startX, endX, spec_min=0, spec_max=None, Save=False, Plot=True): StartTime('msdFit') @@ -444,7 +454,7 @@ def plotInput(inputfiles,spectra=[]): GroupDetectors(root, root, DetectorList=range(spectra[0],spectra[1]+1) ) workspaces.append(root) if len(workspaces) > 0: - graph = mp.plotSpectrum(workspaces,0) + graph = MTD_PLOT.plotSpectrum(workspaces,0) graph.activeLayer().setTitle(", ".join(workspaces)) ############################################################################## @@ -504,15 +514,14 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): ConvertUnits(InputWorkspace=inputWS, OutputWorkspace=inputWS, Target='Wavelength') else: efixed = getEfixed(inputWS) # Get efixed - theta, Q = GetThetaQ(inputWS) + Q = GetThetaQ(inputWS)[1] ConvertUnits(InputWorkspace=inputWS, OutputWorkspace=inputWS, Target='Wavelength', EMode='Indirect', EFixed=efixed) sam_name = getWSprefix(inputWS) - nameStem = corr[:-4] corrections = mtd[corr].getNames() if mtd.doesExist(canWS): - (instr, can_run) = getInstrRun(canWS) + can_run = getInstrRun(canWS)[1] CorrectedWS = sam_name +'Correct_'+ can_run if diffraction_run: @@ -526,7 +535,7 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): # Check that number of histograms in each corrections workspace matches # that of the input (sample) workspace for ws in corrections: - if ( mtd[ws].getNumberHistograms() != nHist ): + if mtd[ws].getNumberHistograms() != nHist: raise ValueError('Mismatch: num of spectra in '+ws+' and inputWS') # Workspaces that hold intermediate results CorrectedSampleWS = '__csam' @@ -537,7 +546,8 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): logger.information(str(i) + str(mtd[CorrectedSampleWS].readX(0))) if len(corrections) == 1: Ass = CubicFit(corrections[0], i) - PolynomialCorrection(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedSampleWS, + PolynomialCorrection(InputWorkspace=CorrectedSampleWS, + OutputWorkspace=CorrectedSampleWS, Coefficients=Ass, Operation='Divide') if i == 0: CloneWorkspace(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedWS) @@ -554,11 +564,13 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): PolynomialCorrection(InputWorkspace=CorrectedCanWS, OutputWorkspace=CorrectedCanWS, Coefficients=Acsc, Operation='Multiply') - subractCanWorkspace(CorrectedSampleWS, CorrectedCanWS, CorrectedSampleWS, rebin_can=rebin_can) + subractCanWorkspace(CorrectedSampleWS, CorrectedCanWS, + CorrectedSampleWS, rebin_can=rebin_can) Assc = CubicFit(corrections[1], i) - PolynomialCorrection(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedSampleWS, - Coefficients=Assc, Operation='Divide') + PolynomialCorrection(InputWorkspace=CorrectedSampleWS, + OutputWorkspace=CorrectedSampleWS, + Coefficients=Assc, Operation='Divide') if i == 0: CloneWorkspace(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedWS) else: @@ -613,7 +625,7 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S StartTime('ApplyCorrections') workdir = config['defaultsave.directory'] - s_hist,sxlen = CheckHistZero(sample) + s_hist = CheckHistZero(sample)[0] CloneWorkspace(sample, OutputWorkspace='__apply_corr_cloned_sample') sample = '__apply_corr_cloned_sample' @@ -635,11 +647,12 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S if diffraction_run and not checkUnitIs(container, 'dSpacing'): raise ValueError("Sample and Can must both have the same units.") - (instr, can_run) = getInstrRun(container) + can_run = getInstrRun(container)[1] if ScaleOrNotToScale: - #use temp workspace so we don't modify original data - Scale(InputWorkspace=container, OutputWorkspace=scaled_container, Factor=factor, Operation='Multiply') + # Use temp workspace so we don't modify original data + Scale(InputWorkspace=container, OutputWorkspace=scaled_container, + Factor=factor, Operation='Multiply') logger.information('Container scaled by %f' % factor) else: @@ -659,7 +672,6 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S cred_path = os.path.join(workdir,cor_result + ext + '.nxs') SaveNexusProcessed(InputWorkspace=cor_result + ext, Filename=cred_path) logger.information('Output file created : '+cred_path) - calc_plot = [cor_result + ext, sample] if not diffraction_run: res_plot = cor_result + '_rqw' @@ -721,7 +733,8 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S fout = outNm + str(i) CreateWorkspace(OutputWorkspace=fout, DataX=dataX, DataY=dataY, DataE=dataE, - Nspec=3, UnitX=x_unit, VerticalAxisUnit='Text', VerticalAxisValues=names) + Nspec=3, UnitX=x_unit, VerticalAxisUnit='Text', + VerticalAxisValues=names) if i == 0: group = fout @@ -735,7 +748,7 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S if Save: res_path = os.path.join(workdir,outNm[:-1] + '.nxs') SaveNexusProcessed(InputWorkspace=outNm[:-1], Filename=res_path) - logger.information('Output file created : '+res_path) + logger.information('Output file created : ' + res_path) DeleteWorkspace(cws) @@ -751,11 +764,11 @@ def plotCorrResult(inWS, PlotResult): plot_list = [] for i in range(0, nHist): plot_list.append(i) - res_plot=mp.plotSpectrum(inWS, plot_list) + MTD_PLOT.plotSpectrum(inWS, plot_list) if PlotResult == 'Contour' or PlotResult == 'Both': if nHist >= 5: #needs at least 5 hists for a contour - mp.importMatrixWorkspace(inWS).plotGraph2D() + MTD_PLOT.importMatrixWorkspace(inWS).plotGraph2D() def plotCorrContrib(plot_list, n): - con_plot = mp.plotSpectrum(plot_list, n) + MTD_PLOT.plotSpectrum(plot_list, n) diff --git a/Code/Mantid/scripts/Inelastic/IndirectImport.py b/Code/Mantid/scripts/Inelastic/IndirectImport.py index 34cf8d8e99f4..e88d525831ce 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectImport.py +++ b/Code/Mantid/scripts/Inelastic/IndirectImport.py @@ -1,16 +1,19 @@ -''' Temporary solutions to the messy problem of importing F2Py libraries into +""" +Temporary solutions to the messy problem of importing F2Py libraries into the Indirect scripts depending on platform and numpy package version. We also deal with importing the mantidplot module outside of MantidPlot here. -''' +""" import numpy import platform import sys from mantid import logger + def import_mantidplot(): - ''' Currently, all scripts in the PythonAlgorithms directory are imported + """ + Currently, all scripts in the PythonAlgorithms directory are imported during system tests. Unfortunately, these tests are run outside of MantidPlot and so are incompatible with scripts that import the "mantidplot" module. As a result, an error message is dumped to the @@ -20,7 +23,7 @@ def import_mantidplot(): Here, we silently catch all ImportErrors so that this does not occur. @returns the mantidplot module. - ''' + """ try: import mantidplot return mantidplot @@ -29,9 +32,11 @@ def import_mantidplot(): # scripts are not needed there. return None + def _os_env(): return platform.system() + platform.architecture()[0] + def _lib_suffix(): if platform.system() == "Windows": suffix = "win" @@ -41,37 +46,37 @@ def _lib_suffix(): return "" return "_" + suffix + platform.architecture()[0][0:2] + def _numpy_ver(): - return numpy.version.short_version + """ + Gets the version of Numpy installed on the host system. -def _linux_distro_name(): - return platform.linux_distribution()[0] + @return Version number + """ + return numpy.version.short_version -def _linux_distro_version(): - return platform.linux_distribution()[1] def unsupported_message(): logger.error('F2Py functionality not currently available on your platform.') sys.exit() + def is_supported_f2py_platform(): - ''' We check for numpy version, as if Linux we check its distro and version + """ + We check for numpy version, as if Linux we check its distro and version as well. @returns True if we are currently on a platform that supports the F2Py libraries, else False. - ''' + """ if _os_env().startswith("Windows") and _numpy_ver() == "1.6.2": return True - #if _os_env() == "Linux64bit" and \ - # _linux_distro_name()[0:24] == "Red Hat Enterprise Linux" and \ - # _linux_distro_version() == "6.2" and \ - # _numpy_ver() == "1.3.0": - # return True return False + def import_f2py(lib_base_name): - ''' Until we can include the compilation process of Indirect F2Py modules + """ + Until we can include the compilation process of Indirect F2Py modules into the automated build of Mantid, we are forced to compile the libraries separately on every platform we wish to support. @@ -83,7 +88,7 @@ def import_f2py(lib_base_name): of "QLres". @returns the imported module. - ''' + """ # Only proceed if we are indeed on one of the supported platforms. assert is_supported_f2py_platform() @@ -91,9 +96,11 @@ def import_f2py(lib_base_name): return __import__(lib_name) + def run_f2py_compatibility_test(): - ''' Convenience method that raises an exception should a user try to run + """ + Convenience method that raises an exception should a user try to run the F2Py libraries on an incompatible platform. - ''' + """ if not is_supported_f2py_platform(): raise RuntimeError("F2Py programs NOT available on this platform.")