advise from pylint

This commit is contained in:
Martin Diehl 2020-03-22 17:03:28 +01:00
parent 1dfdd264b7
commit bbce3456e8
5 changed files with 142 additions and 143 deletions

View File

@ -4,146 +4,146 @@ from . import Lattice
from . import Rotation from . import Rotation
class Orientation: class Orientation:
""" """
Crystallographic orientation. Crystallographic orientation.
A crystallographic orientation contains a rotation and a lattice. A crystallographic orientation contains a rotation and a lattice.
""" """
__slots__ = ['rotation','lattice'] __slots__ = ['rotation','lattice']
def __repr__(self): def __repr__(self):
"""Report lattice type and orientation.""" """Report lattice type and orientation."""
return self.lattice.__repr__()+'\n'+self.rotation.__repr__() return self.lattice.__repr__()+'\n'+self.rotation.__repr__()
def __init__(self, rotation, lattice): def __init__(self, rotation, lattice):
""" """
New orientation from rotation and lattice. New orientation from rotation and lattice.
Parameters Parameters
---------- ----------
rotation : Rotation rotation : Rotation
Rotation specifying the lattice orientation. Rotation specifying the lattice orientation.
lattice : Lattice lattice : Lattice
Lattice type of the crystal. Lattice type of the crystal.
""" """
if isinstance(lattice, Lattice): if isinstance(lattice, Lattice):
self.lattice = lattice self.lattice = lattice
else: else:
self.lattice = Lattice(lattice) # assume string self.lattice = Lattice(lattice) # assume string
if isinstance(rotation, Rotation): if isinstance(rotation, Rotation):
self.rotation = rotation self.rotation = rotation
else: else:
self.rotation = Rotation.fromQuaternion(rotation) # assume quaternion self.rotation = Rotation.fromQuaternion(rotation) # assume quaternion
def disorientation(self, def disorientation(self,
other, other,
SST = True, SST = True,
symmetries = False): symmetries = False):
""" """
Disorientation between myself and given other orientation. Disorientation between myself and given other orientation.
Rotation axis falls into SST if SST == True. Rotation axis falls into SST if SST == True.
(Currently requires same symmetry for both orientations. (Currently requires same symmetry for both orientations.
Look into A. Heinz and P. Neumann 1991 for cases with differing sym.) Look into A. Heinz and P. Neumann 1991 for cases with differing sym.)
""" """
if self.lattice.symmetry != other.lattice.symmetry: if self.lattice.symmetry != other.lattice.symmetry:
raise NotImplementedError('disorientation between different symmetry classes not supported yet.') raise NotImplementedError('disorientation between different symmetry classes not supported yet.')
mySymEqs = self.equivalentOrientations() if SST else self.equivalentOrientations([0]) # take all or only first sym operation mySymEqs = self.equivalentOrientations() if SST else self.equivalentOrientations([0]) # take all or only first sym operation
otherSymEqs = other.equivalentOrientations() otherSymEqs = other.equivalentOrientations()
for i,sA in enumerate(mySymEqs): for i,sA in enumerate(mySymEqs):
aInv = sA.rotation.inversed() aInv = sA.rotation.inversed()
for j,sB in enumerate(otherSymEqs): for j,sB in enumerate(otherSymEqs):
b = sB.rotation b = sB.rotation
r = b*aInv r = b*aInv
for k in range(2): for k in range(2):
r.inverse() r.inverse()
breaker = self.lattice.symmetry.inFZ(r.asRodrigues(vector=True)) \ breaker = self.lattice.symmetry.inFZ(r.asRodrigues(vector=True)) \
and (not SST or other.lattice.symmetry.inDisorientationSST(r.asRodrigues(vector=True))) and (not SST or other.lattice.symmetry.inDisorientationSST(r.asRodrigues(vector=True)))
if breaker: break if breaker: break
if breaker: break if breaker: break
if breaker: break if breaker: break
return (Orientation(r,self.lattice), i,j, k == 1) if symmetries else r # disorientation ... return (Orientation(r,self.lattice), i,j, k == 1) if symmetries else r # disorientation ...
# ... own sym, other sym, # ... own sym, other sym,
# self-->other: True, self<--other: False # self-->other: True, self<--other: False
def inFZ(self): def inFZ(self):
return self.lattice.symmetry.inFZ(self.rotation.asRodrigues(vector=True)) return self.lattice.symmetry.inFZ(self.rotation.asRodrigues(vector=True))
def equivalentOrientations(self,members=[]): def equivalentOrientations(self,members=[]):
"""List of orientations which are symmetrically equivalent.""" """List of orientations which are symmetrically equivalent."""
try: try:
iter(members) # asking for (even empty) list of members? iter(members) # asking for (even empty) list of members?
except TypeError: except TypeError:
return self.__class__(self.lattice.symmetry.symmetryOperations(members)*self.rotation,self.lattice) # no, return rotation object return self.__class__(self.lattice.symmetry.symmetryOperations(members)*self.rotation,self.lattice) # no, return rotation object
else: else:
return [self.__class__(q*self.rotation,self.lattice) \ return [self.__class__(q*self.rotation,self.lattice) \
for q in self.lattice.symmetry.symmetryOperations(members)] # yes, return list of rotations for q in self.lattice.symmetry.symmetryOperations(members)] # yes, return list of rotations
def relatedOrientations(self,model): def relatedOrientations(self,model):
"""List of orientations related by the given orientation relationship.""" """List of orientations related by the given orientation relationship."""
r = self.lattice.relationOperations(model) r = self.lattice.relationOperations(model)
return [self.__class__(o*self.rotation,r['lattice']) for o in r['rotations']] return [self.__class__(o*self.rotation,r['lattice']) for o in r['rotations']]
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."""
for me in self.equivalentOrientations(): for me in self.equivalentOrientations():
if self.lattice.symmetry.inFZ(me.rotation.asRodrigues(vector=True)): break if self.lattice.symmetry.inFZ(me.rotation.asRodrigues(vector=True)): break
return self.__class__(me.rotation,self.lattice) return self.__class__(me.rotation,self.lattice)
def inversePole(self, def inversePole(self,
axis, axis,
proper = False, proper = False,
SST = True): SST = True):
"""Axis rotated according to orientation (using crystal symmetry to ensure location falls into SST).""" """Axis rotated according to orientation (using crystal symmetry to ensure location falls into SST)."""
if SST: # pole requested to be within SST if SST: # pole requested to be within SST
for i,o in enumerate(self.equivalentOrientations()): # test all symmetric equivalent quaternions for i,o in enumerate(self.equivalentOrientations()): # test all symmetric equivalent quaternions
pole = o.rotation*axis # align crystal direction to axis pole = o.rotation*axis # align crystal direction to axis
if self.lattice.symmetry.inSST(pole,proper): break # found SST version if self.lattice.symmetry.inSST(pole,proper): break # found SST version
else: else:
pole = self.rotation*axis # align crystal direction to axis pole = self.rotation*axis # align crystal direction to axis
return (pole,i if SST else 0) return (pole,i if SST else 0)
def IPFcolor(self,axis): def IPFcolor(self,axis):
"""TSL color of inverse pole figure for given axis.""" """TSL color of inverse pole figure for given axis."""
color = np.zeros(3,'d') color = np.zeros(3,'d')
for o in self.equivalentOrientations(): for o in self.equivalentOrientations():
pole = o.rotation*axis # align crystal direction to axis pole = o.rotation*axis # align crystal direction to axis
inSST,color = self.lattice.symmetry.inSST(pole,color=True) inSST,color = self.lattice.symmetry.inSST(pole,color=True)
if inSST: break if inSST: break
return color return color
@staticmethod @staticmethod
def fromAverage(orientations, def fromAverage(orientations,
weights = []): weights = []):
"""Create orientation from average of list of orientations.""" """Create orientation from average of list of orientations."""
if not all(isinstance(item, Orientation) for item in orientations): if not all(isinstance(item, Orientation) for item in orientations):
raise TypeError("Only instances of Orientation can be averaged.") raise TypeError("Only instances of Orientation can be averaged.")
closest = [] closest = []
ref = orientations[0] ref = orientations[0]
for o in orientations: for o in orientations:
closest.append(o.equivalentOrientations( closest.append(o.equivalentOrientations(
ref.disorientation(o, ref.disorientation(o,
SST = False, # select (o[ther]'s) sym orientation SST = False, # select (o[ther]'s) sym orientation
symmetries = True)[2]).rotation) # with lowest misorientation symmetries = True)[2]).rotation) # with lowest misorientation
return Orientation(Rotation.fromAverage(closest,weights),ref.lattice) return Orientation(Rotation.fromAverage(closest,weights),ref.lattice)
def average(self,other): def average(self,other):
"""Calculate the average rotation.""" """Calculate the average rotation."""
return Orientation.fromAverage([self,other]) return Orientation.fromAverage([self,other])

View File

@ -65,7 +65,7 @@ class Result:
self.materialpoints = [m.decode() for m in np.unique(f['mapping/cellResults/materialpoint']['Name'])] self.materialpoints = [m.decode() for m in np.unique(f['mapping/cellResults/materialpoint']['Name'])]
self.constituents = [c.decode() for c in np.unique(f['mapping/cellResults/constituent'] ['Name'])] self.constituents = [c.decode() for c in np.unique(f['mapping/cellResults/constituent'] ['Name'])]
self.con_physics = [] self.con_physics = []
for c in self.constituents: for c in self.constituents:
self.con_physics += f['/'.join([self.increments[0],'constituent',c])].keys() self.con_physics += f['/'.join([self.increments[0],'constituent',c])].keys()
self.con_physics = list(set(self.con_physics)) # make unique self.con_physics = list(set(self.con_physics)) # make unique
@ -75,10 +75,10 @@ class Result:
self.mat_physics += f['/'.join([self.increments[0],'materialpoint',m])].keys() self.mat_physics += f['/'.join([self.increments[0],'materialpoint',m])].keys()
self.mat_physics = list(set(self.mat_physics)) # make unique self.mat_physics = list(set(self.mat_physics)) # make unique
self.selection= {'increments': self.increments, self.selection = {'increments': self.increments,
'constituents': self.constituents,'materialpoints': self.materialpoints, 'constituents': self.constituents,'materialpoints': self.materialpoints,
'con_physics': self.con_physics, 'mat_physics': self.mat_physics 'con_physics': self.con_physics, 'mat_physics': self.mat_physics
} }
self.fname = fname self.fname = fname
@ -129,7 +129,7 @@ class Result:
iterator = map(float,choice) iterator = map(float,choice)
choice = [] choice = []
for c in iterator: for c in iterator:
idx=np.searchsorted(self.times,c) idx = np.searchsorted(self.times,c)
if np.isclose(c,self.times[idx]): if np.isclose(c,self.times[idx]):
choice.append(self.increments[idx]) choice.append(self.increments[idx])
elif np.isclose(c,self.times[idx+1]): elif np.isclose(c,self.times[idx+1]):
@ -141,12 +141,12 @@ class Result:
if action == 'set': if action == 'set':
self.selection[what] = valid self.selection[what] = valid
elif action == 'add': elif action == 'add':
add=existing.union(valid) add = existing.union(valid)
add_sorted=sorted(add, key=lambda x: int("".join([i for i in x if i.isdigit()]))) add_sorted = sorted(add, key=lambda x: int("".join([i for i in x if i.isdigit()])))
self.selection[what] = add_sorted self.selection[what] = add_sorted
elif action == 'del': elif action == 'del':
diff=existing.difference(valid) diff = existing.difference(valid)
diff_sorted=sorted(diff, key=lambda x: int("".join([i for i in x if i.isdigit()]))) diff_sorted = sorted(diff, key=lambda x: int("".join([i for i in x if i.isdigit()])))
self.selection[what] = diff_sorted self.selection[what] = diff_sorted
@ -287,8 +287,8 @@ class Result:
inData[key] = f['mapping/cellResults/materialpoint'][inGeom[key].tolist()]['Position'] inData[key] = f['mapping/cellResults/materialpoint'][inGeom[key].tolist()]['Position']
shape = np.shape(f[path]) shape = np.shape(f[path])
data = np.full((self.Nmaterialpoints,) + (shape[1:] if len(shape)>1 else (1,)), data = np.full((self.Nmaterialpoints,) + (shape[1:] if len(shape)>1 else (1,)),
np.nan, np.nan,
dtype=np.dtype(f[path])) dtype=np.dtype(f[path]))
data[inGeom[key]] = (f[path] if len(shape)>1 else np.expand_dims(f[path],1))[inData[key]] data[inGeom[key]] = (f[path] if len(shape)>1 else np.expand_dims(f[path],1))[inData[key]]
path = (os.path.join(*([prop,name]+([cat] if cat else [])+([item] if item else []))) if split else path)+tag path = (os.path.join(*([prop,name]+([cat] if cat else [])+([item] if item else []))) if split else path)+tag
if split: if split:
@ -350,7 +350,7 @@ class Result:
groups.append(group) groups.append(group)
else: else:
match = [e for e_ in [glob.fnmatch.filter(f[group].keys(),s) for s in sets] for e in e_] match = [e for e_ in [glob.fnmatch.filter(f[group].keys(),s) for s in sets] for e in e_]
if len(set(match)) == len(sets) : groups.append(group) if len(set(match)) == len(sets): groups.append(group)
return groups return groups
@ -359,18 +359,18 @@ class Result:
message = '' message = ''
with h5py.File(self.fname,'r') as f: with h5py.File(self.fname,'r') as f:
for i in self.iterate('increments'): for i in self.iterate('increments'):
message+='\n{} ({}s)\n'.format(i,self.times[self.increments.index(i)]) message += '\n{} ({}s)\n'.format(i,self.times[self.increments.index(i)])
for o,p in zip(['constituents','materialpoints'],['con_physics','mat_physics']): for o,p in zip(['constituents','materialpoints'],['con_physics','mat_physics']):
for oo in self.iterate(o): for oo in self.iterate(o):
message+=' {}\n'.format(oo) message += ' {}\n'.format(oo)
for pp in self.iterate(p): for pp in self.iterate(p):
message+=' {}\n'.format(pp) message += ' {}\n'.format(pp)
group = '/'.join([i,o[:-1],oo,pp]) # o[:-1]: plural/singular issue group = '/'.join([i,o[:-1],oo,pp]) # o[:-1]: plural/singular issue
for d in f[group].keys(): for d in f[group].keys():
try: try:
dataset = f['/'.join([group,d])] dataset = f['/'.join([group,d])]
message+=' {} / ({}): {}\n'.\ message += ' {} / ({}): {}\n'.\
format(d,dataset.attrs['Unit'].decode(),dataset.attrs['Description'].decode()) format(d,dataset.attrs['Unit'].decode(),dataset.attrs['Description'].decode())
except KeyError: except KeyError:
pass pass
return message return message
@ -425,7 +425,7 @@ class Result:
for pa in path: for pa in path:
label = pa.split('/')[2] label = pa.split('/')[2]
if (pa.split('/')[1] == 'geometry'): if pa.split('/')[1] == 'geometry':
dataset = np.array(f[pa]) dataset = np.array(f[pa])
continue continue

View File

@ -365,8 +365,7 @@ class Rotation:
@staticmethod @staticmethod
def fromAverage(rotations, def fromAverage(rotations,weights = None):
weights = []):
""" """
Average rotation. Average rotation.
@ -387,7 +386,7 @@ class Rotation:
raise TypeError("Only instances of Rotation can be averaged.") raise TypeError("Only instances of Rotation can be averaged.")
N = len(rotations) N = len(rotations)
if weights == [] or not weights: if not weights:
weights = np.ones(N,dtype='i') weights = np.ones(N,dtype='i')
for i,(r,n) in enumerate(zip(rotations,weights)): for i,(r,n) in enumerate(zip(rotations,weights)):

View File

@ -327,9 +327,9 @@ class Table:
seen = set() seen = set()
labels = [] labels = []
for l in [x for x in self.data.columns if not (x in seen or seen.add(x))]: for l in [x for x in self.data.columns if not (x in seen or seen.add(x))]:
if(self.shapes[l] == (1,)): if self.shapes[l] == (1,):
labels.append('{}'.format(l)) labels.append('{}'.format(l))
elif(len(self.shapes[l]) == 1): elif len(self.shapes[l]) == 1:
labels += ['{}_{}'.format(i+1,l) \ labels += ['{}_{}'.format(i+1,l) \
for i in range(self.shapes[l][0])] for i in range(self.shapes[l][0])]
else: else:

View File

@ -103,7 +103,7 @@ class VTK:
Spatial position of the points. Spatial position of the points.
""" """
vtk_points= vtk.vtkPoints() vtk_points = vtk.vtkPoints()
vtk_points.SetData(np_to_vtk(points)) vtk_points.SetData(np_to_vtk(points))
geom = vtk.vtkPolyData() geom = vtk.vtkPolyData()
@ -168,11 +168,11 @@ class VTK:
Filename for writing. Filename for writing.
""" """
if (isinstance(self.geom,vtk.vtkRectilinearGrid)): if isinstance(self.geom,vtk.vtkRectilinearGrid):
writer = vtk.vtkXMLRectilinearGridWriter() writer = vtk.vtkXMLRectilinearGridWriter()
elif(isinstance(self.geom,vtk.vtkUnstructuredGrid)): elif isinstance(self.geom,vtk.vtkUnstructuredGrid):
writer = vtk.vtkXMLUnstructuredGridWriter() writer = vtk.vtkXMLUnstructuredGridWriter()
elif(isinstance(self.geom,vtk.vtkPolyData)): elif isinstance(self.geom,vtk.vtkPolyData):
writer = vtk.vtkXMLPolyDataWriter() writer = vtk.vtkXMLPolyDataWriter()
default_ext = writer.GetDefaultFileExtension() default_ext = writer.GetDefaultFileExtension()
@ -234,17 +234,17 @@ class VTK:
ren = vtk.vtkRenderer() ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow() window = vtk.vtkRenderWindow()
renWin.AddRenderer(ren) window.AddRenderer(ren)
ren.AddActor(actor) ren.AddActor(actor)
ren.SetBackground(0.2,0.2,0.2) ren.SetBackground(0.2,0.2,0.2)
renWin.SetSize(Environment().screen_width,Environment().screen_height) window.SetSize(Environment().screen_width,Environment().screen_height)
iren = vtk.vtkRenderWindowInteractor() iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin) iren.SetRenderWindow(window)
iren.Initialize() iren.Initialize()
renWin.Render() window.Render()
iren.Start() iren.Start()