diff --git a/scripts/CryPowderISIS/cry_focus.py b/scripts/CryPowderISIS/cry_focus.py index f0a2be93d12539daf3494e81950bfe200ff6d63a..2d9c7c13ab69a7ae2321e8f88154d4a6332f782c 100644 --- a/scripts/CryPowderISIS/cry_focus.py +++ b/scripts/CryPowderISIS/cry_focus.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-arguments,unused-variable +# pylint: disable=too-many-arguments,unused-variable from mantid.simpleapi import * from os.path import join diff --git a/scripts/Inelastic/CrystalField/__init__.py b/scripts/Inelastic/CrystalField/__init__.py index a2b63df3d0ebfa4893f0dee7b0bbee6aebc53427..e6f90dad972400f36ef77e2447208b4a4d306b1b 100644 --- a/scripts/Inelastic/CrystalField/__init__.py +++ b/scripts/Inelastic/CrystalField/__init__.py @@ -1,2 +1,3 @@ +from __future__ import (absolute_import, division, print_function) from .fitting import CrystalField, CrystalFieldFit, CrystalFieldMulti from .function import PeaksFunction, Background, Function diff --git a/scripts/Inelastic/CrystalField/energies.py b/scripts/Inelastic/CrystalField/energies.py index bde0175b7ca785614ddefac4a44a708df2e78a84..d4add0fcd5f1e7d16b4cff00b700d5e7037910fe 100644 --- a/scripts/Inelastic/CrystalField/energies.py +++ b/scripts/Inelastic/CrystalField/energies.py @@ -1,4 +1,5 @@ #pylint: disable=no-name-in-module +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import CrystalFieldEnergies import numpy as np import warnings diff --git a/scripts/Inelastic/CrystalField/fitting.py b/scripts/Inelastic/CrystalField/fitting.py index b4fd426abbc24193c0e5ab55fe84c4683464c3b8..91084436749e13dfa40450c725c606fa0d23e3f7 100644 --- a/scripts/Inelastic/CrystalField/fitting.py +++ b/scripts/Inelastic/CrystalField/fitting.py @@ -1,3 +1,4 @@ +from __future__ import (absolute_import, division, print_function) import numpy as np import re from mantid.kernel import ConfigService @@ -281,7 +282,7 @@ class CrystalField(object): """ if value not in self.ion_nre_map.keys(): msg = 'Value %s is not allowed for attribute Ion.\nList of allowed values: %s' %\ - (value, ', '.join(self.ion_nre_map.keys())) + (value, ', '.join(list(self.ion_nre_map.keys()))) raise RuntimeError(msg) self._ion = value self._dirty_eigensystem = True diff --git a/scripts/Inelastic/CrystalField/function.py b/scripts/Inelastic/CrystalField/function.py index 39a0edb89f1cee29324bfeb26339390a4fe7833f..aea9c21e3471cbc5d6024eea3ffdd1751923fc7d 100644 --- a/scripts/Inelastic/CrystalField/function.py +++ b/scripts/Inelastic/CrystalField/function.py @@ -1,3 +1,4 @@ +from __future__ import (absolute_import, division, print_function) import re parNamePattern = re.compile(r'([a-zA-Z][\w.]+)') @@ -153,7 +154,7 @@ class CompositeProperties(object): def getSize(self): """Get number of maps (functions) defined here""" - keys = self._properties.keys() + keys = list(self._properties.keys()) if len(keys) > 0: return max(keys) + 1 return 0 @@ -166,7 +167,7 @@ class CompositeProperties(object): for i in range(self.getSize()): if i in self._properties: props = self._properties[i] - prop_list.append(','.join(['%s=%s' % item for item in props.items()])) + prop_list.append(','.join(['%s=%s' % item for item in sorted(props.items())])) else: prop_list.append('') return prop_list @@ -184,7 +185,7 @@ class CompositeProperties(object): props = self._properties[i] if len(out) > 0: out += ',' - out += ','.join(['%s%s=%s' % ((fullPrefix,) + item) for item in props.items()]) + out += ','.join(['%s%s=%s' % ((fullPrefix,) + item) for item in sorted(props.items())]) return out[:] @@ -406,7 +407,7 @@ class Background(object): def __mul__(self, nCopies): """Make expressions like Background(...) * 8 return a list of 8 identical backgrounds.""" copies = [self] * nCopies - return map(Background.clone, copies) + return list(map(Background.clone, copies)) # return [self.clone() for i in range(nCopies)] def __rmul__(self, nCopies): diff --git a/scripts/Inelastic/Direct/DirectEnergyConversion.py b/scripts/Inelastic/Direct/DirectEnergyConversion.py index a770535b0567d0e36fc9415f6b08e65c332afa63..9b57909c4356de2bdff8efb95c1136eb63303591 100644 --- a/scripts/Inelastic/Direct/DirectEnergyConversion.py +++ b/scripts/Inelastic/Direct/DirectEnergyConversion.py @@ -1,6 +1,7 @@ -#pylint: disable=too-many-lines +#pylint: disable=too-many-lines #pylint: disable=invalid-name #pylind: disable=attribute-defined-outside-init +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.kernel import funcinspect from mantid import geometry,api @@ -11,6 +12,8 @@ import math import time import numpy as np import collections +from six import iteritems +from six.moves import range import Direct.CommonFunctions as common import Direct.diagnostics as diagnostics @@ -1087,8 +1090,8 @@ class DirectEnergyConversion(object): TOF_range = self.get_TOF_for_energies(workspace,en_list,spectra_id,ei) def process_block(tof_range): - tof_range = filter(lambda x: not(math.isnan(x)), tof_range) - dt = map(lambda x,y : abs(x - y),tof_range[1:],tof_range[:-1]) + tof_range = [x for x in tof_range if not(math.isnan(x))] + dt = list(map(lambda x,y : abs(x - y),tof_range[1:],tof_range[:-1])) t_step = min(dt) tof_min = min(tof_range) tof_max = max(tof_range) @@ -1097,7 +1100,7 @@ class DirectEnergyConversion(object): nBlocks = len(spectra_id) if nBlocks > 1: tof_min,t_step,tof_max = process_block(TOF_range[0]) - for ind in xrange(1,nBlocks): + for ind in range(1,nBlocks): tof_min1,t_step1,tof_max1 = process_block(TOF_range[ind]) tof_min = min(tof_min,tof_min1) tof_max = max(tof_max,tof_max1) @@ -1482,7 +1485,7 @@ class DirectEnergyConversion(object): scale_factor = van_multiplier * sample_multiplier / xsection - for norm_type,val in norm_factor.iteritems(): + for norm_type,val in iteritems(norm_factor): norm_factor[norm_type] = val * scale_factor # check for NaN diff --git a/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py b/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py index 76d09d7bb5b7bd5a01c8a8ef2fd2ce09601bf6e4..cb0e622476ba439a44369b7fb85c4159d2d24881 100644 --- a/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py +++ b/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py @@ -1,4 +1,5 @@ -#!/usr/bin/python +#!/usr/bin/python +from __future__ import (absolute_import, division, print_function) import os import sys import platform @@ -8,6 +9,7 @@ import copy from datetime import date import time from xml.dom import minidom +from six import iteritems # the list of instruments this configuration is applicable to INELASTIC_INSTRUMENTS = ['MAPS', 'LET', 'MERLIN', 'MARI', 'HET'] @@ -85,7 +87,7 @@ class UserProperties(object): self._rb_dirs[recent_date_id] = rb_folder_or_id if self._recent_dateID: max_date = self._start_dates[self._recent_dateID] - for date_key, a_date in self._start_dates.iteritems(): + for date_key, a_date in iteritems(self._start_dates): if a_date > max_date: self._recent_dateID = date_key max_date = a_date @@ -310,15 +312,15 @@ class UserProperties(object): def get_all_instruments(self): """ Return list of all instruments, user is working on during this cycle""" - return self._instrument.values() + return list(self._instrument.values()) def get_all_cycles(self): """Return list of all cycles the user participates in""" - return self._instrument.keys() + return list(self._instrument.keys()) def get_all_rb(self): """Return list of all rb folders the user participates in""" - return self._rb_dirs.values() + return list(self._rb_dirs.values()) # @@ -544,7 +546,7 @@ class MantidConfigDirectInelastic(object): fh_targ = open(output_file, 'w') if not fh_targ: return - var_to_replace = replacemets_list.keys() + var_to_replace = list(replacemets_list.keys()) with open(input_file) as fh_source: for line in fh_source: rez = line @@ -572,7 +574,7 @@ class MantidConfigDirectInelastic(object): shutil.copyfile(input_file, output_file) else: self._copy_and_parse_user_file(input_file, output_file, replacement_list) - os.chmod(output_file, 0777) + os.chmod(output_file, 0o777) ownership_str = "chown {0}:{1} {2}".format(self._user.userID,rb_group, output_file) if platform.system() != 'Windows': @@ -732,7 +734,7 @@ class MantidConfigDirectInelastic(object): # how to check cycle folders, they may not be available self._cycle_data_folder = set() # pylint: disable=W0212 - for date_key, folder_id in theUser._cycle_IDs.items(): + for date_key, folder_id in list(theUser._cycle_IDs.items()): self._cycle_data_folder.add(self.get_data_folder_name(theUser._instrument[date_key], folder_id)) # Initialize configuration settings self._dynamic_configuration = copy.deepcopy(self._dynamic_options_base) @@ -849,7 +851,7 @@ class MantidConfigDirectInelastic(object): users_cycles = self._user.get_all_cycles() users_rb = self._user.get_all_rb() # extract rb folder without path, which gives RB group name - users_rb = map(os.path.basename,users_rb) + users_rb = list(map(os.path.basename,users_rb)) # for cycle,rb_name in zip(users_cycles,users_rb): if key_users_list: @@ -914,7 +916,7 @@ class MantidConfigDirectInelastic(object): if __name__ == "__main__": if len(sys.argv) != 6: - print "usage: Config.py userID instrument RBNumber cycleID start_date" + print("usage: Config.py userID instrument RBNumber cycleID start_date") exit() argi = sys.argv[1:] @@ -946,19 +948,19 @@ if __name__ == "__main__": # initialize Mantid configuration # its testing route under main so it rightly imports itself #pylint: disable=W0406 - from ISISDirecInelasticConfig import MantidConfigDirectInelastic, UserProperties + from .ISISDirecInelasticConfig import MantidConfigDirectInelastic, UserProperties mcf = MantidConfigDirectInelastic(MantidDir, rootDir, UserScriptRepoDir, MapMaskDir) - print "Successfully initialized ISIS Inelastic Configuration script generator" + print("Successfully initialized ISIS Inelastic Configuration script generator") rb_user_folder = os.path.join(mcf._home_path, user.userID) user.rb_dir = rb_user_folder if not user.rb_dir_exist: - print "RB folder {0} for user {1} should exist and be accessible to configure this user".format(user.rb_dir, - user.userID) + print("RB folder {0} for user {1} should exist and be accessible to configure this user".format(user.rb_dir, + user.userID)) exit() # Configure user mcf.init_user(user.userID, user) mcf.generate_config() - print "Successfully Configured user: {0} for instrument {1} and RBNum: {2}" \ - .format(user.userID, user.instrument, user.rb_folder) + print("Successfully Configured user: {0} for instrument {1} and RBNum: {2}" + .format(user.userID, user.instrument, user.rb_folder)) diff --git a/scripts/Inelastic/Direct/NonIDF_Properties.py b/scripts/Inelastic/Direct/NonIDF_Properties.py index e1236a0cf65025993223d30a6e925c575f413806..6b1fffb112e70a62e8137ba21c4643b8aef656f7 100644 --- a/scripts/Inelastic/Direct/NonIDF_Properties.py +++ b/scripts/Inelastic/Direct/NonIDF_Properties.py @@ -1,4 +1,5 @@ -#pylint: disable=invalid-name +#pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) from Direct.PropertiesDescriptors import * from Direct.RunDescriptor import RunDescriptor,RunDescriptorDependent @@ -16,11 +17,11 @@ class NonIDF_Properties(object): # logging levels available for user #pylint: disable=unnecessary-lambda log_options = \ - { "error" : (1,lambda (msg): logger.error(msg)), - "warning" : (2,lambda (msg): logger.warning(msg)), - "notice" : (3,lambda (msg): logger.notice(msg)), - "information" : (4,lambda (msg): logger.information(msg)), - "debug" : (5,lambda (msg): logger.debug(msg))} + { "error" : (1,lambda msg: logger.error(msg)), + "warning" : (2,lambda msg: logger.warning(msg)), + "notice" : (3,lambda msg: logger.notice(msg)), + "information" : (4,lambda msg: logger.information(msg)), + "debug" : (5,lambda msg: logger.debug(msg))} def __init__(self,Instrument,run_workspace=None): """ initialize main properties, defined by the class @@ -66,7 +67,7 @@ class NonIDF_Properties(object): else: # TODO: reconcile this with Mantid. if lev <= self._current_log_level: - print msg + print(msg) #----------------------------------------------------------------------------- # Complex properties with personal descriptors #----------------------------------------------------------------------------- diff --git a/scripts/Inelastic/Direct/PropertiesDescriptors.py b/scripts/Inelastic/Direct/PropertiesDescriptors.py index 1fe7d4fab941d966ab44afbf99dbd59e02f7e97d..8ba0a0dde6235f6509d4f8fe220beed695aee3cb 100644 --- a/scripts/Inelastic/Direct/PropertiesDescriptors.py +++ b/scripts/Inelastic/Direct/PropertiesDescriptors.py @@ -1,8 +1,9 @@ -#pylint: disable=too-many-lines +#pylint: disable=too-many-lines #pylint: disable=invalid-name """ File contains collection of Descriptors used to define complex properties in NonIDF_Properties and PropertyManager classes """ +from __future__ import (absolute_import, division, print_function) import os import numpy as np import math @@ -17,6 +18,7 @@ from mantid import api,geometry,config import Direct.ReductionHelpers as prop_helpers #pylint: disable=unused-import import Direct.CommonFunctions as common +import collections #----------------------------------------------------------------------------------------- @@ -194,7 +196,7 @@ class IncidentEnergy(PropDescriptor): else: if value.find('[') > -1: energy_list = True - value = value.translate(None, '[]').strip() + value = value.replace('[','').replace(']','').strip() else: energy_list = False en_list = str.split(value,',') @@ -381,7 +383,7 @@ class EnergyBins(PropDescriptor): def __set__(self,instance,values): if values is not None: if isinstance(values,str): - values = values.translate(None, '[]').strip() + values = values.replace('[','').replace(']','').strip() lst = values.split(',') self.__set__(instance,lst) return @@ -514,7 +516,7 @@ class SaveFileName(PropDescriptor): if value is None: self._file_name = None - elif callable(value): + elif isinstance(value, collections.Callable): self._custom_print = value else: self._file_name = str(value) @@ -1067,7 +1069,7 @@ class EiMonSpectra(prop_helpers.ComplexProperty): tDict = instance.__dict__ if isinstance(value,str): - val = value.translate(None,'[]').strip() + val = value.replace('[','').replace(']','').strip() if val.find(':')>-1: val = val.split(':') else: diff --git a/scripts/Inelastic/Direct/PropertyManager.py b/scripts/Inelastic/Direct/PropertyManager.py index e74ec4c7085453e8497d3e55333bb0d93f3f3706..22fb7840ad2c49959c1bace7ecb5a6d40985f934 100644 --- a/scripts/Inelastic/Direct/PropertyManager.py +++ b/scripts/Inelastic/Direct/PropertyManager.py @@ -1,7 +1,9 @@ -#pylint: disable=invalid-name +#pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) from Direct.NonIDF_Properties import * from collections import OrderedDict,Iterable +from six import iteritems class PropertyManager(NonIDF_Properties): @@ -95,7 +97,7 @@ class PropertyManager(NonIDF_Properties): self.__dict__.update(param_dict) # use existing descriptors setter to define IDF-defined descriptor's state - for key,val in descr_dict.iteritems(): + for key,val in iteritems(descr_dict): object.__setattr__(self,key,val) # file properties -- the properties described files which should exist for reduction to work. @@ -132,7 +134,7 @@ class PropertyManager(NonIDF_Properties): class_decor = '_'+type(self).__name__+'__' - for key,val in prop_dict.iteritems(): + for key,val in iteritems(prop_dict): new_key = class_decor+key object.__setattr__(self,new_key,val) @@ -290,7 +292,7 @@ class PropertyManager(NonIDF_Properties): """ Set input properties from a dictionary of parameters """ - for par_name,value in kwargs.items() : + for par_name,value in list(kwargs.items()) : setattr(self,par_name,value) return self.getChangedProperties() @@ -339,7 +341,7 @@ class PropertyManager(NonIDF_Properties): 'instr_name':'','print_diag_results':True,'mapmask_ref_ws':None} result = {} - for key,val in diag_param_list.iteritems(): + for key,val in iteritems(diag_param_list): try: result[key] = getattr(self,key) except KeyError: @@ -379,7 +381,7 @@ class PropertyManager(NonIDF_Properties): param_list = prop_helpers.get_default_idf_param_list(pInstrument,self.__subst_dict) # remove old changes which are not related to IDF (not to reapply it again) - for prop_name in old_changes: + for prop_name in old_changes.copy(): if prop_name not in param_list: try: dependencies = getattr(PropertyManager,prop_name).dependencies() @@ -402,12 +404,12 @@ class PropertyManager(NonIDF_Properties): self.setChangedProperties(set()) #sort parameters to have complex properties (with underscore _) first - sorted_param = OrderedDict(sorted(param_list.items(),key=lambda x : ord((x[0][0]).lower()))) + sorted_param = OrderedDict(sorted(list(param_list.items()),key=lambda x : ord((x[0][0]).lower()))) # Walk through descriptors list and set their values # Assignment to descriptors should accept the form, descriptor is written in IDF changed_descriptors = set() - for key,val in descr_dict.iteritems(): + for key,val in iteritems(descr_dict): if key not in old_changes_list: try: # this is reliability check, and except ideally should never be hit. May occur if old IDF contains # properties, not present in recent IDF. @@ -458,7 +460,7 @@ class PropertyManager(NonIDF_Properties): self.setChangedProperties(changed_descriptors) # Walk through the complex properties first and then through simple properties - for key,val in sorted_param.iteritems(): + for key,val in iteritems(sorted_param.copy()): # complex properties may change through their dependencies so we are setting them first if isinstance(val,prop_helpers.ComplexProperty): public_name = key[1:] @@ -501,7 +503,7 @@ class PropertyManager(NonIDF_Properties): self.setChangedProperties(set()) # set back all changes stored earlier and may be overwritten by new IDF # (this is just to be sure -- should not change anything as we do not set properties changed) - for key,val in old_changes.iteritems(): + for key,val in iteritems(old_changes): setattr(self,key,val) # Clear changed properties list (is this wise?, may be we want to know that some defaults changed?) @@ -739,7 +741,7 @@ class PropertyManager(NonIDF_Properties): for key in changed_Keys: if key in already_changed: continue - val = getattr(self,key) + val = str(getattr(self,key)) self.log(" Value of : {0:<25} is set to : {1:<20} ".format(key,val),log_level) if not display_header: diff --git a/scripts/Inelastic/Direct/ReductionHelpers.py b/scripts/Inelastic/Direct/ReductionHelpers.py index 1d8a8de7e4978016a607f32c0d741225c4394b90..de58a85f0188d6860ba9753c288071ca9527b00e 100644 --- a/scripts/Inelastic/Direct/ReductionHelpers.py +++ b/scripts/Inelastic/Direct/ReductionHelpers.py @@ -1,7 +1,9 @@ -#pylint: disable=invalid-name +#pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) from mantid import config import os - +import re +from six.moves import range """ Set of functions to assist with processing instrument parameters relevant to reduction. """ @@ -143,7 +145,7 @@ def build_properties_dict(param_map,synonims,descr_list=[]) : final_name = str(name) prelim_dict[final_name]=None - param_keys = prelim_dict.keys() + param_keys = list(prelim_dict.keys()) properties_dict = dict() descr_dict = dict() @@ -230,7 +232,7 @@ def build_subst_dictionary(synonims_list=None) : if len(keys[0]) == 0: raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, " "but the first key is empty") - for i in xrange(1,len(keys)) : + for i in range(1,len(keys)) : if len(keys[i]) == 0 : raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, " "but the key"+str(i)+" is empty") @@ -343,7 +345,7 @@ def parse_single_name(filename): if ind1>ind2: raise ValueError('Invalid file number defined using colon : left run number ' '{0} has to be large then right {1}'.format(ind1,ind2)) - number = range(ind1[0],ind2[0]+1) + number = list(range(ind1[0],ind2[0]+1)) if len(filepath)>0: filepath=[filepath]*len(number) else: @@ -356,11 +358,11 @@ def parse_single_name(filename): return (filepath,number,fext) fname,fext = os.path.splitext(fname) - fnumber = filter(lambda x: x.isdigit(), fname) + fnumber = re.findall('\d+', fname) if len(fnumber) == 0: number = 0 else: - number = int(fnumber) + number = int(fnumber[0]) return ([filepath],[number],[fext]) @@ -380,7 +382,7 @@ def parse_run_file_name(run_string): filenum+=ind fext+=ext1 - non_empty = filter(lambda x: len(x) >0, fext) + non_empty = [x for x in fext if len(x) >0] if len(non_empty)>0: anExt = non_empty[-1] for i,val in enumerate(fext): @@ -402,7 +404,7 @@ def process_prop_list(workspace,logName="CombinedSpectraIDList"): """ if workspace.run().hasProperty(logName): spec_id_str = workspace.run().getProperty(logName).value - spec_id_str = spec_id_str.translate(None,'[]').strip() + spec_id_str = spec_id_str.replace('[','').replace(']','').strip() spec_id_listS = spec_id_str.split(',') spec_list = [] for val in spec_id_listS: diff --git a/scripts/Inelastic/Direct/ReductionWrapper.py b/scripts/Inelastic/Direct/ReductionWrapper.py index e54d91d41116e14de2cdbcc43c8ff6ac96a94755..3c65852a01463c559c4136a915ce3265c480bbfc 100644 --- a/scripts/Inelastic/Direct/ReductionWrapper.py +++ b/scripts/Inelastic/Direct/ReductionWrapper.py @@ -1,4 +1,5 @@ -#pylint: disable=invalid-name +#pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid import config,api from mantid.kernel import funcinspect @@ -9,6 +10,7 @@ from Direct.DirectEnergyConversion import DirectEnergyConversion import os import re import time +from six import iteritems try: import h5py h5py_installed = True @@ -119,7 +121,7 @@ class ReductionWrapper(object): f = open(FileName,'w') f.write("standard_vars = {\n") str_wrapper = ' ' - for key,val in self._wvs.standard_vars.iteritems(): + for key,val in iteritems(self._wvs.standard_vars): if isinstance(val,str): row = "{0}\'{1}\':\'{2}\'".format(str_wrapper,key,val) else: @@ -129,7 +131,7 @@ class ReductionWrapper(object): f.write("\n}\nadvanced_vars={\n") #print advances variables str_wrapper = ' ' - for key,val in self._wvs.advanced_vars.iteritems(): + for key,val in iteritems(self._wvs.advanced_vars): if isinstance(val,str): row = "{0}\'{1}\':\'{2}\'".format(str_wrapper,key,val) else: diff --git a/scripts/Inelastic/Direct/RunDescriptor.py b/scripts/Inelastic/Direct/RunDescriptor.py index 92fa99c872889109da89ce505008292300b23b08..ca658dbbcafeb1231e15f76dda728417b17b1945 100644 --- a/scripts/Inelastic/Direct/RunDescriptor.py +++ b/scripts/Inelastic/Direct/RunDescriptor.py @@ -1,8 +1,9 @@ -#pylint: disable=too-many-lines +#pylint: disable=too-many-lines #pylint: disable=invalid-name #pylint: disable=attribute-defined-outside-init """ File contains Descriptors used describe run for direct inelastic reduction """ +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from Direct.PropertiesDescriptors import * import re @@ -1339,7 +1340,7 @@ class RunDescriptor(PropDescriptor): # Hell knows how to redefine these warnings or if they are valid or not #pylint: disable=W0141 #pylint: disable=W0110 - self._ws_cname = part_ind + filter(lambda c: not c.isdigit(), name) + self._ws_cname = part_ind + ''.join(re.findall('\D+', name)) else: #pylint: disable=attribute-defined-outside-init self._ws_cname = part_ind + name diff --git a/scripts/Inelastic/Direct/dgreduce.py b/scripts/Inelastic/Direct/dgreduce.py index 53da051137e7ec56d90377d0efb6d8fd7ce723d6..6627d4c9770e6f1d75117fe16cba47d14845b56f 100644 --- a/scripts/Inelastic/Direct/dgreduce.py +++ b/scripts/Inelastic/Direct/dgreduce.py @@ -1,5 +1,6 @@ #pylint: disable=invalid-name """ Empty class temporary left for compatibility with previous interfaces """ +from __future__ import (absolute_import, division, print_function) import Direct.DirectEnergyConversion as DRC from mantid.simpleapi import * from mantid.kernel import funcinspect diff --git a/scripts/Inelastic/Direct/diagnostics.py b/scripts/Inelastic/Direct/diagnostics.py index 0387017ea7f1d93e0e20760de33ec83d4159ad4c..0916cdd231a60bab54baddc1713c8e8c2ef38b2a 100644 --- a/scripts/Inelastic/Direct/diagnostics.py +++ b/scripts/Inelastic/Direct/diagnostics.py @@ -11,11 +11,13 @@ The output of each function is a workspace containing a single bin where: This workspace can be summed with other masked workspaces to accumulate masking and also passed to MaskDetectors to match masking there. """ +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.kernel.funcinspect import lhs_info import os import Direct.RunDescriptor as RunDescriptor from Direct.PropertyManager import PropertyManager +from six import iteritems # Reference to reducer used if necessary for working with run descriptors (in diagnostics) __Reducer__ = None @@ -412,13 +414,13 @@ def print_test_summary(test_results,test_name=None): """ if len(test_results) == 0: - print "No tests have been run!" + print("No tests have been run!") return if test_name is None: - print '======== Diagnostic Test Summary ' + print('======== Diagnostic Test Summary ') else: - print '======== Diagnostic Test Summary {0} '.format(test_name) + print('======== Diagnostic Test Summary {0} '.format(test_name)) max_test_len = 0 max_ws_len = 0 @@ -432,10 +434,10 @@ def print_test_summary(test_results,test_name=None): for t_name in test_results: t_result = test_results[t_name] - print format_string.format(t_name,t_result[0],t_result[1]) + print(format_string.format(t_name,t_result[0],t_result[1])) # Append a new line - print '================================================================' - print '' + print('================================================================') + print('') #------------------------------------------------------------------------------- @@ -470,5 +472,5 @@ class ArgumentParser(object): def __init__(self, keywords): self.start_index = None # Make this more general for anything that is missing! self.end_index = None - for key, value in keywords.iteritems(): + for key, value in iteritems(keywords): setattr(self, key, value) diff --git a/scripts/Interface/ui/reflectometer/refl_gui.py b/scripts/Interface/ui/reflectometer/refl_gui.py index 682af79e8f4db33b068de7d1cf2ea2876794787a..658fa1ce51d6114827b7569bd5f51a9110d9bca2 100644 --- a/scripts/Interface/ui/reflectometer/refl_gui.py +++ b/scripts/Interface/ui/reflectometer/refl_gui.py @@ -1,4 +1,4 @@ -# pylint: disable = too-many-lines, invalid-name, line-too-long, too-many-instance-attributes, too-many-branches,too-many-locals, too-many-nested-blocks +# pylint: disable = too-many-lines, invalid-name, line-too-long, too-many-instance-attributes, too-many-branches,too-many-locals, too-many-nested-blocks try: from mantidplot import * diff --git a/scripts/QECoverage.py b/scripts/QECoverage.py index 92a075f750c3d0c43e50890be81daf0ae9b7744d..41336738b16e1f100b9df5d92dde5b7ff6c44c48 100644 --- a/scripts/QECoverage.py +++ b/scripts/QECoverage.py @@ -1,4 +1,4 @@ -# pylint: disable=line-too-long, too-many-instance-attributes, invalid-name, missing-docstring, too-many-statements +# pylint: disable=line-too-long, too-many-instance-attributes, invalid-name, missing-docstring, too-many-statements # pylint: disable= too-many-branches, no-self-use import sys diff --git a/scripts/Reflectometry/isis_reflectometry/combineMulti.py b/scripts/Reflectometry/isis_reflectometry/combineMulti.py index d63deb17dbeb187eedf95c1175e7ad0ab2dd3528..d305edbc037fc1f9fbe6ef3224aad37935780539 100644 --- a/scripts/Reflectometry/isis_reflectometry/combineMulti.py +++ b/scripts/Reflectometry/isis_reflectometry/combineMulti.py @@ -1,5 +1,6 @@ # pylint: disable=invalid-name -from l2q import * +from __future__ import (absolute_import, division, print_function) +from .l2q import * from mantid.simpleapi import * from mantid.api import WorkspaceGroup @@ -27,12 +28,12 @@ def combineDataMulti(wksp_list, output_wksp, beg_overlap, end_overlap, Qmin, Qma if not isinstance(end_overlap, list): end_overlap = [end_overlap] if len(wksp_list) != len(beg_overlap): - print "Using default values!" + print("Using default values!") defaultoverlaps = True # copy first workspace into temporary wksp 'currentSum' currentSum = CloneWorkspace(InputWorkspace=wksp_list[0]) - print "Length: ", len(wksp_list), wksp_list + print("Length: ", len(wksp_list), wksp_list) for i in range(0, len(wksp_list) - 1): w1 = currentSum @@ -45,7 +46,7 @@ def combineDataMulti(wksp_list, output_wksp, beg_overlap, end_overlap, Qmin, Qma else: overlapLow = beg_overlap[i + 1] overlapHigh = end_overlap[i] - print "Iteration", i + print("Iteration", i) currentSum, scale_factor = stitch2(currentSum, mtd[wksp_list[i + 1]], currentSum.name(), overlapLow, overlapHigh, Qmin, Qmax, binning, scale_high, scale_right=scale_right) RenameWorkspace(InputWorkspace=currentSum.name(), OutputWorkspace=output_wksp) diff --git a/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py b/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py index 46d7ac1b7688292e75ffc542fcf1f5fb9d3733fb..49c1fe6b3e11c1d856175d082ccdffcb9c6b711d 100644 --- a/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py +++ b/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py @@ -1,4 +1,5 @@ #pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) import mantid.simpleapi as msi import mantid.api from mantid.kernel import logger diff --git a/scripts/Reflectometry/isis_reflectometry/l2q.py b/scripts/Reflectometry/isis_reflectometry/l2q.py index d829f3bdc27ac27b56b8e07e2c8f3929166e6962..b192b4ef490ef2907ce414746d4e6e5245884126 100644 --- a/scripts/Reflectometry/isis_reflectometry/l2q.py +++ b/scripts/Reflectometry/isis_reflectometry/l2q.py @@ -1,5 +1,6 @@ #pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) import math from mantid.simpleapi import * # New API diff --git a/scripts/Reflectometry/isis_reflectometry/load_live_runs.py b/scripts/Reflectometry/isis_reflectometry/load_live_runs.py index a8cddb5d8ca2d5a6a85bcd2ea0a652f5750257ba..f441a47e7db02a1c56ce965320d23dace2ab8f88 100644 --- a/scripts/Reflectometry/isis_reflectometry/load_live_runs.py +++ b/scripts/Reflectometry/isis_reflectometry/load_live_runs.py @@ -1,4 +1,5 @@ #pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * diff --git a/scripts/Reflectometry/isis_reflectometry/procedures.py b/scripts/Reflectometry/isis_reflectometry/procedures.py index f611e775a2af843da161d7d254f9820cf9964652..cb50714fa4cf7c40ccd19d41b214ecc4a5853722 100644 --- a/scripts/Reflectometry/isis_reflectometry/procedures.py +++ b/scripts/Reflectometry/isis_reflectometry/procedures.py @@ -1,5 +1,6 @@ # pylint: disable=too-many-lines, invalid-name, too-many-arguments, too-many-branches, too-many-locals +from __future__ import (absolute_import, division, print_function) from math import * try: @@ -94,13 +95,13 @@ def parseRunList(istring): tstr[j].strip() tstr2 = tstr[j].split('-') tstr3 = tstr2[1].split(':') - r1 = range(int(tstr2[0]), int(tstr3[0]) + 1, int(tstr3[1])) + r1 = list(range(int(tstr2[0]), int(tstr3[0]) + 1, int(tstr3[1]))) for k in r1: rlist2.append(str(k)) elif tstr[j].find('-') >= 0: tstr[j].strip() tstr2 = tstr[j].split('-') - r1 = range(int(tstr2[0]), int(tstr2[1]) + 1) + r1 = list(range(int(tstr2[0]), int(tstr2[1]) + 1)) for k in r1: rlist2.append(str(k)) else: @@ -110,13 +111,13 @@ def parseRunList(istring): rlist1[i].strip() tstr2 = rlist1[i].split('-') tstr3 = tstr2[1].split(':') - r1 = range(int(tstr2[0]), int(tstr3[0]) + 1, int(tstr3[1])) + r1 = list(range(int(tstr2[0]), int(tstr3[0]) + 1, int(tstr3[1]))) for k in r1: rlist2.append(str(k)) elif rlist1[i].find('-') >= 0: rlist1[i].strip() tstr2 = rlist1[i].split('-') - r1 = range(int(tstr2[0]), int(tstr2[1]) + 1) + r1 = list(range(int(tstr2[0]), int(tstr2[1]) + 1)) for k in r1: rlist2.append(str(k)) else: @@ -460,7 +461,7 @@ def nrCalcSEConst(RFFrequency, poleShoeAngle): th0 = -0.0000000467796 * (th0 ** 5) + 0.0000195413 * (th0 ** 4) - 0.00326229 * (th0 ** 3) + 0.271767 * ( th0 ** 2) - 10.4269 * th0 + 198.108 c1 = Gl * m * 2.0 * B * L / (2.0 * pi * h * tan(th0 * pi / 180.0) * 1.0e20) - print c1 * 1e8 + print(c1 * 1e8) return c1 * 1e8 @@ -556,7 +557,7 @@ def nrSERGISFn(runList, nameList, P0runList, P0nameList, incidentAngles, SEConst # print str(2.0*float(incAngles[k]))+" "+str(atan((float(minSpec)-float(specChan))*1.2e-3/3.63)*180.0/pi)+" "+str(a1) RotateInstrumentComponent(wksp + "det", "DetectorBench", X="-1.0", Angle=str(a1)) GroupDetectors(wksp + "det", wksp + "sum", - WorkspaceIndexList=range(int(minSpec) - 5, int(maxSpec) - 5 + 1), + WorkspaceIndexList=list(range(int(minSpec) - 5, int(maxSpec) - 5 + 1)), KeepUngroupedSpectra="0") Divide(wksp + "sum", wksp + "mon", wksp + "norm") Divide(wksp + "det", wksp + "mon", wksp + "detnorm") @@ -699,7 +700,7 @@ def nrNRFn(runList, nameList, incidentAngles, DBList, specChan, minSpec, maxSpec EndWorkspaceIndex=mon_spec) Rebin(InputWorkspace=i + "mon", OutputWorkspace=i + "mon", Params=reb) Rebin(InputWorkspace=i + "det", OutputWorkspace=i + "det", Params=reb) - GroupDetectors(i + "det", i + "sum", WorkspaceIndexList=range(int(minSpec) - 5, int(maxSpec) - 5 + 1), + GroupDetectors(i + "det", i + "sum", WorkspaceIndexList=list(range(int(minSpec) - 5, int(maxSpec) - 5 + 1)), KeepUngroupedSpectra="0") Divide(i + "sum", i + "mon", i + "norm") Divide(i + "det", i + "mon", i + "detnorm") @@ -779,7 +780,7 @@ def nrDBFn(runListShort, nameListShort, runListLong, nameListLong, nameListComb, else: CropWorkspace(InputWorkspace=i, OutputWorkspace=i + "det", StartWorkspaceIndex=4, EndWorkspaceIndex=243) floodnorm(i + "det", floodfile) - GroupDetectors(i + "det", i + "sum", WorkspaceIndexList=range(int(minSpec) - 5, int(maxSpec) - 5 + 1), + GroupDetectors(i + "det", i + "sum", WorkspaceIndexList=list(range(int(minSpec) - 5, int(maxSpec) - 5 + 1)), KeepUngroupedSpectra="0") Divide(i + "sum", i + "mon", i + "norm") ReplaceSpecialValues(i + "norm", i + "norm", "0.0", "0.0", "0.0", "0.0") @@ -804,7 +805,7 @@ def nrDBFn(runListShort, nameListShort, runListLong, nameListLong, nameListComb, else: CropWorkspace(InputWorkspace=i, OutputWorkspace=i + "det", StartWorkspaceIndex=4, EndWorkspaceIndex=243) floodnorm(i + "det", floodfile) - GroupDetectors(i + "det", i + "sum", WorkspaceIndexList=range(int(minSpec) - 5, int(maxSpec) - 5 + 1), + GroupDetectors(i + "det", i + "sum", WorkspaceIndexList=list(range(int(minSpec) - 5, int(maxSpec) - 5 + 1)), KeepUngroupedSpectra="0") Divide(i + "sum", i + "mon", i + "norm") ReplaceSpecialValues(i + "norm", i + "norm", "0.0", "0.0", "0.0", "0.0") @@ -913,12 +914,12 @@ def NRCombineDatafn(RunsNameList, CombNameList, applySFs, SFList, SFError, scale if scaleOption != "2": Divide("i" + str(i) + "1temp", "i" + str(i) + "2temp", "sf" + str(i)) a1 = mtd["sf" + str(i)] - print "sf" + str(i) + "=" + str(a1.readY(0)) + " +/- " + str(a1.readE(0)) + print("sf" + str(i) + "=" + str(a1.readY(0)) + " +/- " + str(a1.readE(0))) sfs.append(str(a1.readY(0)[0])) sferrs.append(str(a1.readE(0)[0])) else: Divide("i" + str(i) + "2temp", "i" + str(i) + "1temp", "sf" + str(i)) - print "sf" + str(i) + "=" + str(a1.readY(0)) + " +/- " + str(a1.readE(0)) + print("sf" + str(i) + "=" + str(a1.readY(0)) + " +/- " + str(a1.readE(0))) sfs.append(str(a1.readY(0)[0])) sferrs.append(str(a1.readE(0)[0])) mtd.deleteWorkspace("i" + str(i) + "1temp") @@ -1161,8 +1162,8 @@ def nrPNRFn(runList, nameList, incidentAngles, DBList, specChan, minSpec, maxSpe if nper > 2: for j in range(2, nper): Plus("wbgdsum", "bgdtemp" + "_" + pnums[j], OutputWorkspace="wbgdsum") - GroupDetectors("wbgdsum", "bgd2", WorkspaceIndexList=range(0, 50), KeepUngroupedSpectra="0") - GroupDetectors("wbgdsum", "bgd1", WorkspaceIndexList=range(160, 240), KeepUngroupedSpectra="0") + GroupDetectors("wbgdsum", "bgd2", WorkspaceIndexList=list(range(0, 50)), KeepUngroupedSpectra="0") + GroupDetectors("wbgdsum", "bgd1", WorkspaceIndexList=list(range(160, 240)), KeepUngroupedSpectra="0") Plus("bgd1", "bgd2", OutputWorkspace="bgd") wbgdtemp = mtd["bgd"] / (130.0 * nper) mtd.deleteWorkspace("bgdtemp") @@ -1200,11 +1201,11 @@ def nrPNRFn(runList, nameList, incidentAngles, DBList, specChan, minSpec, maxSpe ResetNegatives(InputWorkspace=wksp + "det", OutputWorkspace=wksp + "det", AddMinimum='0', ResetValue="0.0") GroupDetectors(wksp + "det", wksp + "sum", - WorkspaceIndexList=range(int(minSpec) - 5, int(maxSpec) - 5 + 1), + WorkspaceIndexList=list(range(int(minSpec) - 5, int(maxSpec) - 5 + 1)), KeepUngroupedSpectra="0") else: GroupDetectors(wksp + "det", wksp + "sum", - WorkspaceIndexList=range(int(minSpec) - 5, int(maxSpec) - 5 + 1), + WorkspaceIndexList=list(range(int(minSpec) - 5, int(maxSpec) - 5 + 1)), KeepUngroupedSpectra="0") RebinToWorkspace(WorkspaceToRebin=wksp + "sum", WorkspaceToMatch=wksp + "mon", OutputWorkspace=wksp + "sum") Divide(LHSWorkspace=wksp + "sum", RHSWorkspace=wksp + "mon", OutputWorkspace=wksp + "norm") diff --git a/scripts/Reflectometry/isis_reflectometry/quick.py b/scripts/Reflectometry/isis_reflectometry/quick.py index 75a4653bf81e777d4a0ee39074aedc5f851e79ce..c99fc588e53cae49d5f4eb3c8f50ed62cda02a35 100644 --- a/scripts/Reflectometry/isis_reflectometry/quick.py +++ b/scripts/Reflectometry/isis_reflectometry/quick.py @@ -9,6 +9,7 @@ ''' # these need to be moved into one NR folder or so # from ReflectometerCors import * +from __future__ import (absolute_import, division, print_function) from isis_reflectometry.l2q import * from isis_reflectometry.combineMulti import * from mantid.simpleapi import * # New API @@ -19,6 +20,7 @@ from isis_reflectometry.convert_to_wavelength import ConvertToWavelength import math import re import abc +from six import with_metaclass def enum(**enums): @@ -28,9 +30,7 @@ def enum(**enums): PolarisationCorrection = enum(PNR=1, PA=2, NONE=3) -class CorrectionStrategy(object): - __metaclass__ = abc.ABCMeta # Mark as an abstract class - +class CorrectionStrategy(with_metaclass(abc.ABCMeta, object)): @abc.abstractmethod def apply(self, to_correct): pass @@ -138,8 +138,8 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_min inst = _sample_ws.getInstrument() # Some beamline constants from IDF - print i0_monitor_index - print nHist + print(i0_monitor_index) + print(nHist) if run == '0': RunNumber = '0' @@ -149,7 +149,7 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_min if not pointdet: # Proccess Multi-Detector; assume MD goes to the end: # if roi or db are given in the function then sum over the apropriate channels - print "This is a multidetector run." + print("This is a multidetector run.") _I0M = RebinToWorkspace(WorkspaceToRebin=_monitor_ws, WorkspaceToMatch=_detector_ws) IvsLam = _detector_ws / _I0M @@ -166,14 +166,14 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_min # Single Detector processing------------------------------------------------------------- else: - print "This is a Point-Detector run." + print("This is a Point-Detector run.") # handle transmission runs # process the point detector reflectivity _I0P = RebinToWorkspace(WorkspaceToRebin=_monitor_ws, WorkspaceToMatch=_detector_ws) IvsLam = Scale(InputWorkspace=_detector_ws, Factor=1) if not trans: - print "No transmission file. Trying default exponential/polynomial correction..." + print("No transmission file. Trying default exponential/polynomial correction...") IvsLam = correction_strategy.apply(_detector_ws) IvsLam = Divide(LHSWorkspace=IvsLam, RHSWorkspace=_I0P) else: # we have a transmission run @@ -199,11 +199,11 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_min if not theta: theta = inst.getComponentByName(detector_component_name).getTwoTheta(sampleLocation, beamPos) * 180.0 / math.pi / 2.0 - print "Det location: ", detLocation, "Calculated theta = ", theta + print("Det location: ", detLocation, "Calculated theta = ", theta) if correct_positions: # detector is not in correct place # Get detector angle theta from NeXuS logger.information('The detectorlocation is not at Y=0') - print 'Nexus file theta =', theta + print('Nexus file theta =', theta) IvsQ = l2q(IvsLam, detector_component_name, theta, sample_component_name) else: IvsQ = ConvertUnits(InputWorkspace=IvsLam, OutputWorkspace="IvsQ", Target="MomentumTransfer") @@ -278,7 +278,7 @@ def make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_p if isinstance(transrun, str) and (',' in transrun): slam = transrun.split(',')[0] llam = transrun.split(',')[1] - print "Transmission runs: ", transrun + print("Transmission runs: ", transrun) to_lam = ConvertToWavelength(slam) _monitor_ws_slam, _detector_ws_slam = to_lam.convert(wavelength_min=lambda_min, wavelength_max=lambda_max, @@ -302,7 +302,7 @@ def make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_p _mon_int_trans = Integration(InputWorkspace=_i0p_llam, RangeLower=int_min, RangeUpper=int_max) _detector_ws_llam = Divide(LHSWorkspace=_detector_ws_llam, RHSWorkspace=_mon_int_trans) - print stitch_start_overlap, stitch_end_overlap, stitch_params + print(stitch_start_overlap, stitch_end_overlap, stitch_params) transWS, _outputScaling = Stitch1D(LHSWorkspace=_detector_ws_slam, RHSWorkspace=_detector_ws_llam, StartOverlap=stitch_start_overlap, EndOverlap=stitch_end_overlap, Params=stitch_params) @@ -363,7 +363,7 @@ def polCorr(polcorr, IvsLam, crho, calpha, cAp, cPp): else: message = "No Polarisation Correction Requested." logger.notice(message) - print message + print(message) return IvsLam @@ -397,7 +397,7 @@ def get_defaults(run_ws, polcorr=False): if polcorr and (polcorr != PolarisationCorrection.NONE): def str_to_float_list(_str): str_list = _str.split(',') - float_list = map(float, str_list) + float_list = list(map(float, str_list)) return float_list defaults['crho'] = str_to_float_list(instrument.getStringParameter('crho')[0]) @@ -428,10 +428,10 @@ def nrPNRCorrection(Wksp, crho, calpha, cAp, cPp): # cPp=[0.972762,0.001828,-0.000261,0.0] message = "Performing PNR correction" logger.notice(message) - print message + print(message) CloneWorkspace(Wksp, OutputWorkspace='_' + Wksp + '_uncorrected') if (not isinstance(mtd[Wksp], WorkspaceGroup)) or (not mtd[Wksp].size() == 2): - print "PNR correction works only with exactly 2 periods!" + print("PNR correction works only with exactly 2 periods!") return mtd[Wksp] else: Ip = mtd[Wksp][0] @@ -499,10 +499,10 @@ def nrPACorrection(Wksp, crho, calpha, cAp, cPp): # UpUpWksp,UpDownWksp,DownUpW # Ipa and Iap appear to be swapped in the sequence on CRISP 4 perido data! message = "Performing PA correction" logger.notice(message) - print message + print(message) CloneWorkspace(Wksp, OutputWorkspace='_' + Wksp + '_uncorrected') if (not isinstance(mtd[Wksp], WorkspaceGroup)) or (not mtd[Wksp].size() == 4): - print "PNR correction works only with exactly 4 periods (uu,ud,du,dd)!" + print("PNR correction works only with exactly 4 periods (uu,ud,du,dd)!") return mtd[Wksp] else: Ipp = mtd[Wksp][0] @@ -600,7 +600,7 @@ def groupGet(wksp, whattoget, field=''): res = log[len(log) - 1] except RuntimeError: res = 0 - print "Block " + field + " not found." + print("Block " + field + " not found.") else: try: log = mtd[wksp].getRun().getLogData(field).value @@ -610,7 +610,7 @@ def groupGet(wksp, whattoget, field=''): res = log[len(log) - 1] except RuntimeError: res = 0 - print "Block " + field + " not found." + print("Block " + field + " not found.") return res elif whattoget == 'wksp': if isinstance(mtd[wksp], WorkspaceGroup): diff --git a/scripts/Reflectometry/isis_reflectometry/saveModule.py b/scripts/Reflectometry/isis_reflectometry/saveModule.py index 4910e22b3a8b9e807b848dde85231647958ffb98..572ef67d3485e7962735ad26dcc09b0ed3a87d01 100644 --- a/scripts/Reflectometry/isis_reflectometry/saveModule.py +++ b/scripts/Reflectometry/isis_reflectometry/saveModule.py @@ -1,4 +1,5 @@ #pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) from PyQt4 import QtCore from mantid.simpleapi import * import numpy as n @@ -12,7 +13,7 @@ except AttributeError: def saveCustom(idx,fname,sep = ' ',logs = [],title = False,error = False): fname+='.dat' - print "FILENAME: ", fname + print("FILENAME: ", fname) a1=mtd[str(idx.text())] titl='#'+a1.getTitle()+'\n' x1=a1.readX(0) @@ -28,10 +29,10 @@ def saveCustom(idx,fname,sep = ' ',logs = [],title = False,error = False): for log in logs: prop = samp.getLogData(str(log.text())) headerLine='#'+log.text() + ': ' + str(prop.value) + '\n' - print headerLine + print(headerLine) f.write(headerLine) qres=(X1[1]-X1[0])/X1[1] - print "Constant dq/q from file: ",qres + print("Constant dq/q from file: ",qres) for i in range(len(X1)): if error: dq=X1[i]*qres @@ -44,7 +45,7 @@ def saveCustom(idx,fname,sep = ' ',logs = [],title = False,error = False): def saveANSTO(idx,fname): fname+='.txt' - print "FILENAME: ", fname + print("FILENAME: ", fname) a1=mtd[str(idx.text())] x1=a1.readX(0) X1=n.zeros((len(x1)-1)) @@ -55,7 +56,7 @@ def saveANSTO(idx,fname): sep='\t' f=open(fname,'w') qres=(X1[1]-X1[0])/X1[1] - print "Constant dq/q from file: ",qres + print("Constant dq/q from file: ",qres) for i in range(len(X1)): dq=X1[i]*qres s="%e" % X1[i] +sep+"%e" % y1[i] +sep + "%e" % e1[i] + sep + "%e" % dq +"\n" @@ -65,7 +66,7 @@ def saveANSTO(idx,fname): def saveMFT(idx,fname,logs): fname+='.mft' - print "FILENAME: ", fname + print("FILENAME: ", fname) a1=mtd[str(idx.text())] x1=a1.readX(0) X1=n.zeros((len(x1)-1)) @@ -89,7 +90,7 @@ def saveMFT(idx,fname,logs): for log in logs: prop = samp.getLogData(str(log.text())) headerLine=log.text() + ': ' + str(prop.value) + '\n' - print headerLine + print(headerLine) f.write(headerLine) f.write('Number of file format: 2\n') s = 'Number of data points:\t' + str(len(X1))+'\n' @@ -97,7 +98,7 @@ def saveMFT(idx,fname,logs): f.write('\n') f.write('\tq\trefl\trefl_err\tq_res\n') qres=(X1[1]-X1[0])/X1[1] - print "Constant dq/q from file: ",qres + print("Constant dq/q from file: ",qres) for i in range(len(X1)): dq=X1[i]*qres s="\t%e" % X1[i] +sep+"%e" % y1[i] +sep + "%e" % e1[i] + sep + "%e" % dq +"\n" diff --git a/scripts/Reflectometry/isis_reflectometry/settings.py b/scripts/Reflectometry/isis_reflectometry/settings.py index 04a749429c9304988d2c461f790dd9904cd6c9fe..06ee5e46b64b401990f28087476bb960a1d8834f 100644 --- a/scripts/Reflectometry/isis_reflectometry/settings.py +++ b/scripts/Reflectometry/isis_reflectometry/settings.py @@ -1,3 +1,4 @@ +from __future__ import (absolute_import, division, print_function) import xml.etree.ElementTree as XML import os.path @@ -44,7 +45,7 @@ class Settings(object): if not value: raise ValueError("Missing value for Setting element") temp[key] = value - self.__contents = dict(frozenset(temp.items())) + self.__contents = dict(frozenset(list(temp.items()))) def get_all_entries(self): return self.__contents diff --git a/scripts/SANS/DarkRunCorrection.py b/scripts/SANS/DarkRunCorrection.py index c73dcc064b660aa405f2510bd3b7f015a254a6c3..6d32e9488d44a67802658d692ed04e1a7e52204a 100644 --- a/scripts/SANS/DarkRunCorrection.py +++ b/scripts/SANS/DarkRunCorrection.py @@ -1,4 +1,5 @@ -#pylint: disable=invalid-name +#pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * diff --git a/scripts/SANS/ISISCommandInterface.py b/scripts/SANS/ISISCommandInterface.py index 07d9163db62469f9afd7f1a9dd5f5daf2f244930..f75dfa15c9762b7af925d00d249c646a1fcbea9b 100644 --- a/scripts/SANS/ISISCommandInterface.py +++ b/scripts/SANS/ISISCommandInterface.py @@ -1,8 +1,9 @@ -# pylint: disable=too-many-lines, invalid-name, redefined-builtin, protected-access, too-many-arguments +# pylint: disable=too-many-lines, invalid-name, redefined-builtin, protected-access, too-many-arguments """ Enables the SANS commands (listed at http://www.mantidproject.org/SANS) to be run """ +from __future__ import (absolute_import, division, print_function) import isis_instrument from reducer_singleton import ReductionSingleton from mantid.kernel import Logger @@ -23,7 +24,7 @@ sanslog = Logger("SANS") # disable plotting if running outside Mantidplot try: import mantidplot -except (StandardError, Warning): +except (Exception, Warning): mantidplot = None # this should happen when this is called from outside Mantidplot and only then, # the result is that attempting to plot will raise an exception @@ -52,7 +53,7 @@ def _printMessage(msg, log=True, no_console=False): if log and _VERBOSE_: sanslog.notice(msg) if not no_console: - print msg + print(msg) def issueWarning(msg): @@ -90,7 +91,7 @@ def SANS2D(idf_path=None): raise RuntimeError("The provided idf path seems to have been incorrect") ReductionSingleton().set_instrument(instrument) config['default.instrument'] = 'SANS2D' - except (StandardError, Warning): + except (Exception, Warning): return False return True @@ -115,7 +116,7 @@ def LOQ(idf_path='LOQ_Definition_20020226-.xml'): raise RuntimeError("The provided idf path seems to have been incorrect") ReductionSingleton().set_instrument(instrument) config['default.instrument'] = 'LOQ' - except(StandardError, Warning): + except(Exception, Warning): return False return True @@ -134,7 +135,7 @@ def LARMOR(idf_path = None): raise RuntimeError("The provided idf path seems to have been incorrect") ReductionSingleton().set_instrument(instrument) config['default.instrument'] = 'LARMOR' - except (StandardError, Warning): + except (Exception, Warning): return False return True @@ -261,7 +262,7 @@ def _return_old_compatibility_assign_methods(ws_name): if isinstance(ReductionSingleton().instrument, isis_instrument.SANS2D): try: logs = ReductionSingleton().instrument.get_detector_log(ws_name) - except (StandardError, Warning): + except (Exception, Warning): pass return ws_name, logs @@ -713,7 +714,7 @@ def delete_workspaces(workspaces): if wksp and wksp in mtd: try: DeleteWorkspace(Workspace=wksp) - except (StandardError, Warning): + except (Exception, Warning): # we're only deleting to save memory, if the workspace really won't delete leave it pass @@ -1179,7 +1180,7 @@ def FindBeamCentre(rlow, rupp, MaxIter=10, xstart=None, ystart=None, tolerance=1 graph_handle = mantidplot.plotSpectrum(centre.QUADS, 0) graph_handle.activeLayer().setTitle( beam_center_logger.get_status_message(it, COORD1NEW, COORD2NEW, resCoord1, resCoord2)) - except (StandardError, Warning): + except (Exception, Warning): # if plotting is not available it probably means we are running outside a GUI, in which case # do everything but don't plot pass @@ -1264,7 +1265,7 @@ def check_if_event_workspace(file_name): @returns true if the workspace is an event workspace otherwise false ''' result = su.can_load_as_event_workspace(filename=file_name) - print result + print(result) return result @@ -1287,14 +1288,14 @@ def check_time_shifts_for_added_event_files(number_of_files, time_shifts=''): except ValueError: message = ('Error: Elements of the time shift list cannot be ' + 'converted to a numeric value, e.g ' + time_shift_element) - print message + print(message) return message if number_of_files - 1 != len(time_shift_container): message = ('Error: Expected N-1 time shifts for N files, but read ' + str(len(time_shift_container)) + ' time shifts for ' + str(number_of_files) + ' files.') - print message + print(message) return message @@ -1492,7 +1493,7 @@ def get_q_resolution_moderator(): val = ReductionSingleton().to_Q.get_q_resolution_moderator() if val is None: val = '' - print str(val) + print(str(val)) return val @@ -1503,7 +1504,7 @@ def set_q_resolution_moderator(file_name): ''' try: ReductionSingleton().to_Q.set_q_resolution_moderator(file_name) - except RuntimeError, details: + except RuntimeError as details: sanslog.error("The specified moderator file could not be found. Please specify a file" "which exists in the search directories. See details: %s" % str(details)) @@ -1515,7 +1516,7 @@ def get_q_resultution_use(): @returns true if the resolution option is being used, else false ''' val = ReductionSingleton().to_Q.get_use_q_resolution() - print str(val) + print(str(val)) return val @@ -1544,7 +1545,7 @@ def get_q_resolution_collimation_length(): pass else: sanslog.warning('Warning: Could not convert %s to float.' % msg) - print str(element) + print(str(element)) return element @@ -1570,7 +1571,7 @@ def get_q_resolution_delta_r(): @returns the delta r in mm ''' val = get_q_resolution_float(ReductionSingleton().to_Q.get_q_resolution_delta_r, "DeltaR") - print str(val) + print(str(val)) return val @@ -1589,7 +1590,7 @@ def get_q_resolution_a1(): @returns the diameter for the first aperature in mm ''' val = get_q_resolution_float(ReductionSingleton().to_Q.get_q_resolution_a1, "A1") - print str(val) + print(str(val)) return val @@ -1608,7 +1609,7 @@ def get_q_resolution_a2(): @returns the diameter for the second aperature in mm ''' val = get_q_resolution_float(ReductionSingleton().to_Q.get_q_resolution_a2, "A2") - print str(val) + print(str(val)) return val @@ -1627,7 +1628,7 @@ def get_q_resolution_h1(): @returns the first height in mm ''' val = get_q_resolution_float(ReductionSingleton().to_Q.get_q_resolution_h1, "H1") - print str(val) + print(str(val)) return val @@ -1646,7 +1647,7 @@ def get_q_resolution_h2(): @returns the second height in mm ''' val = get_q_resolution_float(ReductionSingleton().to_Q.get_q_resolution_h2, "H2") - print str(val) + print(str(val)) return val @@ -1665,7 +1666,7 @@ def get_q_resolution_w1(): @returns the first width in mm ''' val = get_q_resolution_float(ReductionSingleton().to_Q.get_q_resolution_w1, "W1") - print str(val) + print(str(val)) return val @@ -1684,7 +1685,7 @@ def get_q_resolution_w2(): @returns the second width in mm ''' val = get_q_resolution_float(ReductionSingleton().to_Q.get_q_resolution_w2, "W2") - print str(val) + print(str(val)) return val @@ -1747,7 +1748,7 @@ def are_settings_consistent(): ''' try: ReductionSingleton().perform_consistency_check() - except RuntimeError, details: + except RuntimeError as details: sanslog.error("There was an inconsistency issue with your settings. See details: %s" % str(details)) raise RuntimeError("Please fix the following inconsistencies: %s" % str(details)) @@ -1761,7 +1762,7 @@ def is_current_workspace_an_angle_workspace(): is_angle = False try: is_angle = is_workspace_which_requires_angle(reducer=ReductionSingleton()) - except (StopIteration, StandardError, Warning): + except (StopIteration, Exception, Warning): is_angle = False return is_angle @@ -1803,7 +1804,7 @@ def has_user_file_valid_extension(file_name): @returns true if it is valid else false ''' is_valid = su.is_valid_user_file_extension(file_name) - print str(is_valid) + print(str(is_valid)) return is_valid @@ -1815,7 +1816,7 @@ def get_current_idf_path_in_reducer(): ''' idf_path_reducer = ReductionSingleton().get_idf_file_path() idf_path_reducer = os.path.normpath(idf_path_reducer) - print str(idf_path_reducer) + print(str(idf_path_reducer)) return idf_path_reducer @@ -1894,7 +1895,7 @@ def get_background_correction(is_time, is_mon, component): value = convert_from_int_list_to_string(setting.mon_numbers) else: pass - print str(value) + print(str(value)) return value @@ -1957,15 +1958,15 @@ def SetFrontEfficiencyFile(filename): @deprecated def displayUserFile(): - print '-- Mask file defaults --' - print ReductionSingleton().to_wavlen - print ReductionSingleton().Q_string() + print('-- Mask file defaults --') + print(ReductionSingleton().to_wavlen) + print(ReductionSingleton().Q_string()) # print correction_files() - print ' direct beam file rear:', - print ReductionSingleton().instrument.detector_file('rear') - print ' direct beam file front:', - print ReductionSingleton().instrument.detector_file('front') - print ReductionSingleton().mask + print(' direct beam file rear:', end=' ') + print(ReductionSingleton().instrument.detector_file('rear')) + print(' direct beam file front:', end=' ') + print(ReductionSingleton().instrument.detector_file('front')) + print(ReductionSingleton().mask) @deprecated @@ -1976,8 +1977,8 @@ def displayMaskFile(): @deprecated def displayGeometry(): [x, y] = ReductionSingleton().get_beam_center() - print 'Beam centre: [' + str(x) + ',' + str(y) + ']' - print ReductionSingleton().get_sample().geometry + print('Beam centre: [' + str(x) + ',' + str(y) + ']') + print(ReductionSingleton().get_sample().geometry) @deprecated diff --git a/scripts/SANS/SANSBatchMode.py b/scripts/SANS/SANSBatchMode.py index 7d6f643ac973fc3c21a3ce398051416e04cfc81e..e04be8e948dcb2285fff3ff13167ffae4a204e2a 100644 --- a/scripts/SANS/SANSBatchMode.py +++ b/scripts/SANS/SANSBatchMode.py @@ -1,4 +1,4 @@ -#pylint: disable=invalid-name +#pylint: disable=invalid-name # # SANSBatchMode.py # @@ -30,6 +30,7 @@ # The save directory must currently be specified in the Mantid.user.properties file #Make the reduction module available +from __future__ import (absolute_import, division, print_function) from ISISCommandInterface import * import SANSUtility as su from mantid.simpleapi import * @@ -48,7 +49,7 @@ if sys.version_info[0] == 2 and sys.version_info[1] == 6: import types def _deepcopy_method(x, memo): - return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class) + return type(x)(x.__func__, copy.deepcopy(x.__self__, memo), x.__self__.__class__) copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method ################################################################################ @@ -216,15 +217,15 @@ def BatchReduce(filename, format, plotresults=False, saveAlgs={'SaveRKH':'txt'}, # DefaultTrans or CalcTrans: reduced = WavRangeReduction(combineDet=combineDet, out_fit_settings=scale_shift) - except SkipEntry, reason: + except SkipEntry as reason: #this means that a load step failed, the warning and the fact that the results aren't there is enough for the user issueWarning(str(reason)+ ', skipping entry') continue - except SkipReduction, reason: + except SkipReduction as reason: #this means that a load step failed, the warning and the fact that the results aren't there is enough for the user issueWarning(str(reason)+ ', skipping reduction') continue - except ValueError, reason: + except ValueError as reason: issueWarning('Cannot load file :'+str(reason)) #when we are all up to Python 2.5 replace the duplicated code below with one finally: delete_workspaces(raw_workspaces) @@ -287,7 +288,7 @@ def BatchReduce(filename, format, plotresults=False, saveAlgs={'SaveRKH':'txt'}, # else we map it to itself. save_names_dict = get_mapped_workspaces(save_names, save_as_zero_error_free) - for algor in saveAlgs.keys(): + for algor in list(saveAlgs.keys()): for workspace_name in save_names: #add the file extension, important when saving different types of file so they don't over-write each other ext = saveAlgs[algor] diff --git a/scripts/SANS/SANSUserFileParser.py b/scripts/SANS/SANSUserFileParser.py index ac0b87ee447d08cbd348c80a8d043871d2914ad4..480c64d3d430e66a9c4cb963f72e5ff3854b2e62 100644 --- a/scripts/SANS/SANSUserFileParser.py +++ b/scripts/SANS/SANSUserFileParser.py @@ -1,4 +1,5 @@ -#pylint: disable=invalid-name +#pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) from collections import namedtuple import re diff --git a/scripts/SANS/SANSUtility.py b/scripts/SANS/SANSUtility.py index 85e1d15871189c3e0bd5cc8cf2cd1f34eb354111..7609aad8de83e3df7f5c108db32178d54641f7a7 100644 --- a/scripts/SANS/SANSUtility.py +++ b/scripts/SANS/SANSUtility.py @@ -1,9 +1,10 @@ -#pylint: disable=too-many-lines +#pylint: disable=too-many-lines #pylint: disable=invalid-name ######################################################### # This module contains utility functions common to the # SANS data reduction scripts ######################################################## +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.api import IEventWorkspace, MatrixWorkspace, WorkspaceGroup, FileLoaderRegistry from mantid.kernel import time_duration, DateAndTime @@ -11,7 +12,7 @@ import inspect import math import os import re -import types +from six import types, iteritems import numpy as np sanslog = Logger("SANS") @@ -43,7 +44,7 @@ def deprecated(obj): if inspect.isfunction(obj): obj_desc = "\"%s\" function" % obj.__name__ else: - obj_desc = "\"%s\" class" % obj.im_class.__name__ + obj_desc = "\"%s\" class" % obj.__self__.__class__.__name__ def print_warning_wrapper(*args, **kwargs): sanslog.warning("The %s has been marked as deprecated and may be " @@ -58,7 +59,7 @@ def deprecated(obj): # (by recursion). if inspect.isclass(obj): for name, fn in inspect.getmembers(obj): - if isinstance(fn, types.UnboundMethodType): + if isinstance(fn, types.MethodType): setattr(obj, name, deprecated(fn)) return obj @@ -913,7 +914,7 @@ class PlusWorkspaces(object): def _get_workspace(self, workspace): if isinstance(workspace, MatrixWorkspace): return workspace - elif isinstance(workspace, basestring) and mtd.doesExist(workspace): + elif isinstance(workspace, str) and mtd.doesExist(workspace): return mtd[workspace] @@ -978,7 +979,7 @@ class OverlayWorkspaces(object): def _get_workspace(self, workspace): if isinstance(workspace, MatrixWorkspace): return workspace - elif isinstance(workspace, basestring) and mtd.doesExist(workspace): + elif isinstance(workspace, str) and mtd.doesExist(workspace): return mtd[workspace] #pylint: disable=too-few-public-methods @@ -1207,10 +1208,10 @@ class CummulativeTimeSeriesPropertyAdder(object): values.extend(values_lhs) values.extend(values_rhs) - zipped = zip(times, values) + zipped = list(zip(times, values)) # We sort via the times zipped.sort(key = lambda z : z[0]) - unzipped = zip(*zipped) + unzipped = list(zip(*zipped)) return unzipped[0], unzipped[1] def _shift_time_series(self, time_series): @@ -1413,7 +1414,7 @@ def can_load_as_event_workspace(filename): # We only check the first entry in the root # and check for event_eventworkspace in the next level nxs_file =nxs.open(filename, 'r') - rootKeys = nxs_file.getentries().keys() + rootKeys = list(nxs_file.getentries().keys()) nxs_file.opengroup(rootKeys[0]) nxs_file.opengroup('event_workspace') is_event_workspace = True @@ -1643,7 +1644,7 @@ class MeasurementTimeFromNexusFileExtractor(object): nxs_file = nxs.open(filename_full, 'r') # pylint: disable=bare-except try: - rootKeys = nxs_file.getentries().keys() + rootKeys = list(nxs_file.getentries().keys()) nxs_file.opengroup(rootKeys[0]) is_processed_file = self._check_if_processed_nexus_file(nxs_file) if is_processed_file: @@ -1765,7 +1766,7 @@ def createUnmanagedAlgorithm(name, **kwargs): alg = AlgorithmManager.createUnmanaged(name) alg.initialize() alg.setChild(True) - for key, value in kwargs.iteritems(): + for key, value in iteritems(kwargs): alg.setProperty(key, value) return alg @@ -1916,7 +1917,7 @@ def ConvertToSpecList(maskstring, firstspec, dimension, orientation): ydim=abs(upp2-low2)+1 speclist += spectrumBlock(firstspec,low2, low,nstrips, dimension, dimension,orientation)+ ',' else: - print "error in mask, ignored: " + x + print("error in mask, ignored: " + x) elif '>' in x: pieces = x.split('>') low = int(pieces[0].lstrip('hvs')) diff --git a/scripts/SANS/SANSadd2.py b/scripts/SANS/SANSadd2.py index 9244af582f57ab58554ed5a3fc3bf923dd2c4ee6..b3867b1332b99789c9dc9273f327d3a2716b66db 100644 --- a/scripts/SANS/SANSadd2.py +++ b/scripts/SANS/SANSadd2.py @@ -1,4 +1,5 @@ -#pylint: disable=invalid-name +#pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) import os from mantid.simpleapi import * from mantid.kernel import Logger @@ -55,7 +56,7 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add' is_not_allowed_instrument = inst.upper() != 'SANS2D' and inst.upper() != 'LARMOR' if is_not_allowed_instrument and isFirstDataSetEvent: error = 'Adding event data not supported for ' + inst + ' for now' - print error + print(error) logger.notice(error) for workspaceName in ('AddFilesSumTempory','AddFilesSumTempory_monitors'): if workspaceName in mtd: @@ -69,7 +70,7 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add' if isDataSetEvent != isFirstDataSetEvent: error = 'Datasets added must be either ALL histogram data or ALL event data' - print error + print(error) logger.notice(error) for workspaceName in ('AddFilesSumTempory','AddFilesNewTempory'): if workspaceName in mtd: @@ -88,14 +89,14 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add' counter_run +=1 except ValueError as e: error = 'Error opening file ' + userEntry+': ' + str(e) - print error + print(error) logger.notice(error) if 'AddFilesSumTempory' in mtd : DeleteWorkspace('AddFilesSumTempory') return "" except Exception as e: error = 'Error finding files: ' + str(e) - print error + print(error) logger.notice(error) for workspaceName in ('AddFilesSumTempory','AddFilesNewTempory'): if workspaceName in mtd: @@ -321,7 +322,7 @@ def _copyLog(lastPath, logFile, pathout): logger.notice("Could not find log file %s" % logFile) except Exception: error = 'Error copying log file ' + logFile + ' to directory ' + pathout+'\n' - print error + print(error) logger.notice(error) if __name__ == '__main__': diff --git a/scripts/SANS/centre_finder.py b/scripts/SANS/centre_finder.py index c22bb431d8d6a019fb732e1ac35c731a127c26cf..770276ef046c2d3184332928a20c388404015b08 100644 --- a/scripts/SANS/centre_finder.py +++ b/scripts/SANS/centre_finder.py @@ -1,4 +1,5 @@ #pylint: disable=invalid-name +from __future__ import (absolute_import, division, print_function) from isis_reduction_steps import StripEndNans from isis_instrument import LARMOR from mantid.simpleapi import * diff --git a/scripts/SANS/isis_instrument.py b/scripts/SANS/isis_instrument.py index 0af2527313a771a7470b512e6676b42b700a71a4..d2cdde2b12fe7e174f43cd5b66a2bdfdb1ec8a9a 100644 --- a/scripts/SANS/isis_instrument.py +++ b/scripts/SANS/isis_instrument.py @@ -1,4 +1,5 @@ -# pylint: disable=too-many-lines, invalid-name, bare-except, too-many-instance-attributes +# pylint: disable=too-many-lines, invalid-name, bare-except, too-many-instance-attributes +from __future__ import (absolute_import, division, print_function) import math import os import re @@ -10,6 +11,7 @@ from mantid.kernel import Logger from mantid.kernel import V3D import SANSUtility as su from math import copysign +from six import iteritems sanslog = Logger("SANS") @@ -590,7 +592,7 @@ class ISISInstrument(BaseInstrument): return self.DETECTORS['high-angle'] def getDetector(self, requested): - for _n, detect in self.DETECTORS.iteritems(): + for _n, detect in iteritems(self.DETECTORS): if detect.isAlias(requested): return detect sanslog.notice("getDetector: Detector " + requested + "not found") @@ -724,7 +726,7 @@ class ISISInstrument(BaseInstrument): MoveInstrumentComponent(Workspace=ws, ComponentName='some-sample-holder', Z=self.SAMPLE_Z_CORR, RelativePosition=True) - for i in self.monitor_zs.keys(): + for i in list(self.monitor_zs.keys()): # get the current location component = self.monitor_names[i] ws = mtd[str(ws)] @@ -915,7 +917,7 @@ class LOQ(ISISInstrument): if self.has_m4_monitor: self.monitor_names.update({self._m4_det_id: self._m4_monitor_name}) - elif self._m4_det_id in self.monitor_names.keys(): + elif self._m4_det_id in list(self.monitor_names.keys()): del self.monitor_names[self._m4_det_id] def move_components(self, ws, xbeam, ybeam): diff --git a/scripts/SANS/isis_reducer.py b/scripts/SANS/isis_reducer.py index 6358ed5f73c864887ef12924ae5b3b51e9f62b64..5e092dabbd0cda93c89d555fbc79d0b4276b1eac 100644 --- a/scripts/SANS/isis_reducer.py +++ b/scripts/SANS/isis_reducer.py @@ -1,4 +1,4 @@ -# pylint: disable=invalid-name, property-on-old-class, redefined-builtin, protected-access +# pylint: disable=invalid-name, property-on-old-class, redefined-builtin, protected-access """ ISIS-specific implementation of the SANS Reducer. @@ -6,6 +6,7 @@ understand what's happening and how best to fit it in the Reducer design. """ +from __future__ import (absolute_import, division, print_function) from reducer_singleton import Reducer import isis_reduction_steps import isis_instrument @@ -28,7 +29,7 @@ if sys.version_info[0] == 2 and sys.version_info[1] == 6: import types def _deepcopy_method(x, memo): - return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class) + return type(x)(x.__func__, copy.deepcopy(x.__self__, memo), x.__self__.__class__) copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method ################################################################################ @@ -84,7 +85,7 @@ class Sample(object): def get_monitor(self, index=None): try: _ws = mtd[self.loader.wksp_name + "_monitors"] - except (StandardError, Warning): + except (Exception, Warning): _ws = mtd[self.loader.wksp_name] if index is not None: @@ -507,10 +508,10 @@ class ISISReducer(Reducer): self.__transmission_sample = "" self.__transmission_can = "" - for role in self._temporys.keys(): + for role in list(self._temporys.keys()): try: DeleteWorkspace(Workspace=self._temporys[role]) - except (StandardError, Warning): + except (Exception, Warning): # if cleaning up isn't possible there is probably nothing we can do pass @@ -690,7 +691,7 @@ class ISISReducer(Reducer): try: if wk and wk in mtd: DeleteWorkspace(Workspace=wk) - except (StandardError, Warning): + except (Exception, Warning): # if the workspace can't be deleted this function does nothing pass @@ -714,7 +715,7 @@ class ISISReducer(Reducer): to_check = self._reduction_steps for element in to_check: element.run_consistency_check() - except RuntimeError, details: + except RuntimeError as details: if was_empty: self._reduction_steps = None raise RuntimeError(str(details)) diff --git a/scripts/SANS/isis_reduction_steps.py b/scripts/SANS/isis_reduction_steps.py index 0a71a96c5f40ccc051003da319da7713ebf9350e..104e50eb6e975d9fc2b0cd09672a8e60e1796bb0 100644 --- a/scripts/SANS/isis_reduction_steps.py +++ b/scripts/SANS/isis_reduction_steps.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines, too-many-branches, invalid-name, super-on-old-class, protected-access, +# pylint: disable=too-many-lines, too-many-branches, invalid-name, super-on-old-class, protected-access, # pylint: disable=too-few-public-methods,too-few-public-methods, too-many-arguments, too-many-instance-attributes """ This file defines what happens in each step in the data reduction, it's @@ -8,6 +8,7 @@ Most of this code is a copy-paste from SANSReduction.py, organized to be used with ReductionStep objects. The guts needs refactoring. """ +from __future__ import (absolute_import, division, print_function) import os import re import math @@ -44,7 +45,7 @@ def _issueWarning(msg): Prints a message to the log marked as warning @param msg: message to be issued """ - print msg + print(msg) sanslog.warning(msg) @@ -53,7 +54,7 @@ def _issueInfo(msg): Prints a message to the log @param msg: message to be issued """ - print msg + print(msg) sanslog.notice(msg) @@ -184,7 +185,7 @@ class LoadRun(object): if isinstance(outWs, IEventWorkspace): try: LoadNexusMonitors(self._data_file, OutputWorkspace=monitor_ws_name) - except ValueError, details: + except ValueError as details: sanslog.warning('The file does not contain monitors. \n' + 'The normalization might behave differently than you expect.\n' ' Further details: ' + str(details) + '\n') @@ -202,7 +203,7 @@ class LoadRun(object): try: last_algorithm = outWs.getHistory().lastAlgorithm() loader_name = last_algorithm.getProperty('LoaderName').value - except RuntimeError, details: + except RuntimeError as details: sanslog.warning( 'Tried to get a loader name. But it seems that there is no loader name. Further info: ' + str(details)) @@ -325,7 +326,7 @@ class LoadRun(object): else: # the spectrum_limits is not the default only for transmission data self._load(reducer.instrument, extra_options=spectrum_limits) - except RuntimeError, details: + except RuntimeError as details: sanslog.warning(str(details)) self._wksp_name = '' return @@ -858,7 +859,7 @@ class Mask_ISIS(ReductionStep): ydim = abs(upp2 - low2) + 1 speclist += detector.spectrum_block(low2, low, ydim, xdim) + ',' else: - print "error in mask, ignored: " + x + print("error in mask, ignored: " + x) elif '>' in x: # Commands: MASK Ssp1>Ssp2, MASK Hn1>Hn2 and MASK Vn1>Vn2 pieces = x.split('>') low = int(pieces[0].lstrip('hvs')) @@ -1181,7 +1182,7 @@ class LoadSample(LoadRun): raise RuntimeError('Unable to load SANS sample run, cannot continue.') if self.periods_in_file > 1: - self.entries = range(0, self.periods_in_file) + self.entries = list(range(0, self.periods_in_file)) # applies on_load_sample for all the workspaces (single or groupworkspace) num = 0 @@ -2665,7 +2666,7 @@ class ConvertToQISIS(ReductionStep): else: msg = "User file can't override previous gravity setting, do gravity correction remains " + str( self._use_gravity) - print msg + print(msg) sanslog.warning(msg) def get_extra_length(self): @@ -2686,7 +2687,7 @@ class ConvertToQISIS(ReductionStep): else: msg = ("User file can't override previous extra length setting for" + " gravity correction; extra length remains " + str(self._grav_extra_length)) - print msg + print(msg) sanslog.warning(msg) def execute(self, reducer, workspace): @@ -2793,7 +2794,7 @@ class ConvertToQISIS(ReductionStep): # Run a consistency check try: self.run_consistency_check() - except RuntimeError, details: + except RuntimeError as details: sanslog.warning("ConverToQISIS: There was something wrong with the Q Resolution" " settings. Running the reduction without the Q Resolution" " Setting. See details %s" % str(details)) @@ -3295,7 +3296,7 @@ class UserFile(ReductionStep): y_pos = float(values[1]) / YSF elif hab_str_pos > 0: values = upper_line[hab_str_pos + 4:].split() # remove the SET CENTRE/HAB - print ' convert values ', values + print(' convert values ', values) x_pos = float(values[0]) / XSF y_pos = float(values[1]) / YSF else: @@ -3303,7 +3304,7 @@ class UserFile(ReductionStep): x_pos = float(values[2]) / XSF y_pos = float(values[3]) / YSF if hab_str_pos > 0: - print 'Front values = ', x_pos, y_pos + print('Front values = ', x_pos, y_pos) reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos), 'front') else: reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos)) @@ -3749,7 +3750,7 @@ class UserFile(ReductionStep): # parse the words after 'TIME' as first the start time and then the end reducer.inst.set_TOFs(int(times[0]), int(times[1]), monitor) return '' - except Exception, reason: + except Exception as reason: # return a description of any problems and then continue to read the next line return str(reason) + ' on line: ' @@ -3784,7 +3785,7 @@ class UserFile(ReductionStep): reducer.inst.set_TOFs_for_ROI(int(times[0]), int(times[1])) return '' raise ValueError('Expected two times for BACK/TRANS') - except ValueError, reason: + except ValueError as reason: # return a description of any problems and then continue to read the next line return str(reason) + ' on line: ' diff --git a/scripts/SANS/reduction_settings.py b/scripts/SANS/reduction_settings.py index 3766b1a9ee7ee194fc1a6ff5e3e72199f282ba08..c75d22107a1707b90776ee9de536a499fbe5817b 100644 --- a/scripts/SANS/reduction_settings.py +++ b/scripts/SANS/reduction_settings.py @@ -62,6 +62,7 @@ between reduction steps. The benefits to this new method are as follows: passing settings to each other via PropertyManager objects. """ +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * diff --git a/scripts/test/CrystalFieldTest.py b/scripts/test/CrystalFieldTest.py index 2eab6cba3e0a3764c2577301f58aaf7bbf876bbe..cfb0e32e3ba5dc21fad3bacb5c347b88275982fa 100644 --- a/scripts/test/CrystalFieldTest.py +++ b/scripts/test/CrystalFieldTest.py @@ -1,5 +1,6 @@ """Test suite for the crystal field calculations in the Inelastic/CrystalField package """ +from __future__ import (absolute_import, division, print_function) import unittest import numpy as np @@ -23,22 +24,22 @@ class BackgroundTest(unittest.TestCase): from CrystalField import Background, Function b = Background(peak=Function('PseudoVoigt', Height=10, FWHM=1, Mixing=0.5), background=Function('LinearBackground', A0=1.0, A1=0.1)) * 3 - self.assertEquals(len(b), 3) + self.assertEqual(len(b), 3) self.assertTrue(isinstance(b[0], Background)) self.assertTrue(isinstance(b[1], Background)) self.assertTrue(isinstance(b[2], Background)) b[0].peak.param['Height'] = 31 b[1].peak.param['Height'] = 41 b[2].peak.param['Height'] = 51 - self.assertEquals(b[0].peak.param['Height'], 31) - self.assertEquals(b[1].peak.param['Height'], 41) - self.assertEquals(b[2].peak.param['Height'], 51) + self.assertEqual(b[0].peak.param['Height'], 31) + self.assertEqual(b[1].peak.param['Height'], 41) + self.assertEqual(b[2].peak.param['Height'], 51) b[0].background.param['A1'] = 3 b[1].background.param['A1'] = 4 b[2].background.param['A1'] = 5 - self.assertEquals(b[0].background.param['A1'], 3) - self.assertEquals(b[1].background.param['A1'], 4) - self.assertEquals(b[2].background.param['A1'], 5) + self.assertEqual(b[0].background.param['A1'], 3) + self.assertEqual(b[1].background.param['A1'], 4) + self.assertEqual(b[2].background.param['A1'], 5) class CrystalFieldTests(unittest.TestCase): @@ -137,7 +138,7 @@ class CrystalFieldTests(unittest.TestCase): cf = CrystalField('Ce', 'C2v', B20=0.035, B40=-0.012, B43=-0.027, B60=-0.00012, B63=0.0025, B66=0.0068, Temperature=44.0) pl = cf.getPeakList() - self.assertEquals(pl.shape, (2, 7)) + self.assertEqual(pl.shape, (2, 7)) self.assertAlmostEqual(pl[0, 0], 0.0, 10) self.assertAlmostEqual(pl[1, 0], 1.99118947*c_mbsr, 6) self.assertAlmostEqual(pl[0, 1], 3.85696607, 8) @@ -150,7 +151,7 @@ class CrystalFieldTests(unittest.TestCase): cf = CrystalField('Ce', 'C2v', B20=0.035, B40=-0.012, B43=-0.027, B60=-0.00012, B63=0.0025, B66=0.0068, Temperature=[44.0, 50.0]) pl1 = cf.getPeakList() - self.assertEquals(pl1.shape, (2, 7)) + self.assertEqual(pl1.shape, (2, 7)) self.assertAlmostEqual(pl1[0, 0], 0.0, 10) self.assertAlmostEqual(pl1[1, 0], 1.99118947*c_mbsr, 6) self.assertAlmostEqual(pl1[0, 1], 3.85696607, 8) @@ -159,7 +160,7 @@ class CrystalFieldTests(unittest.TestCase): self.assertAlmostEqual(pl1[1, 2], 0.37963778*c_mbsr, 6) pl2 = cf.getPeakList(1) - self.assertEquals(pl2.shape, (2, 7)) + self.assertEqual(pl2.shape, (2, 7)) self.assertAlmostEqual(pl2[0, 0], 0.0, 10) self.assertAlmostEqual(pl2[1, 0], 1.97812511*c_mbsr, 6) self.assertAlmostEqual(pl2[0, 1], 3.85696607, 8) @@ -174,8 +175,8 @@ class CrystalFieldTests(unittest.TestCase): pf.attr[0]['SomeAttr'] = 'Hello' pf.param[1]['Sigma'] = 2.1 pf.param[1]['Height'] = 100 - self.assertEquals(pf.paramString(), 'f0.SomeAttr=Hello,f0.Sigma=1.1,f1.Sigma=2.1,f1.Height=100') - self.assertEquals(pf.toString(), 'name=Gaussian,SomeAttr=Hello,Sigma=1.1;name=Gaussian,Sigma=2.1,Height=100') + self.assertEqual(pf.paramString(), 'f0.SomeAttr=Hello,f0.Sigma=1.1,f1.Height=100,f1.Sigma=2.1') + self.assertEqual(pf.toString(), 'name=Gaussian,SomeAttr=Hello,Sigma=1.1;name=Gaussian,Height=100,Sigma=2.1') def test_api_CrystalField_spectrum(self): from CrystalField import CrystalField @@ -440,18 +441,18 @@ class CrystalFieldFitTest(unittest.TestCase): s = origin.makeMultiSpectrumFunction() fun = FunctionFactory.createInitialized(s) - self.assertEquals(fun.getParameterValue('f0.f0.f0.Sigma'), 0.3) - self.assertEquals(fun.getParameterValue('f0.f0.f1.A0'), 1.0) - self.assertEquals(fun.getParameterValue('f1.f0.f0.Sigma'), 0.8) - self.assertEquals(fun.getParameterValue('f1.f0.f1.A0'), 1.1) + self.assertEqual(fun.getParameterValue('f0.f0.f0.Sigma'), 0.3) + self.assertEqual(fun.getParameterValue('f0.f0.f1.A0'), 1.0) + self.assertEqual(fun.getParameterValue('f1.f0.f0.Sigma'), 0.8) + self.assertEqual(fun.getParameterValue('f1.f0.f1.A0'), 1.1) - self.assertEquals(fun.getParameterValue('f0.f1.FWHM'), 1.11) - self.assertEquals(fun.getParameterValue('f0.f2.FWHM'), 1.1) - self.assertEquals(fun.getParameterValue('f0.f3.FWHM'), 1.1) + self.assertEqual(fun.getParameterValue('f0.f1.FWHM'), 1.11) + self.assertEqual(fun.getParameterValue('f0.f2.FWHM'), 1.1) + self.assertEqual(fun.getParameterValue('f0.f3.FWHM'), 1.1) - self.assertEquals(fun.getParameterValue('f1.f1.FWHM'), 0.9) - self.assertEquals(fun.getParameterValue('f1.f2.FWHM'), 1.12) - self.assertEquals(fun.getParameterValue('f1.f3.FWHM'), 0.9) + self.assertEqual(fun.getParameterValue('f1.f1.FWHM'), 0.9) + self.assertEqual(fun.getParameterValue('f1.f2.FWHM'), 1.12) + self.assertEqual(fun.getParameterValue('f1.f3.FWHM'), 0.9) cf = CrystalField('Ce', 'C2v', B20=0.37737, B22=3.9770, B40=-0.031787, B42=-0.11611, B44=-0.12544, Temperature=[44.0, 50], FWHM=[1.1, 0.9]) @@ -525,15 +526,15 @@ class CrystalFieldFitTest(unittest.TestCase): s = origin.makeMultiSpectrumFunction() fun = FunctionFactory.createInitialized(s) - self.assertEquals(fun.getParameterValue('f1.f0.A0'), 1.2) + self.assertEqual(fun.getParameterValue('f1.f0.A0'), 1.2) - self.assertEquals(fun.getParameterValue('f0.f1.FWHM'), 1.11) - self.assertEquals(fun.getParameterValue('f0.f2.FWHM'), 1.1) - self.assertEquals(fun.getParameterValue('f0.f3.FWHM'), 1.1) + self.assertEqual(fun.getParameterValue('f0.f1.FWHM'), 1.11) + self.assertEqual(fun.getParameterValue('f0.f2.FWHM'), 1.1) + self.assertEqual(fun.getParameterValue('f0.f3.FWHM'), 1.1) - self.assertEquals(fun.getParameterValue('f1.f1.FWHM'), 0.9) - self.assertEquals(fun.getParameterValue('f1.f2.FWHM'), 1.12) - self.assertEquals(fun.getParameterValue('f1.f3.FWHM'), 0.9) + self.assertEqual(fun.getParameterValue('f1.f1.FWHM'), 0.9) + self.assertEqual(fun.getParameterValue('f1.f2.FWHM'), 1.12) + self.assertEqual(fun.getParameterValue('f1.f3.FWHM'), 0.9) cf = CrystalField('Ce', 'C2v', B20=0.37737, B22=3.9770, B40=-0.031787, B42=-0.11611, B44=-0.12544, Temperature=[44.0, 50], FWHM=[1.1, 0.9]) @@ -566,16 +567,16 @@ class CrystalFieldFitTest(unittest.TestCase): s = origin.makeMultiSpectrumFunction() fun = FunctionFactory.createInitialized(s) - self.assertEquals(fun.getParameterValue('f0.f0.Sigma'), 0.3) - self.assertEquals(fun.getParameterValue('f1.f0.Sigma'), 0.8) + self.assertEqual(fun.getParameterValue('f0.f0.Sigma'), 0.3) + self.assertEqual(fun.getParameterValue('f1.f0.Sigma'), 0.8) - self.assertEquals(fun.getParameterValue('f0.f1.FWHM'), 1.11) - self.assertEquals(fun.getParameterValue('f0.f2.FWHM'), 1.1) - self.assertEquals(fun.getParameterValue('f0.f3.FWHM'), 1.1) + self.assertEqual(fun.getParameterValue('f0.f1.FWHM'), 1.11) + self.assertEqual(fun.getParameterValue('f0.f2.FWHM'), 1.1) + self.assertEqual(fun.getParameterValue('f0.f3.FWHM'), 1.1) - self.assertEquals(fun.getParameterValue('f1.f1.FWHM'), 0.9) - self.assertEquals(fun.getParameterValue('f1.f2.FWHM'), 1.12) - self.assertEquals(fun.getParameterValue('f1.f3.FWHM'), 0.9) + self.assertEqual(fun.getParameterValue('f1.f1.FWHM'), 0.9) + self.assertEqual(fun.getParameterValue('f1.f2.FWHM'), 1.12) + self.assertEqual(fun.getParameterValue('f1.f3.FWHM'), 0.9) cf = CrystalField('Ce', 'C2v', B20=0.37737, B22=3.9770, B40=-0.031787, B42=-0.11611, B44=-0.12544, Temperature=[44.0, 50], FWHM=[1.1, 0.9]) diff --git a/scripts/test/DirectEnergyConversionTest.py b/scripts/test/DirectEnergyConversionTest.py index 781aedfc6b8ef9c712663bdb63b42914899b7ff6..ff71ad1f51bfc75952daee22808f0272d6eff0b6 100644 --- a/scripts/test/DirectEnergyConversionTest.py +++ b/scripts/test/DirectEnergyConversionTest.py @@ -1,3 +1,4 @@ +from __future__ import (absolute_import, division, print_function) import os, sys from mantid.simpleapi import * from mantid import api diff --git a/scripts/test/DirectPropertyManagerTest.py b/scripts/test/DirectPropertyManagerTest.py index e78fc0d9f2a528592ea3d339d3154da8f2b9278b..dbbf632001d1985be63cac3a773bd2d7b429e81b 100644 --- a/scripts/test/DirectPropertyManagerTest.py +++ b/scripts/test/DirectPropertyManagerTest.py @@ -1,4 +1,5 @@ -import os +from __future__ import (absolute_import, division, print_function) +import os from mantid.simpleapi import * from mantid import api import unittest @@ -119,7 +120,7 @@ class DirectPropertyManagerTest(unittest.TestCase): propman.spectra_to_monitors_list = 35 self.assertTrue(isinstance(propman.spectra_to_monitors_list,list)) - self.assertEquals(35,propman.spectra_to_monitors_list[0]) + self.assertEqual(35,propman.spectra_to_monitors_list[0]) propman.spectra_to_monitors_list = None self.assertTrue(propman.spectra_to_monitors_list is None) @@ -129,15 +130,15 @@ class DirectPropertyManagerTest(unittest.TestCase): self.assertTrue(propman.spectra_to_monitors_list is None) propman.spectra_to_monitors_list = '467' - self.assertEquals(467,propman.spectra_to_monitors_list[0]) + self.assertEqual(467,propman.spectra_to_monitors_list[0]) propman.spectra_to_monitors_list = '467,444' - self.assertEquals(467,propman.spectra_to_monitors_list[0]) - self.assertEquals(444,propman.spectra_to_monitors_list[1]) + self.assertEqual(467,propman.spectra_to_monitors_list[0]) + self.assertEqual(444,propman.spectra_to_monitors_list[1]) propman.spectra_to_monitors_list = ['467','444'] - self.assertEquals(467,propman.spectra_to_monitors_list[0]) - self.assertEquals(444,propman.spectra_to_monitors_list[1]) + self.assertEqual(467,propman.spectra_to_monitors_list[0]) + self.assertEqual(444,propman.spectra_to_monitors_list[1]) prop_changed = propman.getChangedProperties() self.assertEqual(len(prop_changed),1) @@ -444,18 +445,18 @@ class DirectPropertyManagerTest(unittest.TestCase): propman = PropertyManager(instr) self.assertAlmostEqual(propman.TestParam1,3.5) - self.assertEquals(propman.TestParam2,"initial1") - self.assertEquals(propman.TestParam3,"initial2") + self.assertEqual(propman.TestParam2,"initial1") + self.assertEqual(propman.TestParam3,"initial2") propman.TestParam2 = "gui_changed1" - self.assertEquals(propman.TestParam2,"gui_changed1") + self.assertEqual(propman.TestParam2,"gui_changed1") SetInstrumentParameter(ws,ParameterName="TestParam2",Value="instr_changed1",ParameterType="String") SetInstrumentParameter(ws,ParameterName="TestParam3",Value="instr_changed2",ParameterType="String") self.assertAlmostEqual(propman.TestParam1,3.5) - self.assertEquals(propman.TestParam2,"gui_changed1") - self.assertEquals(propman.TestParam3,"initial2") + self.assertEqual(propman.TestParam2,"gui_changed1") + self.assertEqual(propman.TestParam3,"initial2") changes = propman.getChangedProperties() self.assertTrue('TestParam2' in changes) self.assertTrue(not('TestParam3' in changes)) @@ -465,8 +466,8 @@ class DirectPropertyManagerTest(unittest.TestCase): changes = propman.update_defaults_from_instrument(ws.getInstrument()) self.assertAlmostEqual(propman.TestParam1,3.5) - self.assertEquals(propman.TestParam2,"gui_changed1") - self.assertEquals(propman.TestParam3,"instr_changed2") + self.assertEqual(propman.TestParam2,"gui_changed1") + self.assertEqual(propman.TestParam3,"instr_changed2") self.assertTrue('TestParam2' in changes) self.assertTrue('TestParam3' in changes) @@ -514,7 +515,7 @@ class DirectPropertyManagerTest(unittest.TestCase): self.assertEqual(propman.ParaPara,'OtherVal2') self.assertEqual(propman.BaseParam2,'OtherVal2') - self.assertEquals(propman.BaseParam1,"OtherVal1") + self.assertEqual(propman.BaseParam1,"OtherVal1") def test_set_all_defaults_from_instrument(self) : ws = CreateSampleWorkspace(NumBanks=1, BankPixelWidth=4, NumEvents=10) @@ -796,7 +797,7 @@ class DirectPropertyManagerTest(unittest.TestCase): changed_prop = propman.update_defaults_from_instrument(ws.getInstrument()) - self.assertEqual(len(changed_prop),1) + self.assertEqual(len(changed_prop),3) bkgd_range = propman.bkgd_range self.assertAlmostEqual(bkgd_range[0],20) self.assertAlmostEqual(bkgd_range[1],40) @@ -1099,7 +1100,7 @@ class DirectPropertyManagerTest(unittest.TestCase): ok,fail_list = propman._check_file_properties() self.assertTrue(ok) if not ok: - print "fail prop list: ",fail_list + print("fail prop list: ",fail_list) api.AnalysisDataService.clear() diff --git a/scripts/test/DirectReductionHelpersTest.py b/scripts/test/DirectReductionHelpersTest.py index e612fc26089d6a7a4bbf1495dc61564731583cd7..0b975d9e5585d21f67bfbd865ba11d1da28c484c 100644 --- a/scripts/test/DirectReductionHelpersTest.py +++ b/scripts/test/DirectReductionHelpersTest.py @@ -1,4 +1,5 @@ -import os +from __future__ import (absolute_import, division, print_function) +import os from mantid.simpleapi import * from mantid import api import unittest diff --git a/scripts/test/ISISDirecInelasticConfigTest.py b/scripts/test/ISISDirecInelasticConfigTest.py index 259d12d606651629a4eba3972c8997fc97a0c089..caa9ee12fad5b769eb384f93bf538d0d409838b1 100644 --- a/scripts/test/ISISDirecInelasticConfigTest.py +++ b/scripts/test/ISISDirecInelasticConfigTest.py @@ -1,4 +1,5 @@ -import os +from __future__ import (absolute_import, division, print_function) +import os import sys import unittest import shutil @@ -23,10 +24,7 @@ class ISISDirectInelasticConfigTest(unittest.TestCase): self.rbnumber = "RB" + nrbnumber self.start_date= '20150503' self.userID = 'tuf666699' - self._set_up() return super(ISISDirectInelasticConfigTest, self).__init__(methodName) - def __del__(self): - self._tear_down() def get_save_dir(self): targetDir = config['defaultsave.directory'] @@ -51,7 +49,7 @@ class ISISDirectInelasticConfigTest(unittest.TestCase): fh.close() - def _set_up(self): + def setUp(self): # Create user's folder structure in default save directory. # the administrative script (not here) builds all this for real in /home targetDir = self.get_save_dir() @@ -98,7 +96,7 @@ class ISISDirectInelasticConfigTest(unittest.TestCase): return full_file - def _tear_down(self): + def tearDown(self): # Clean-up user's folder structure if os.path.exists(self.rbdir): shutil.rmtree(self.rbdir,ignore_errors=True) @@ -118,13 +116,13 @@ class ISISDirectInelasticConfigTest(unittest.TestCase): id = user._recent_dateID self.assertEqual(user._instrument[id],'MERLIN') self.assertEqual(user._cycle_IDs[id],('2015','1')) - self.assertEqual(user._start_dates[id],datetime.date(2015,05,03)) + self.assertEqual(user._start_dates[id],datetime.date(2015,5,3)) self.assertEqual(user._rb_dirs[id],self.rbdir) self.assertEqual(user.userID,self.userID) self.assertEqual(user.instrument,'MERLIN') self.assertEqual(user.cycleID,'2015_1') - self.assertEqual(user.start_date,datetime.date(2015,05,03)) + self.assertEqual(user.start_date,datetime.date(2015,5,3)) self.assertEqual(user.rb_dir,self.rbdir) @@ -152,7 +150,7 @@ class ISISDirectInelasticConfigTest(unittest.TestCase): self.assertEqual(len(user._instrument),2) self.assertEqual(user._recent_dateID,id) - self.assertEqual(user._start_dates['2000-01-12'],datetime.date(2000,01,12)) + self.assertEqual(user._start_dates['2000-01-12'],datetime.date(2000,1,12)) targetDir = self.get_save_dir() rbdir = os.path.join(self.userRootDir,'RB1999666') diff --git a/scripts/test/ReductionWrapperTest.py b/scripts/test/ReductionWrapperTest.py index 391f8115bf8256ab66f264ef9415b2e2757a7eb7..269a4d79c461779e5d4245e1669ccde731dae72b 100644 --- a/scripts/test/ReductionWrapperTest.py +++ b/scripts/test/ReductionWrapperTest.py @@ -1,4 +1,5 @@ -import os,sys +from __future__ import (absolute_import, division, print_function) +import os,sys from mantid.simpleapi import * from mantid import api,config @@ -9,6 +10,7 @@ import MariReduction as mr # import unittest +import imp class test_helper(ReductionWrapper): def __init__(self,web_var=None): @@ -102,7 +104,7 @@ class ReductionWrapperTest(unittest.TestCase): # see what have changed and what have changed as advanced properties. all_changed_prop = red.reducer.prop_man.getChangedProperties() - self.assertEqual(set(main_prop.keys()+adv_prop.keys()),all_changed_prop) + self.assertEqual(set(list(main_prop.keys())+list(adv_prop.keys())),all_changed_prop) test_dir = config['defaultsave.directory'] file = os.path.join(test_dir,'reduce_vars.py') @@ -126,7 +128,7 @@ class ReductionWrapperTest(unittest.TestCase): self.assertEqual(rv.advanced_vars,adv_prop) self.assertTrue(hasattr(rv,'variable_help')) - reload(mr) + imp.reload(mr) # tis will run MARI reduction, which probably not work from unit tests # will move this to system tests @@ -179,8 +181,8 @@ class ReductionWrapperTest(unittest.TestCase): red._wvs.advanced_vars={} ok,level,errors = red.validate_settings() if not ok: - print "Errors found at level",level - print errors + print("Errors found at level",level) + print(errors) self.assertTrue(ok) self.assertEqual(level,0) diff --git a/scripts/test/ReflectometryQuickAuxiliaryTest.py b/scripts/test/ReflectometryQuickAuxiliaryTest.py index e3974346dfd68c731afd6fbb55ef5a792cdf07f7..977f4333c4f37c14bb665d4e5d12acacf185c122 100644 --- a/scripts/test/ReflectometryQuickAuxiliaryTest.py +++ b/scripts/test/ReflectometryQuickAuxiliaryTest.py @@ -1,3 +1,4 @@ +from __future__ import (absolute_import, division, print_function) import unittest import numpy from mantid.simpleapi import * @@ -9,14 +10,15 @@ class ReflectometryQuickAuxiliaryTest(unittest.TestCase): def __init__(self, methodName='runTest'): - super(ReflectometryQuickAuxiliaryTest, self).__init__(methodName) self.__wsName = "TestWorkspace" + super(ReflectometryQuickAuxiliaryTest, self).__init__(methodName) + + def setUp(self): LoadISISNexus(Filename='POLREF00004699', OutputWorkspace=self.__wsName) - def __del__(self): + def tearDown(self): DeleteWorkspace(mtd[self.__wsName]) - def test_cleanup(self): numObjectsOriginal = len(mtd.getObjectNames()) todump =CreateSingleValuedWorkspace(OutputWorkspace='_toremove', DataValue=1, ErrorValue=1) @@ -36,11 +38,11 @@ class ReflectometryQuickAuxiliaryTest(unittest.TestCase): # Test with group workspace as input instrument = quick.groupGet(self.__wsName, 'inst') - self.assertEquals(expectedInstrument, instrument.getName(), "Did not fetch the instrument from ws group") + self.assertEqual(expectedInstrument, instrument.getName(), "Did not fetch the instrument from ws group") # Test with single workspace as input instrument = quick.groupGet(mtd[self.__wsName][0].name(), 'inst') - self.assertEquals(expectedInstrument, instrument.getName(), "Did not fetch the instrument from ws") + self.assertEqual(expectedInstrument, instrument.getName(), "Did not fetch the instrument from ws") def test_groupGet_histogram_count(self): @@ -48,11 +50,11 @@ class ReflectometryQuickAuxiliaryTest(unittest.TestCase): # Test with group workspace as input nHistograms = quick.groupGet(self.__wsName, 'wksp') - self.assertEquals(expectedNHistograms, nHistograms, "Did not fetch the n histograms from ws group") + self.assertEqual(expectedNHistograms, nHistograms, "Did not fetch the n histograms from ws group") # Test with single workspace as input nHistograms = quick.groupGet(mtd[self.__wsName][0].name(), 'wksp') - self.assertEquals(expectedNHistograms, nHistograms, "Did not fetch the n histograms from ws") + self.assertEqual(expectedNHistograms, nHistograms, "Did not fetch the n histograms from ws") def test_groupGet_log_single_value(self): @@ -61,11 +63,11 @@ class ReflectometryQuickAuxiliaryTest(unittest.TestCase): # Test with group workspace as input nPeriods = quick.groupGet(self.__wsName, 'samp', 'nperiods') - self.assertEquals(expectedNPeriods, nPeriods, "Did not fetch the number of periods from ws group") + self.assertEqual(expectedNPeriods, nPeriods, "Did not fetch the number of periods from ws group") # Test with single workspace as input nPeriods = quick.groupGet(mtd[self.__wsName][0].name(), 'samp', 'nperiods') - self.assertEquals(expectedNPeriods, nPeriods, "Did not fetch the number of periods from ws") + self.assertEqual(expectedNPeriods, nPeriods, "Did not fetch the number of periods from ws") def test_groupGet_multi_value_log(self): @@ -74,19 +76,19 @@ class ReflectometryQuickAuxiliaryTest(unittest.TestCase): # Test with group workspace as input stheta = quick.groupGet(self.__wsName, 'samp', 'stheta') - self.assertEquals(expectedStartTheta, round(float(stheta), 4)) + self.assertEqual(expectedStartTheta, round(float(stheta), 4)) # Test with single workspace as input stheta = quick.groupGet(mtd[self.__wsName][0].name(), 'samp', 'stheta') - self.assertEquals(expectedStartTheta, round(float(stheta), 4)) + self.assertEqual(expectedStartTheta, round(float(stheta), 4)) def test_groupGet_unknown_log_error_code(self): errorCode = 0 # Test with group workspace as input - self.assertEquals(errorCode, quick.groupGet(self.__wsName, 'samp','MADE-UP-LOG-NAME')) + self.assertEqual(errorCode, quick.groupGet(self.__wsName, 'samp','MADE-UP-LOG-NAME')) # Test with group workspace as input - self.assertEquals(errorCode, quick.groupGet(mtd[self.__wsName][0].name(), 'samp','MADE-UP-LOG-NAME')) + self.assertEqual(errorCode, quick.groupGet(mtd[self.__wsName][0].name(), 'samp','MADE-UP-LOG-NAME')) def test_exponential_correction_strategy(self): test_ws = CreateWorkspace(UnitX="TOF", DataX=[0,1,2,3], DataY=[1,1,1], NSpec=1) diff --git a/scripts/test/RunDescriptorTest.py b/scripts/test/RunDescriptorTest.py index 04ff7b1ba9ab844092beb210a5cad7990f8c1e36..80f4449d19316aaab9bbd1e8e19241fcaed0af65 100644 --- a/scripts/test/RunDescriptorTest.py +++ b/scripts/test/RunDescriptorTest.py @@ -1,4 +1,5 @@ -import os,sys,inspect +from __future__ import (absolute_import, division, print_function) +import os,sys,inspect from mantid.simpleapi import * from mantid import api import unittest diff --git a/scripts/test/SANSBatchModeTest.py b/scripts/test/SANSBatchModeTest.py index 3279c62071ad0759f2a9652fb1be272af7cd9411..ee2af6f8960622ce928cf96f915ab8114093499d 100644 --- a/scripts/test/SANSBatchModeTest.py +++ b/scripts/test/SANSBatchModeTest.py @@ -1,4 +1,5 @@ +from __future__ import (absolute_import, division, print_function) import unittest import re # Need to import mantid before we import SANSUtility diff --git a/scripts/test/SANSCentreFinderTest.py b/scripts/test/SANSCentreFinderTest.py index 955269e543e76db6e80caa6662490bc25ef45188..e60fc514a26c04de72c2b847f4989e398bf184e6 100644 --- a/scripts/test/SANSCentreFinderTest.py +++ b/scripts/test/SANSCentreFinderTest.py @@ -1,3 +1,4 @@ +from __future__ import (absolute_import, division, print_function) import unittest import mantid from mantid.simpleapi import * diff --git a/scripts/test/SANSCommandInterfaceTest.py b/scripts/test/SANSCommandInterfaceTest.py index 9da01269d4dccaa9111ff11e7e1de137eff12a80..fdf744afee5bf6ce4aa59c9bd1aeb5c185b3f21b 100644 --- a/scripts/test/SANSCommandInterfaceTest.py +++ b/scripts/test/SANSCommandInterfaceTest.py @@ -1,4 +1,5 @@ -import unittest +from __future__ import (absolute_import, division, print_function) +import unittest import mantid import os import isis_instrument as instruments @@ -404,11 +405,11 @@ class SANSCommandInterfaceGetAndSetBackgroundCorrectionSettings(unittest.TestCas def _do_test_correct_setting(self, run_number, is_time, is_mon, is_mean, mon_numbers): # Assert that settings were set setting = ReductionSingleton().get_dark_run_setting(is_time, is_mon) - self.assertEquals(setting.run_number, run_number) - self.assertEquals(setting.time, is_time) - self.assertEquals(setting.mean, is_mean) - self.assertEquals(setting.mon, is_mon) - self.assertEquals(setting.mon_numbers, mon_numbers) + self.assertEqual(setting.run_number, run_number) + self.assertEqual(setting.time, is_time) + self.assertEqual(setting.mean, is_mean) + self.assertEqual(setting.mon, is_mon) + self.assertEqual(setting.mon_numbers, mon_numbers) # Assert that other settings are None. Hence set up all combinations and remove the one which # has been set up earlier diff --git a/scripts/test/SANSDarkRunCorrectionTest.py b/scripts/test/SANSDarkRunCorrectionTest.py index 1232f70927bc2fd4cd1cd56495c2510906609035..a39c6594cded4eb7cb16b95fb01669b4c10f6baa 100644 --- a/scripts/test/SANSDarkRunCorrectionTest.py +++ b/scripts/test/SANSDarkRunCorrectionTest.py @@ -1,4 +1,4 @@ -import unittest +import unittest import mantid from mantid.simpleapi import * from mantid.kernel import DateAndTime diff --git a/scripts/test/SANSIsisInstrumentTest.py b/scripts/test/SANSIsisInstrumentTest.py index 62c7f9cb1fd96537476f9453faa490e70318a8ad..f8798b32dd0bd4c234e25e59c56723bf64298ab0 100644 --- a/scripts/test/SANSIsisInstrumentTest.py +++ b/scripts/test/SANSIsisInstrumentTest.py @@ -1,3 +1,4 @@ +from __future__ import (absolute_import, division, print_function) import unittest import mantid from mantid.simpleapi import * diff --git a/scripts/test/SANSReductionStepsUserFileTest.py b/scripts/test/SANSReductionStepsUserFileTest.py index fb2139936a2e901c8003725f5bcf30d6c0ab3e85..eeb3d709beec5499ad20090cc439986200259fba 100644 --- a/scripts/test/SANSReductionStepsUserFileTest.py +++ b/scripts/test/SANSReductionStepsUserFileTest.py @@ -1,4 +1,5 @@ -import unittest +from __future__ import (absolute_import, division, print_function) +import unittest import mantid import isis_instrument as instruments import ISISCommandInterface as command_iface diff --git a/scripts/test/SANSUserFileParserTest.py b/scripts/test/SANSUserFileParserTest.py index 41274e3bed97d9a58fcfcda12f92205f01c293c3..53133902969f4763ea5705177e3ba773392e9d25 100644 --- a/scripts/test/SANSUserFileParserTest.py +++ b/scripts/test/SANSUserFileParserTest.py @@ -1,4 +1,4 @@ -import unittest +import unittest import mantid import SANSUserFileParser as UserFileParser diff --git a/scripts/test/SANSUtilityTest.py b/scripts/test/SANSUtilityTest.py index aca613d0689b815de01eed95270fc8280373fa75..184d162ca207ae7ebca4fede51ca18adb25dd912 100644 --- a/scripts/test/SANSUtilityTest.py +++ b/scripts/test/SANSUtilityTest.py @@ -1,4 +1,5 @@ - + +from __future__ import (absolute_import, division, print_function) import unittest # Need to import mantid before we import SANSUtility import mantid @@ -168,15 +169,15 @@ class SANSUtilityTest(unittest.TestCase): # workspace in the ADS, and NOTHING else? self.assertTrue("result" in mtd) self.assertTrue("ws" in mtd) - self.assertEquals(2, len(mtd)) + self.assertEqual(2, len(mtd)) - self.assertEquals(result.getNumberHistograms(), len(det_ids)) - self.assertEquals(result.getDetector(0).getID(), 100) - self.assertEquals(result.getDetector(1).getID(), 102) - self.assertEquals(result.getDetector(2).getID(), 104) + self.assertEqual(result.getNumberHistograms(), len(det_ids)) + self.assertEqual(result.getDetector(0).getID(), 100) + self.assertEqual(result.getDetector(1).getID(), 102) + self.assertEqual(result.getDetector(2).getID(), 104) ws = CreateSampleWorkspace("Histogram", "Multiple Peaks") - det_ids = range(100, 299, 2) + det_ids = list(range(100, 299, 2)) result = su.extract_spectra(ws, det_ids, "result") def test_get_masked_det_ids(self): @@ -189,13 +190,13 @@ class SANSUtilityTest(unittest.TestCase): self.assertTrue(100 in masked_det_ids) self.assertTrue(102 in masked_det_ids) self.assertTrue(104 in masked_det_ids) - self.assertEquals(len(masked_det_ids), 3) + self.assertEqual(len(masked_det_ids), 3) def test_merge_to_ranges(self): - self.assertEquals([[1, 4]], su._merge_to_ranges([1, 2, 3, 4])) - self.assertEquals([[1, 3], [5, 7]], su._merge_to_ranges([1, 2, 3, 5, 6, 7])) - self.assertEquals([[1, 3], [5, 5], [7, 9]], su._merge_to_ranges([1, 2, 3, 5, 7, 8, 9])) - self.assertEquals([[1, 1]], su._merge_to_ranges([1])) + self.assertEqual([[1, 4]], su._merge_to_ranges([1, 2, 3, 4])) + self.assertEqual([[1, 3], [5, 7]], su._merge_to_ranges([1, 2, 3, 5, 6, 7])) + self.assertEqual([[1, 3], [5, 5], [7, 9]], su._merge_to_ranges([1, 2, 3, 5, 7, 8, 9])) + self.assertEqual([[1, 1]], su._merge_to_ranges([1])) class TestBundleAddedEventDataFilesToGroupWorkspaceFile(unittest.TestCase): def _prepare_workspaces(self, names): @@ -671,7 +672,7 @@ class TestZeroErrorFreeWorkspace(unittest.TestCase): message, complete = su.create_zero_error_free_workspace(input_workspace_name = ws_name, output_workspace_name = ws_clone_name) # Assert message.strip() - print message + print(message) # self.assertTrue(not message) #self.assertTrue(complete) self.assertTrue(mtd[ws_name] != mtd[ws_clone_name]) @@ -1234,7 +1235,7 @@ class TestCorrectingCummulativeSampleLogs(unittest.TestCase): self.assertTrue(larger_or_equal) def _check_that_values_of_series_are_the_same(self, series1, series2): - zipped = zip(series1, series2) + zipped = list(zip(series1, series2)) areEqual = True for e1, e2 in zipped: isEqual = e1 == e2 diff --git a/scripts/test/SansIsisGuiSettings.py b/scripts/test/SansIsisGuiSettings.py index 1adf12e286f600d439bf87c5ff93c4ae1bfe5d59..16807c8c5fd5033278148194e58e69b0dfe522fe 100644 --- a/scripts/test/SansIsisGuiSettings.py +++ b/scripts/test/SansIsisGuiSettings.py @@ -1,3 +1,4 @@ +from __future__ import (absolute_import, division, print_function) import unittest from mantid.simpleapi import * import ISISCommandInterface as i @@ -132,7 +133,7 @@ class Sans2DIsisGuiSettings(unittest.TestCase): ('Linear',2.5,13.,'CAN')] for option in options: - print 'Applying option ', str(option) + print('Applying option ', str(option)) i.TransFit(mode=option[0], lambdamin=option[1], lambdamax=option[2], selector=option[3]) checkFitOption(option) diff --git a/scripts/test/SettingsTest.py b/scripts/test/SettingsTest.py index 5644ab457523e7772e161cd35c4df6293e8cf3ec..1b53835495137062c541007aca8eb89ae53d67ad 100644 --- a/scripts/test/SettingsTest.py +++ b/scripts/test/SettingsTest.py @@ -1,3 +1,4 @@ +from __future__ import (absolute_import, division, print_function) import unittest import os from mantid.simpleapi import * @@ -47,14 +48,14 @@ if not skipAllTests(): class SettingsTest(unittest.TestCase): def test_avalid_file(self): - fileObject = TempFile(contents="<SettingList><Setting name='test_setting'>test</Setting></SettingList>", extension=".xml") + fileObject = TempFile(contents=b"<SettingList><Setting name='test_setting'>test</Setting></SettingList>", extension=".xml") configuration = settings.Settings( fileObject.pathToFile() ) entries = configuration.get_all_entries() self.assertEqual(len(entries), 1, "There is only one setting entry") # Quick check def test_bad_file_extension_throws(self): bad_extension = ".txt " - fileObject = TempFile(contents="<SettingList><Setting name='test_setting'>test</Setting></SettingList>", extension=bad_extension) + fileObject = TempFile(contents=b"<SettingList><Setting name='test_setting'>test</Setting></SettingList>", extension=bad_extension) self.assertRaises(ValueError, settings.Settings, fileObject.pathToFile() ) def test_bad_file_location_throws(self): @@ -62,19 +63,19 @@ if not skipAllTests(): self.assertRaises(settings.MissingSettings, settings.Settings, missing_file) def test_bad_xml_format_throws(self): - fileObject = TempFile(contents="<SettingList>invalid xml", extension=".xml") + fileObject = TempFile(contents=b"<SettingList>invalid xml", extension=".xml") self.assertRaises(ValueError, settings.Settings, fileObject.pathToFile() ) def test_sanity_check_missing_attribute_name_throws(self): - fileObject = TempFile(contents="<SettingList><Setting>test</Setting></SettingList>", extension=".xml") + fileObject = TempFile(contents=b"<SettingList><Setting>test</Setting></SettingList>", extension=".xml") self.assertRaises(ValueError, settings.Settings, fileObject.pathToFile() ) def test_sanity_check_missing_attribute_value_throws(self): - fileObject = TempFile(contents="<SettingList><Setting name='test_setting'></Setting></SettingList>", extension=".xml") + fileObject = TempFile(contents=b"<SettingList><Setting name='test_setting'></Setting></SettingList>", extension=".xml") self.assertRaises(ValueError, settings.Settings, fileObject.pathToFile() ) def test_get_entries(self): - fileObject = TempFile(contents="<SettingList><Setting name='a'>1</Setting><Setting name='b'>2</Setting></SettingList>", extension=".xml") + fileObject = TempFile(contents=b"<SettingList><Setting name='a'>1</Setting><Setting name='b'>2</Setting></SettingList>", extension=".xml") configuration = settings.Settings( fileObject.pathToFile() ) entries = configuration.get_all_entries() self.assertEqual(len(entries), 2) @@ -82,12 +83,12 @@ if not skipAllTests(): self.assertEqual(int(entries['b']), 2) def test_get_filename(self): - fileObject = TempFile(contents="<SettingList></SettingList>", extension=".xml") + fileObject = TempFile(contents=b"<SettingList></SettingList>", extension=".xml") configuration = settings.Settings( fileObject.pathToFile() ) self.assertEqual(configuration.get_contents_file(), fileObject.pathToFile()) def test_get_named_setting(self): - fileObject = TempFile(contents="<SettingList><Setting name='a'>1</Setting></SettingList>", extension=".xml") + fileObject = TempFile(contents=b"<SettingList><Setting name='a'>1</Setting></SettingList>", extension=".xml") configuration = settings.Settings( fileObject.pathToFile() ) self.assertEqual(configuration.get_named_setting('a'), '1') self.assertRaises(KeyError, configuration.get_named_setting, 'b')