compatible to python3

This commit is contained in:
Martin Diehl 2016-07-02 13:28:32 +02:00
parent af4307ea72
commit 759126b906
8 changed files with 47 additions and 39 deletions

View File

@ -12,7 +12,7 @@ from .config import Material # noqa
from .colormaps import Colormap, Color # noqa from .colormaps import Colormap, Color # noqa
try: try:
from .corientation import Quaternion, Rodrigues, Symmetry, Orientation # noqa from .corientation import Quaternion, Rodrigues, Symmetry, Orientation # noqa
print "Import Cython version of Orientation module" print("Import Cython version of Orientation module")
except: except:
from .orientation import Quaternion, Rodrigues, Symmetry, Orientation # noqa from .orientation import Quaternion, Rodrigues, Symmetry, Orientation # noqa
#from .block import Block # only one class #from .block import Block # only one class

View File

@ -3,6 +3,14 @@
import os,sys import os,sys
import numpy as np import numpy as np
# ------------------------------------------------------------------
# python 3 has no unicode object, this ensures that the code works on Python 2&3
try:
test=isinstance('test', unicode)
except(NameError):
unicode=str
# ------------------------------------------------------------------
class ASCIItable(): class ASCIItable():
"""Read and write to ASCII tables""" """Read and write to ASCII tables"""
@ -158,12 +166,12 @@ class ASCIItable():
if self.__IO__['labeled']: # table features labels if self.__IO__['labeled']: # table features labels
self.info = [self.__IO__['in'].readline().strip() for i in xrange(1,int(m.group(1)))] self.info = [self.__IO__['in'].readline().strip() for i in range(1,int(m.group(1)))]
self.tags = shlex.split(self.__IO__['in'].readline()) # store tags found in last line self.tags = shlex.split(self.__IO__['in'].readline()) # store tags found in last line
else: else:
self.info = [self.__IO__['in'].readline().strip() for i in xrange(0,int(m.group(1)))] # all header is info ... self.info = [self.__IO__['in'].readline().strip() for i in range(0,int(m.group(1)))] # all header is info ...
else: # other table format else: # other table format
try: try:
@ -224,11 +232,11 @@ class ASCIItable():
extra_header = [] extra_header = []
for header in self.info: for header in self.info:
headitems = map(str.lower,header.split()) headitems = list(map(str.lower,header.split()))
if len(headitems) == 0: continue # skip blank lines if len(headitems) == 0: continue # skip blank lines
if headitems[0] in mappings.keys(): if headitems[0] in list(mappings.keys()):
if headitems[0] in identifiers.keys(): if headitems[0] in list(identifiers.keys()):
for i in xrange(len(identifiers[headitems[0]])): for i in range(len(identifiers[headitems[0]])):
info[headitems[0]][i] = \ info[headitems[0]][i] = \
mappings[headitems[0]](headitems[headitems.index(identifiers[headitems[0]][i])+1]) mappings[headitems[0]](headitems[headitems.index(identifiers[headitems[0]][i])+1])
else: else:
@ -415,9 +423,9 @@ class ASCIItable():
start = self.label_index(labels) start = self.label_index(labels)
dim = self.label_dimension(labels) dim = self.label_dimension(labels)
return np.hstack(map(lambda c: xrange(c[0],c[0]+c[1]), zip(start,dim))) \ return np.hstack([range(c[0],c[0]+c[1]) for c in zip(start,dim)]) \
if isinstance(labels, Iterable) and not isinstance(labels, str) \ if isinstance(labels, Iterable) and not isinstance(labels, str) \
else xrange(start,start+dim) else range(start,start+dim)
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def info_append(self, def info_append(self,
@ -447,7 +455,7 @@ class ASCIItable():
def data_skipLines(self, def data_skipLines(self,
count): count):
"""wind forward by count number of lines""" """wind forward by count number of lines"""
for i in xrange(count): for i in range(count):
alive = self.data_read() alive = self.data_read()
return alive return alive
@ -501,9 +509,9 @@ class ASCIItable():
columns = [] columns = []
for i,(c,d) in enumerate(zip(indices[present],dimensions[present])): # for all valid labels ... for i,(c,d) in enumerate(zip(indices[present],dimensions[present])): # for all valid labels ...
# ... transparently add all components unless column referenced by number or with explicit dimension # ... transparently add all components unless column referenced by number or with explicit dimension
columns += range(c,c + \ columns += list(range(c,c + \
(d if str(c) != str(labels[present[i]]) else \ (d if str(c) != str(labels[present[i]]) else \
1)) 1)))
use = np.array(columns) use = np.array(columns)
self.tags = list(np.array(self.tags)[use]) # update labels with valid subset self.tags = list(np.array(self.tags)[use]) # update labels with valid subset
@ -530,7 +538,7 @@ class ASCIItable():
"""write whole numpy array data""" """write whole numpy array data"""
for row in self.data: for row in self.data:
try: try:
output = [fmt % value for value in row] if fmt else map(repr,row) output = [fmt % value for value in row] if fmt else list(map(repr,row))
except: except:
output = [fmt % row] if fmt else [repr(row)] output = [fmt % row] if fmt else [repr(row)]
@ -555,7 +563,7 @@ class ASCIItable():
try: try:
idx = self.label_index(where) idx = self.label_index(where)
if len(self.data) <= idx: if len(self.data) <= idx:
self.data_append(['n/a' for i in xrange(idx+1-len(self.data))]) # grow data if too short self.data_append(['n/a' for i in range(idx+1-len(self.data))]) # grow data if too short
self.data[idx] = str(what) self.data[idx] = str(what)
except(ValueError): except(ValueError):
pass pass
@ -568,7 +576,7 @@ class ASCIItable():
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def data_asFloat(self): def data_asFloat(self):
return map(self._transliterateToFloat,self.data) return list(map(self._transliterateToFloat,self.data))
@ -590,8 +598,8 @@ class ASCIItable():
if len(items) > 2: if len(items) > 2:
if items[1].lower() == 'of': items = np.ones(datatype(items[0]))*datatype(items[2]) if items[1].lower() == 'of': items = np.ones(datatype(items[0]))*datatype(items[2])
elif items[1].lower() == 'to': items = np.arange(datatype(items[0]),1+datatype(items[2])) elif items[1].lower() == 'to': items = np.arange(datatype(items[0]),1+datatype(items[2]))
else: items = map(datatype,items) else: items = list(map(datatype,items))
else: items = map(datatype,items) else: items = list(map(datatype,items))
s = min(len(items), N-i) # prevent overflow of microstructure array s = min(len(items), N-i) # prevent overflow of microstructure array
microstructure[i:i+s] = items[:s] microstructure[i:i+s] = items[:s]

View File

@ -33,7 +33,7 @@ class Color():
} }
model = model.upper() model = model.upper()
if model not in self.__transforms__.keys(): model = 'RGB' if model not in list(self.__transforms__.keys()): model = 'RGB'
if model == 'RGB' and max(color) > 1.0: # are we RGB255 ? if model == 'RGB' and max(color) > 1.0: # are we RGB255 ?
for i in range(3): for i in range(3):
color[i] /= 255.0 # rescale to RGB color[i] /= 255.0 # rescale to RGB
@ -62,7 +62,7 @@ class Color():
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def convertTo(self,toModel = 'RGB'): def convertTo(self,toModel = 'RGB'):
toModel = toModel.upper() toModel = toModel.upper()
if toModel not in self.__transforms__.keys(): return if toModel not in list(self.__transforms__.keys()): return
sourcePos = self.__transforms__[self.model]['index'] sourcePos = self.__transforms__[self.model]['index']
targetPos = self.__transforms__[toModel]['index'] targetPos = self.__transforms__[toModel]['index']
@ -139,7 +139,7 @@ class Color():
HSL[0] = HSL[0]*60.0 # scaling to 360 might be dangerous for small values HSL[0] = HSL[0]*60.0 # scaling to 360 might be dangerous for small values
if (HSL[0] < 0.0): if (HSL[0] < 0.0):
HSL[0] = HSL[0] + 360.0 HSL[0] = HSL[0] + 360.0
for i in xrange(2): for i in range(2):
HSL[i+1] = min(HSL[i+1],1.0) HSL[i+1] = min(HSL[i+1],1.0)
HSL[i+1] = max(HSL[i+1],0.0) HSL[i+1] = max(HSL[i+1],0.0)
@ -164,11 +164,11 @@ class Color():
[0.212671,0.715160,0.072169], [0.212671,0.715160,0.072169],
[0.019334,0.119193,0.950227]]) [0.019334,0.119193,0.950227]])
for i in xrange(3): for i in range(3):
if (self.color[i] > 0.04045): RGB_lin[i] = ((self.color[i]+0.0555)/1.0555)**2.4 if (self.color[i] > 0.04045): RGB_lin[i] = ((self.color[i]+0.0555)/1.0555)**2.4
else: RGB_lin[i] = self.color[i] /12.92 else: RGB_lin[i] = self.color[i] /12.92
XYZ = np.dot(convert,RGB_lin) XYZ = np.dot(convert,RGB_lin)
for i in xrange(3): for i in range(3):
XYZ[i] = max(XYZ[i],0.0) XYZ[i] = max(XYZ[i],0.0)
@ -193,10 +193,10 @@ class Color():
RGB_lin = np.dot(convert,self.color) RGB_lin = np.dot(convert,self.color)
RGB = np.zeros(3,'d') RGB = np.zeros(3,'d')
for i in xrange(3): for i in range(3):
if (RGB_lin[i] > 0.0031308): RGB[i] = ((RGB_lin[i])**(1.0/2.4))*1.0555-0.0555 if (RGB_lin[i] > 0.0031308): RGB[i] = ((RGB_lin[i])**(1.0/2.4))*1.0555-0.0555
else: RGB[i] = RGB_lin[i] *12.92 else: RGB[i] = RGB_lin[i] *12.92
for i in xrange(3): for i in range(3):
RGB[i] = min(RGB[i],1.0) RGB[i] = min(RGB[i],1.0)
RGB[i] = max(RGB[i],0.0) RGB[i] = max(RGB[i],0.0)
@ -225,7 +225,7 @@ class Color():
XYZ[0] = XYZ[1] + self.color[1]/ 500.0 XYZ[0] = XYZ[1] + self.color[1]/ 500.0
XYZ[2] = XYZ[1] - self.color[2]/ 200.0 XYZ[2] = XYZ[1] - self.color[2]/ 200.0
for i in xrange(len(XYZ)): for i in range(len(XYZ)):
if (XYZ[i] > 6./29. ): XYZ[i] = XYZ[i]**3. if (XYZ[i] > 6./29. ): XYZ[i] = XYZ[i]**3.
else: XYZ[i] = 108./841. * (XYZ[i] - 4./29.) else: XYZ[i] = 108./841. * (XYZ[i] - 4./29.)
@ -245,7 +245,7 @@ class Color():
ref_white = np.array([.95047, 1.00000, 1.08883],'d') # Observer = 2, Illuminant = D65 ref_white = np.array([.95047, 1.00000, 1.08883],'d') # Observer = 2, Illuminant = D65
XYZ = self.color/ref_white XYZ = self.color/ref_white
for i in xrange(len(XYZ)): for i in range(len(XYZ)):
if (XYZ[i] > 216./24389 ): XYZ[i] = XYZ[i]**(1.0/3.0) if (XYZ[i] > 216./24389 ): XYZ[i] = XYZ[i]**(1.0/3.0)
else: XYZ[i] = (841./108. * XYZ[i]) + 16.0/116.0 else: XYZ[i] = (841./108. * XYZ[i]) + 16.0/116.0
@ -451,7 +451,7 @@ class Colormap():
""" """
format = format.lower() # consistent comparison basis format = format.lower() # consistent comparison basis
frac = 0.5*(np.array(crop) + 1.0) # rescale crop range to fractions frac = 0.5*(np.array(crop) + 1.0) # rescale crop range to fractions
colors = [self.color(float(i)/(steps-1)*(frac[1]-frac[0])+frac[0]).expressAs(model).color for i in xrange(steps)] colors = [self.color(float(i)/(steps-1)*(frac[1]-frac[0])+frac[0]).expressAs(model).color for i in range(steps)]
if format == 'paraview': if format == 'paraview':
colormap = ['[\n {{\n "ColorSpace" : "RGB", "Name" : "{}",\n "RGBPoints" : ['.format(name)] \ colormap = ['[\n {{\n "ColorSpace" : "RGB", "Name" : "{}",\n "RGBPoints" : ['.format(name)] \
+ [' {:4d},{:8.6f},{:8.6f},{:8.6f},'.format(i,color[0],color[1],color[2],) + [' {:4d},{:8.6f},{:8.6f},{:8.6f},'.format(i,color[0],color[1],color[2],)
@ -461,7 +461,7 @@ class Colormap():
elif format == 'gmsh': elif format == 'gmsh':
colormap = ['View.ColorTable = {'] \ colormap = ['View.ColorTable = {'] \
+ [',\n'.join(['{%s}'%(','.join(map(lambda x:str(x*255.0),color))) for color in colors])] \ + [',\n'.join(['{%s}'%(','.join([str(x*255.0) for x in color])) for color in colors])] \
+ ['}'] + ['}']
elif format == 'gom': elif format == 'gom':
@ -469,7 +469,7 @@ class Colormap():
+ ' 9 ' + str(name) \ + ' 9 ' + str(name) \
+ ' 0 1 0 3 0 0 -1 9 \ 0 0 0 255 255 255 0 0 255 ' \ + ' 0 1 0 3 0 0 -1 9 \ 0 0 0 255 255 255 0 0 255 ' \
+ '30 NO_UNIT 1 1 64 64 64 255 1 0 0 0 0 0 0 3 0 ' + str(len(colors)) \ + '30 NO_UNIT 1 1 64 64 64 255 1 0 0 0 0 0 0 3 0 ' + str(len(colors)) \
+ ' '.join([' 0 %s 255 1'%(' '.join(map(lambda x:str(int(x*255.0)),color))) for color in reversed(colors)])] + ' '.join([' 0 %s 255 1'%(' '.join([str(int(x*255.0)) for x in color])) for color in reversed(colors)])]
elif format == 'raw': elif format == 'raw':
colormap = ['\t'.join(map(str,color)) for color in colors] colormap = ['\t'.join(map(str,color)) for color in colors]

