python3 compatible solutions that still work on python2

This commit is contained in:
Martin Diehl 2016-09-11 19:03:32 +02:00
parent 590f42cdb6
commit 9d7cad1fa4
3 changed files with 63 additions and 71 deletions

View File

@ -154,7 +154,7 @@ class Quaternion:
def __div__(self, other): def __div__(self, other):
"""division""" """division"""
if isinstance(other, (int,float,long)): if isinstance(other, (int,float)):
w = self.w / other w = self.w / other
x = self.x / other x = self.x / other
y = self.y / other y = self.y / other
@ -165,7 +165,7 @@ class Quaternion:
def __idiv__(self, other): def __idiv__(self, other):
"""in place division""" """in place division"""
if isinstance(other, (int,float,long)): if isinstance(other, (int,float)):
self.w /= other self.w /= other
self.x /= other self.x /= other
self.y /= other self.y /= other
@ -338,7 +338,7 @@ class Quaternion:
type = "bunge", type = "bunge",
degrees = False, degrees = False,
standardRange = False): standardRange = False):
u""" """
Orientation as Bunge-Euler angles Orientation as Bunge-Euler angles
conversion of ACTIVE rotation to Euler angles taken from: conversion of ACTIVE rotation to Euler angles taken from:
@ -553,7 +553,7 @@ class Symmetry:
def __init__(self, symmetry = None): def __init__(self, symmetry = None):
"""lattice with given symmetry, defaults to None""" """lattice with given symmetry, defaults to None"""
if isinstance(symmetry, basestring) and symmetry.lower() in Symmetry.lattices: if isinstance(symmetry, str) and symmetry.lower() in Symmetry.lattices:
self.lattice = symmetry.lower() self.lattice = symmetry.lower()
else: else:
self.lattice = None self.lattice = None
@ -650,8 +650,8 @@ class Symmetry:
[ 1.0,0.0,0.0,0.0 ], [ 1.0,0.0,0.0,0.0 ],
] ]
return map(Quaternion, return list(map(Quaternion,
np.array(symQuats)[np.atleast_1d(np.array(who)) if who != [] else xrange(len(symQuats))]) np.array(symQuats)[np.atleast_1d(np.array(who)) if who != [] else range(len(symQuats))]))
def equivalentQuaternions(self, def equivalentQuaternions(self,
@ -887,8 +887,7 @@ class Orientation:
def equivalentOrientations(self, def equivalentOrientations(self,
who = []): who = []):
return map(lambda q: Orientation(quaternion = q, symmetry = self.symmetry.lattice), return [Orientation(quaternion = q, symmetry = self.symmetry.lattice) for q in self.equivalentQuaternions(who)]
self.equivalentQuaternions(who))
def reduced(self): def reduced(self):
"""Transform orientation to fall into fundamental zone according to symmetry""" """Transform orientation to fall into fundamental zone according to symmetry"""
@ -917,7 +916,7 @@ class Orientation:
for i,sA in enumerate(mySymQs): for i,sA in enumerate(mySymQs):
for j,sB in enumerate(otherSymQs): for j,sB in enumerate(otherSymQs):
theQ = sA.conjugated()*misQ*sB theQ = sA.conjugated()*misQ*sB
for k in xrange(2): for k in range(2):
theQ.conjugate() theQ.conjugate()
breaker = self.symmetry.inFZ(theQ) \ breaker = self.symmetry.inFZ(theQ) \
and (not SST or other.symmetry.inDisorientationSST(theQ)) and (not SST or other.symmetry.inDisorientationSST(theQ))

View File

@ -55,7 +55,7 @@ class Test():
def execute(self): def execute(self):
"""Run all variants and report first failure.""" """Run all variants and report first failure."""
if self.options.debug: if self.options.debug:
for variant in xrange(len(self.variants)): for variant in range(len(self.variants)):
try: try:
self.postprocess(variant) self.postprocess(variant)
if not self.compare(variant): if not self.compare(variant):
@ -68,7 +68,7 @@ class Test():
if not self.testPossible(): return -1 if not self.testPossible(): return -1
self.clean() self.clean()
self.prepareAll() self.prepareAll()
for variant in xrange(len(self.variants)): for variant in range(len(self.variants)):
try: try:
self.prepare(variant) self.prepare(variant)
self.run(variant) self.run(variant)
@ -178,7 +178,7 @@ class Test():
""" """
if not B or len(B) == 0: B = A if not B or len(B) == 0: B = A
for source,target in zip(map(mapA,A),map(mapB,B)): for source,target in zip(list(map(mapA,A)),list(map(mapB,B))):
try: try:
shutil.copy2(source,target) shutil.copy2(source,target)
except: except:
@ -269,9 +269,9 @@ class Test():
max_loc=np.argmax(abs(refArrayNonZero[curArray.nonzero()]/curArray[curArray.nonzero()]-1.)) max_loc=np.argmax(abs(refArrayNonZero[curArray.nonzero()]/curArray[curArray.nonzero()]-1.))
refArrayNonZero = refArrayNonZero[curArray.nonzero()] refArrayNonZero = refArrayNonZero[curArray.nonzero()]
curArray = curArray[curArray.nonzero()] curArray = curArray[curArray.nonzero()]
print(' ********\n * maximum relative error {} between {} and {}\n ********'.format(max_err, print((' ********\n * maximum relative error {} between {} and {}\n ********'.format(max_err,
refArrayNonZero[max_loc], refArrayNonZero[max_loc],
curArray[max_loc])) curArray[max_loc])))
return max_err return max_err
else: else:
raise Exception('mismatch in array size to compare') raise Exception('mismatch in array size to compare')
@ -301,26 +301,26 @@ class Test():
# check if comparison is possible and determine lenght of columns # check if comparison is possible and determine lenght of columns
if len(headings0) == len(headings1) == len(normHeadings): if len(headings0) == len(headings1) == len(normHeadings):
dataLength = len(headings0) dataLength = len(headings0)
length = [1 for i in xrange(dataLength)] length = [1 for i in range(dataLength)]
shape = [[] for i in xrange(dataLength)] shape = [[] for i in range(dataLength)]
data = [[] for i in xrange(dataLength)] data = [[] for i in range(dataLength)]
maxError = [0.0 for i in xrange(dataLength)] maxError = [0.0 for i in range(dataLength)]
absTol = [absoluteTolerance for i in xrange(dataLength)] absTol = [absoluteTolerance for i in range(dataLength)]
column = [[1 for i in xrange(dataLength)] for j in xrange(2)] column = [[1 for i in range(dataLength)] for j in range(2)]
norm = [[] for i in xrange(dataLength)] norm = [[] for i in range(dataLength)]
normLength = [1 for i in xrange(dataLength)] normLength = [1 for i in range(dataLength)]
normShape = [[] for i in xrange(dataLength)] normShape = [[] for i in range(dataLength)]
normColumn = [1 for i in xrange(dataLength)] normColumn = [1 for i in range(dataLength)]
for i in xrange(dataLength): for i in range(dataLength):
if headings0[i]['shape'] != headings1[i]['shape']: if headings0[i]['shape'] != headings1[i]['shape']:
raise Exception('shape mismatch between {} and {} '.format(headings0[i]['label'],headings1[i]['label'])) raise Exception('shape mismatch between {} and {} '.format(headings0[i]['label'],headings1[i]['label']))
shape[i] = headings0[i]['shape'] shape[i] = headings0[i]['shape']
for j in xrange(np.shape(shape[i])[0]): for j in range(np.shape(shape[i])[0]):
length[i] *= shape[i][j] length[i] *= shape[i][j]
normShape[i] = normHeadings[i]['shape'] normShape[i] = normHeadings[i]['shape']
for j in xrange(np.shape(normShape[i])[0]): for j in range(np.shape(normShape[i])[0]):
normLength[i] *= normShape[i][j] normLength[i] *= normShape[i][j]
else: else:
raise Exception('trying to compare {} with {} normed by {} data sets'.format(len(headings0), raise Exception('trying to compare {} with {} normed by {} data sets'.format(len(headings0),
@ -332,7 +332,7 @@ class Test():
table1 = damask.ASCIItable(name=file1,readonly=True) table1 = damask.ASCIItable(name=file1,readonly=True)
table1.head_read() table1.head_read()
for i in xrange(dataLength): for i in range(dataLength):
key0 = ('1_' if length[i]>1 else '') + headings0[i]['label'] key0 = ('1_' if length[i]>1 else '') + headings0[i]['label']
key1 = ('1_' if length[i]>1 else '') + headings1[i]['label'] key1 = ('1_' if length[i]>1 else '') + headings1[i]['label']
normKey = ('1_' if normLength[i]>1 else '') + normHeadings[i]['label'] normKey = ('1_' if normLength[i]>1 else '') + normHeadings[i]['label']
@ -350,11 +350,11 @@ class Test():
line0 = 0 line0 = 0
while table0.data_read(): # read next data line of ASCII table while table0.data_read(): # read next data line of ASCII table
if line0 not in skipLines: if line0 not in skipLines:
for i in xrange(dataLength): for i in range(dataLength):
myData = np.array(map(float,table0.data[column[0][i]:\ myData = np.array(list(map(float,table0.data[column[0][i]:\
column[0][i]+length[i]]),'d') column[0][i]+length[i]])),'d')
normData = np.array(map(float,table0.data[normColumn[i]:\ normData = np.array(list(map(float,table0.data[normColumn[i]:\
normColumn[i]+normLength[i]]),'d') normColumn[i]+normLength[i]])),'d')
data[i] = np.append(data[i],np.reshape(myData,shape[i])) data[i] = np.append(data[i],np.reshape(myData,shape[i]))
if normType == 'pInf': if normType == 'pInf':
norm[i] = np.append(norm[i],np.max(np.abs(normData))) norm[i] = np.append(norm[i],np.max(np.abs(normData)))
@ -362,11 +362,11 @@ class Test():
norm[i] = np.append(norm[i],np.linalg.norm(np.reshape(normData,normShape[i]),normType)) norm[i] = np.append(norm[i],np.linalg.norm(np.reshape(normData,normShape[i]),normType))
line0 += 1 line0 += 1
for i in xrange(dataLength): for i in range(dataLength):
if not perLine: norm[i] = [np.max(norm[i]) for j in xrange(line0-len(skipLines))] if not perLine: norm[i] = [np.max(norm[i]) for j in range(line0-len(skipLines))]
data[i] = np.reshape(data[i],[line0-len(skipLines),length[i]]) data[i] = np.reshape(data[i],[line0-len(skipLines),length[i]])
if any(norm[i]) == 0.0 or absTol[i]: if any(norm[i]) == 0.0 or absTol[i]:
norm[i] = [1.0 for j in xrange(line0-len(skipLines))] norm[i] = [1.0 for j in range(line0-len(skipLines))]
absTol[i] = True absTol[i] = True
if perLine: if perLine:
logging.warning('At least one norm of {} in 1. table is 0.0, using absolute tolerance'.format(headings0[i]['label'])) logging.warning('At least one norm of {} in 1. table is 0.0, using absolute tolerance'.format(headings0[i]['label']))
@ -376,9 +376,9 @@ class Test():
line1 = 0 line1 = 0
while table1.data_read(): # read next data line of ASCII table while table1.data_read(): # read next data line of ASCII table
if line1 not in skipLines: if line1 not in skipLines:
for i in xrange(dataLength): for i in range(dataLength):
myData = np.array(map(float,table1.data[column[1][i]:\ myData = np.array(list(map(float,table1.data[column[1][i]:\
column[1][i]+length[i]]),'d') column[1][i]+length[i]])),'d')
maxError[i] = max(maxError[i],np.linalg.norm(np.reshape(myData-data[i][line1-len(skipLines),:],shape[i]))/ maxError[i] = max(maxError[i],np.linalg.norm(np.reshape(myData-data[i][line1-len(skipLines),:],shape[i]))/
norm[i][line1-len(skipLines)]) norm[i][line1-len(skipLines)])
line1 +=1 line1 +=1
@ -386,7 +386,7 @@ class Test():
if (line0 != line1): raise Exception('found {} lines in 1. table but {} in 2. table'.format(line0,line1)) if (line0 != line1): raise Exception('found {} lines in 1. table but {} in 2. table'.format(line0,line1))
logging.info(' ********') logging.info(' ********')
for i in xrange(dataLength): for i in range(dataLength):
if absTol[i]: if absTol[i]:
logging.info(' * maximum absolute error {} between {} and {}'.format(maxError[i], logging.info(' * maximum absolute error {} between {} and {}'.format(maxError[i],
headings0[i]['label'], headings0[i]['label'],
@ -424,7 +424,7 @@ class Test():
if column is None: columns[i] = tables[i].labels(raw = True) # if no column is given, read all if column is None: columns[i] = tables[i].labels(raw = True) # if no column is given, read all
logging.info('comparing ASCIItables statistically') logging.info('comparing ASCIItables statistically')
for i in xrange(len(columns)): for i in range(len(columns)):
columns[i] = columns[0] if not columns[i] else \ columns[i] = columns[0] if not columns[i] else \
([columns[i]] if not (isinstance(columns[i], Iterable) and not isinstance(columns[i], str)) else \ ([columns[i]] if not (isinstance(columns[i], Iterable) and not isinstance(columns[i], str)) else \
columns[i] columns[i]
@ -440,7 +440,7 @@ class Test():
table.close() table.close()
for i in xrange(1,len(data)): for i in range(1,len(data)):
delta = data[i]-data[i-1] delta = data[i]-data[i-1]
normBy = (np.abs(data[i]) + np.abs(data[i-1]))*0.5 normBy = (np.abs(data[i]) + np.abs(data[i-1]))*0.5
normedDelta = np.where(normBy>preFilter,delta/normBy,0.0) normedDelta = np.where(normBy>preFilter,delta/normBy,0.0)
@ -480,7 +480,7 @@ class Test():
if column is None: columns[i] = tables[i].labels(raw = True) # if no column is given, read all if column is None: columns[i] = tables[i].labels(raw = True) # if no column is given, read all
logging.info('comparing ASCIItables') logging.info('comparing ASCIItables')
for i in xrange(len(columns)): for i in range(len(columns)):
columns[i] = columns[0] if not columns[i] else \ columns[i] = columns[0] if not columns[i] else \
([columns[i]] if not (isinstance(columns[i], Iterable) and not isinstance(columns[i], str)) else \ ([columns[i]] if not (isinstance(columns[i], Iterable) and not isinstance(columns[i], str)) else \
columns[i] columns[i]
@ -499,7 +499,7 @@ class Test():
maximum /= len(tables) maximum /= len(tables)
maximum = np.where(maximum >0.0, maximum, 1) # avoid div by zero for empty columns maximum = np.where(maximum >0.0, maximum, 1) # avoid div by zero for empty columns
for i in xrange(len(data)): for i in range(len(data)):
data[i] /= maximum data[i] /= maximum
mask = np.zeros_like(table.data,dtype='bool') mask = np.zeros_like(table.data,dtype='bool')
@ -509,7 +509,7 @@ class Test():
allclose = True # start optimistic allclose = True # start optimistic
for i in xrange(1,len(data)): for i in range(1,len(data)):
if debug: if debug:
t0 = np.where(mask,0.0,data[i-1]) t0 = np.where(mask,0.0,data[i-1])
t1 = np.where(mask,0.0,data[i ]) t1 = np.where(mask,0.0,data[i ])

View File

@ -40,7 +40,7 @@ def srepr(arg,glue = '\n'):
hasattr(arg, "__getitem__") or hasattr(arg, "__getitem__") or
hasattr(arg, "__iter__")): hasattr(arg, "__iter__")):
return glue.join(srepr(x) for x in arg) return glue.join(srepr(x) for x in arg)
return arg if isinstance(arg,basestring) else repr(arg) return arg if isinstance(arg,str) else repr(arg)
# ----------------------------- # -----------------------------
def croak(what, newline = True): def croak(what, newline = True):
@ -136,29 +136,22 @@ class extendableOption(Option):
class backgroundMessage(threading.Thread): class backgroundMessage(threading.Thread):
"""reporting with animation to indicate progress""" """reporting with animation to indicate progress"""
choices = {'bounce': ['_', 'o', 'O', u'\u00B0', choices = {'bounce': ['_', 'o', 'O', '°', '', '', '°', 'O', 'o', '_'],
u'\u203e',u'\u203e',u'\u00B0','O','o','_'], 'spin': ['', '', '', ''],
'spin': [u'\u25dc',u'\u25dd',u'\u25de',u'\u25df'], 'circle': ['', '', '', ''],
'circle': [u'\u25f4',u'\u25f5',u'\u25f6',u'\u25f7'], 'hexagon': ['', ''],
'hexagon': [u'\u2b22',u'\u2b23'], 'square': ['', '', '', ''],
'square': [u'\u2596',u'\u2598',u'\u259d',u'\u2597'], 'triangle': ['', '', '', '', '', ''],
'triangle': [u'\u140a',u'\u140a',u'\u1403',u'\u1405',u'\u1405',u'\u1403'], 'amoeba': ['', '', '', '', '', '', '', ''],
'amoeba': [u'\u2596',u'\u258f',u'\u2598',u'\u2594',u'\u259d',u'\u2595', 'beat': ['', '', '', '', '', '', '', '', '', '', ''],
u'\u2597',u'\u2582'], 'prison': ['', '', '', '', '', '', '', ''],
'beat': [u'\u2581',u'\u2582',u'\u2583',u'\u2585',u'\u2586',u'\u2587', 'breath': ['', '', '', '', '', '', '', '', ''],
u'\u2587',u'\u2586',u'\u2585',u'\u2583',u'\u2582',], 'pulse': ['·', '', '', '', ''],
'prison': [u'\u168b',u'\u168c',u'\u168d',u'\u168f',u'\u168e',u'\u168d', 'ant': ['', '', '', '', '', '', '', '', '', '', '', ''],
u'\u168c',u'\u168b',], 'juggle': ['', '', '', '', '', '', '', '', ''],
'breath': [u'\u1690',u'\u1691',u'\u1692',u'\u1693',u'\u1694',u'\u1693', # 'wobbler': ['▁', '◣', '▏', '◤', '▔', '◥', '▕', '◢'],
u'\u1692',u'\u1691',u'\u1690',], 'grout': ['', '', '', ''],
'pulse': [u'·',u'',u'\u25cf',u'\u25cf',u'',], 'partner': ['', '', '', '', '', ''],
'ant': [u'\u2801',u'\u2802',u'\u2810',u'\u2820',u'\u2804',u'\u2840',
u'\u2880',u'\u2820',u'\u2804',u'\u2802',u'\u2810',u'\u2808'],
'juggle': [u'\ua708',u'\ua709',u'\ua70a',u'\ua70b',u'\ua70c',u'\ua711',
u'\ua710',u'\ua70f',u'\ua70d',],
# 'wobbler': [u'\u2581',u'\u25e3',u'\u258f',u'\u25e4',u'\u2594',u'\u25e5',u'\u2595',u'\u25e2',],
'grout': [u'\u2581',u'\u258f',u'\u2594',u'\u2595',],
'partner': [u'\u26ac',u'\u26ad',u'\u26ae',u'\u26af',u'\u26ae',u'\u26ad',],
'classic': ['-', '\\', '|', '/',], 'classic': ['-', '\\', '|', '/',],
} }
@ -170,7 +163,7 @@ class backgroundMessage(threading.Thread):
self.new_message = '' self.new_message = ''
self.counter = 0 self.counter = 0
self.gap = ' ' self.gap = ' '
self.symbols = self.choices[symbol if symbol in self.choices else random.choice(self.choices.keys())] self.symbols = self.choices[symbol if symbol in self.choices else random.choice(list(self.choices.keys()))]
self.waittime = wait self.waittime = wait
def __quit__(self): def __quit__(self):
@ -199,7 +192,7 @@ class backgroundMessage(threading.Thread):
def print_message(self): def print_message(self):
length = len(self.symbols[self.counter] + self.gap + self.message) length = len(self.symbols[self.counter] + self.gap + self.message)
sys.stderr.write(chr(8)*length + ' '*length + chr(8)*length + \ sys.stderr.write(chr(8)*length + ' '*length + chr(8)*length + \
self.symbols[self.counter].encode('utf-8') + self.gap + self.new_message) # delete former and print new message self.symbols[self.counter] + self.gap + self.new_message) # delete former and print new message
sys.stderr.flush() sys.stderr.flush()
self.message = self.new_message self.message = self.new_message