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
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):
"""Report lattice type and orientation."""
return self.lattice.__repr__()+'\n'+self.rotation.__repr__()
def __repr__(self):
"""Report lattice type and orientation."""
return self.lattice.__repr__()+'\n'+self.rotation.__repr__()
def __init__(self, rotation, lattice):
"""
New orientation from rotation and lattice.
def __init__(self, rotation, lattice):
"""
New orientation from rotation and lattice.
Parameters
----------
rotation : Rotation
Rotation specifying the lattice orientation.
lattice : Lattice
Lattice type of the crystal.
Parameters
----------
rotation : Rotation
Rotation specifying the lattice orientation.
lattice : Lattice
Lattice type of the crystal.
"""
if isinstance(lattice, Lattice):
self.lattice = lattice
else:
self.lattice = Lattice(lattice) # assume string
"""
if isinstance(lattice, Lattice):
self.lattice = lattice
else:
self.lattice = Lattice(lattice) # assume string
if isinstance(rotation, Rotation):
self.rotation = rotation
else:
self.rotation = Rotation.fromQuaternion(rotation) # assume quaternion
if isinstance(rotation, Rotation):
self.rotation = rotation
else:
self.rotation = Rotation.fromQuaternion(rotation) # assume quaternion
def disorientation(self,
other,
SST = True,
symmetries = False):
"""
Disorientation between myself and given other orientation.
def disorientation(self,
other,
SST = True,
symmetries = False):
"""
Disorientation between myself and given other orientation.
Rotation axis falls into SST if SST == True.
(Currently requires same symmetry for both orientations.
Look into A. Heinz and P. Neumann 1991 for cases with differing sym.)
"""
if self.lattice.symmetry != other.lattice.symmetry:
raise NotImplementedError('disorientation between different symmetry classes not supported yet.')
Rotation axis falls into SST if SST == True.
(Currently requires same symmetry for both orientations.
Look into A. Heinz and P. Neumann 1991 for cases with differing sym.)
"""
if self.lattice.symmetry != other.lattice.symmetry:
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
otherSymEqs = other.equivalentOrientations()
mySymEqs = self.equivalentOrientations() if SST else self.equivalentOrientations([0]) # take all or only first sym operation
otherSymEqs = other.equivalentOrientations()
for i,sA in enumerate(mySymEqs):
aInv = sA.rotation.inversed()
for j,sB in enumerate(otherSymEqs):
b = sB.rotation
r = b*aInv
for k in range(2):
r.inverse()
breaker = self.lattice.symmetry.inFZ(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
for i,sA in enumerate(mySymEqs):
aInv = sA.rotation.inversed()
for j,sB in enumerate(otherSymEqs):
b = sB.rotation
r = b*aInv
for k in range(2):
r.inverse()
breaker = self.lattice.symmetry.inFZ(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
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,
# self-->other: True, self<--other: False
def inFZ(self):
return self.lattice.symmetry.inFZ(self.rotation.asRodrigues(vector=True))
def inFZ(self):
return self.lattice.symmetry.inFZ(self.rotation.asRodrigues(vector=True))
def equivalentOrientations(self,members=[]):
"""List of orientations which are symmetrically equivalent."""
try:
iter(members) # asking for (even empty) list of members?
except TypeError:
return self.__class__(self.lattice.symmetry.symmetryOperations(members)*self.rotation,self.lattice) # no, return rotation object
else:
return [self.__class__(q*self.rotation,self.lattice) \
for q in self.lattice.symmetry.symmetryOperations(members)] # yes, return list of rotations
def equivalentOrientations(self,members=[]):
"""List of orientations which are symmetrically equivalent."""
try:
iter(members) # asking for (even empty) list of members?
except TypeError:
return self.__class__(self.lattice.symmetry.symmetryOperations(members)*self.rotation,self.lattice) # no, return rotation object
else:
return [self.__class__(q*self.rotation,self.lattice) \
for q in self.lattice.symmetry.symmetryOperations(members)] # yes, return list of rotations
def relatedOrientations(self,model):
"""List of orientations related by the given orientation relationship."""
r = self.lattice.relationOperations(model)
return [self.__class__(o*self.rotation,r['lattice']) for o in r['rotations']]
def relatedOrientations(self,model):
"""List of orientations related by the given orientation relationship."""
r = self.lattice.relationOperations(model)
return [self.__class__(o*self.rotation,r['lattice']) for o in r['rotations']]
def reduced(self):
"""Transform orientation to fall into fundamental zone according to symmetry."""
for me in self.equivalentOrientations():
if self.lattice.symmetry.inFZ(me.rotation.asRodrigues(vector=True)): break
def reduced(self):
"""Transform orientation to fall into fundamental zone according to symmetry."""
for me in self.equivalentOrientations():
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,
axis,
proper = False,
SST = True):
"""Axis rotated according to orientation (using crystal symmetry to ensure location falls into SST)."""
if SST: # pole requested to be within SST
for i,o in enumerate(self.equivalentOrientations()): # test all symmetric equivalent quaternions
pole = o.rotation*axis # align crystal direction to axis
if self.lattice.symmetry.inSST(pole,proper): break # found SST version
else:
pole = self.rotation*axis # align crystal direction to axis
def inversePole(self,
axis,
proper = False,
SST = True):
"""Axis rotated according to orientation (using crystal symmetry to ensure location falls into SST)."""
if SST: # pole requested to be within SST
for i,o in enumerate(self.equivalentOrientations()): # test all symmetric equivalent quaternions
pole = o.rotation*axis # align crystal direction to axis
if self.lattice.symmetry.inSST(pole,proper): break # found SST version
else:
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):
"""TSL color of inverse pole figure for given axis."""
color = np.zeros(3,'d')
def IPFcolor(self,axis):
"""TSL color of inverse pole figure for given axis."""
color = np.zeros(3,'d')
for o in self.equivalentOrientations():
pole = o.rotation*axis # align crystal direction to axis
inSST,color = self.lattice.symmetry.inSST(pole,color=True)
if inSST: break
for o in self.equivalentOrientations():
pole = o.rotation*axis # align crystal direction to axis
inSST,color = self.lattice.symmetry.inSST(pole,color=True)
if inSST: break
return color
return color
@staticmethod
def fromAverage(orientations,
weights = []):
"""Create orientation from average of list of orientations."""
if not all(isinstance(item, Orientation) for item in orientations):
raise TypeError("Only instances of Orientation can be averaged.")
@staticmethod
def fromAverage(orientations,
weights = []):
"""Create orientation from average of list of orientations."""
if not all(isinstance(item, Orientation) for item in orientations):
raise TypeError("Only instances of Orientation can be averaged.")
closest = []
ref = orientations[0]
for o in orientations:
closest.append(o.equivalentOrientations(
ref.disorientation(o,
SST = False, # select (o[ther]'s) sym orientation
symmetries = True)[2]).rotation) # with lowest misorientation
closest = []
ref = orientations[0]
for o in orientations:
closest.append(o.equivalentOrientations(
ref.disorientation(o,
SST = False, # select (o[ther]'s) sym orientation
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):
"""Calculate the average rotation."""
return Orientation.fromAverage([self,other])
def average(self,other):
"""Calculate the average rotation."""
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.constituents = [c.decode() for c in np.unique(f['mapping/cellResults/constituent'] ['Name'])]
self.con_physics = []
self.con_physics = []
for c in self.constituents:
self.con_physics += f['/'.join([self.increments[0],'constituent',c])].keys()
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 = list(set(self.mat_physics)) # make unique
self.selection= {'increments': self.increments,
'constituents': self.constituents,'materialpoints': self.materialpoints,
'con_physics': self.con_physics, 'mat_physics': self.mat_physics
}
self.selection = {'increments': self.increments,
'constituents': self.constituents,'materialpoints': self.materialpoints,
'con_physics': self.con_physics, 'mat_physics': self.mat_physics
}
self.fname = fname
@ -129,7 +129,7 @@ class Result:
iterator = map(float,choice)
choice = []
for c in iterator:
idx=np.searchsorted(self.times,c)
idx = np.searchsorted(self.times,c)
if np.isclose(c,self.times[idx]):
choice.append(self.increments[idx])
elif np.isclose(c,self.times[idx+1]):
@ -141,12 +141,12 @@ class Result:
if action == 'set':
self.selection[what] = valid
elif action == 'add':
add=existing.union(valid)
add_sorted=sorted(add, key=lambda x: int("".join([i for i in x if i.isdigit()])))
add = existing.union(valid)
add_sorted = sorted(add, key=lambda x: int("".join([i for i in x if i.isdigit()])))
self.selection[what] = add_sorted
elif action == 'del':
diff=existing.difference(valid)
diff_sorted=sorted(diff, key=lambda x: int("".join([i for i in x if i.isdigit()])))
diff = existing.difference(valid)
diff_sorted = sorted(diff, key=lambda x: int("".join([i for i in x if i.isdigit()])))
self.selection[what] = diff_sorted
@ -287,8 +287,8 @@ class Result:
inData[key] = f['mapping/cellResults/materialpoint'][inGeom[key].tolist()]['Position']
shape = np.shape(f[path])
data = np.full((self.Nmaterialpoints,) + (shape[1:] if len(shape)>1 else (1,)),
np.nan,
dtype=np.dtype(f[path]))
np.nan,
dtype=np.dtype(f[path]))
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
if split:
@ -350,7 +350,7 @@ class Result:
groups.append(group)
else:
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
@ -359,18 +359,18 @@ class Result:
message = ''
with h5py.File(self.fname,'r') as f:
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 oo in self.iterate(o):
message+=' {}\n'.format(oo)
message += ' {}\n'.format(oo)
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
for d in f[group].keys():
try:
dataset = f['/'.join([group,d])]
message+=' {} / ({}): {}\n'.\
format(d,dataset.attrs['Unit'].decode(),dataset.attrs['Description'].decode())
message += ' {} / ({}): {}\n'.\
format(d,dataset.attrs['Unit'].decode(),dataset.attrs['Description'].decode())
except KeyError:
pass
return message
@ -425,7 +425,7 @@ class Result:
for pa in path:
label = pa.split('/')[2]
if (pa.split('/')[1] == 'geometry'):
if pa.split('/')[1] == 'geometry':
dataset = np.array(f[pa])
continue

View File

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

View File

@ -327,9 +327,9 @@ class Table:
seen = set()
labels = []
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))
elif(len(self.shapes[l]) == 1):
elif len(self.shapes[l]) == 1:
labels += ['{}_{}'.format(i+1,l) \
for i in range(self.shapes[l][0])]
else:

View File

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