View File

@ -19,7 +19,7 @@ class Section():
self.parameters[key] = data[key] self.parameters[key] = data[key]
if '__order__' not in self.parameters: if '__order__' not in self.parameters:
self.parameters['__order__'] = self.parameters.keys() self.parameters['__order__'] = list(self.parameters.keys())
if part.lower() in classes: if part.lower() in classes:
self.__class__ = classes[part.lower()] self.__class__ = classes[part.lower()]
self.__init__(data) self.__init__(data)
@ -61,11 +61,11 @@ class Texture(Section):
def add_component(self,theType,properties): def add_component(self,theType,properties):
if 'scatter' not in map(str.lower,properties.keys()): if 'scatter' not in list(map(str.lower,list(properties.keys()))):
scatter = 0.0 scatter = 0.0
else: else:
scatter = properties['scatter'] scatter = properties['scatter']
if 'fraction' not in map(str.lower,properties.keys()): if 'fraction' not in list(map(str.lower,list(properties.keys()))):
fraction = 1.0 fraction = 1.0
else: else:
fraction = properties['fraction'] fraction = properties['fraction']
@ -224,10 +224,10 @@ class Material():
def add_microstructure(self, section='', def add_microstructure(self, section='',
components={}, # dict of phase,texture, and fraction lists components={}, # dict of phase,texture, and fraction lists
): ):
"""Experimental! Needs expansion to multi-constituent microstructures...""" """Experimental! Needs expansion to multi-constituent microstructures..."""
microstructure = Microstructure() microstructure = Microstructure()
# make keys lower case (http://stackoverflow.com/questions/764235/dictionary-to-lowercase-in-python) # make keys lower case (http://stackoverflow.com/questions/764235/dictionary-to-lowercase-in-python)
components=dict((k.lower(), v) for k,v in components.iteritems()) components=dict((k.lower(), v) for k,v in components.items())
for key in ['phase','texture','fraction','crystallite']: for key in ['phase','texture','fraction','crystallite']:
if type(components[key]) is not list: if type(components[key]) is not list:

View File

@ -41,7 +41,7 @@ class Environment():
try: try:
cmd = """ ssh mulicense2 "/Stat_Flexlm | grep 'Users of %s: ' | cut -d' ' -f7,13" """%software cmd = """ ssh mulicense2 "/Stat_Flexlm | grep 'Users of %s: ' | cut -d' ' -f7,13" """%software
process = subprocess.Popen(shlex.split(cmd),stdout = subprocess.PIPE,stderr = subprocess.PIPE) process = subprocess.Popen(shlex.split(cmd),stdout = subprocess.PIPE,stderr = subprocess.PIPE)
licenses = map(int, process.stdout.readline().split()) licenses = list(map(int, process.stdout.readline().split()))
try: try:
if licenses[0]-licenses[1] >= Nneeded: if licenses[0]-licenses[1] >= Nneeded:
return 0 return 0

View File

@ -15,7 +15,7 @@ class Geometry():
'spectral': damask.geometry.Spectral, 'spectral': damask.geometry.Spectral,
'marc': damask.geometry.Marc, 'marc': damask.geometry.Marc,
} }
if solver.lower() in solverClass.keys(): if solver.lower() in list(solverClass.keys()):
self.__class__=solverClass[solver.lower()] self.__class__=solverClass[solver.lower()]
self.__init__() self.__init__()

View File

@ -25,7 +25,7 @@ class Marc(Solver):
MSCpath = damask.environment.Environment(rootRelation).options['MSC_ROOT'] MSCpath = damask.environment.Environment(rootRelation).options['MSC_ROOT']
for release,subdirs in sorted(self.releases.items(),reverse=True): for release,subdirs in sorted(list(self.releases.items()),reverse=True):
for subdir in subdirs: for subdir in subdirs:
path = '%s/mentat%s/shlib/%s'%(MSCpath,release,subdir) path = '%s/mentat%s/shlib/%s'%(MSCpath,release,subdir)
if os.path.exists(path): return release if os.path.exists(path): return release
@ -40,7 +40,7 @@ class Marc(Solver):
MSCpath = damask.environment.Environment(rootRelation).options['MSC_ROOT'] MSCpath = damask.environment.Environment(rootRelation).options['MSC_ROOT']
if len(releases) == 0: releases = self.releases.keys() if len(releases) == 0: releases = list(self.releases.keys())
if type(releases) is not list: releases = [releases] if type(releases) is not list: releases = [releases]
for release in sorted(releases,reverse=True): for release in sorted(releases,reverse=True):
if release not in self.releases: continue if release not in self.releases: continue

View File

@ -15,7 +15,7 @@ class Solver():
'spectral': damask.solver.Spectral, 'spectral': damask.solver.Spectral,
'marc': damask.solver.Marc, 'marc': damask.solver.Marc,
} }
if solver.lower() in solverClass.keys(): if solver.lower() in list(solverClass.keys()):
self.__class__=solverClass[solver.lower()] self.__class__=solverClass[solver.lower()]
self.__init__() self.__init__()