Python 3.8 magic: The walrus operator ":="

This commit is contained in:
Martin Diehl 2022-01-29 18:16:19 +01:00
parent 6fe6be7a34
commit 609f13c590
7 changed files with 15 additions and 29 deletions

View File

@ -266,9 +266,7 @@ class Colormap(mpl.colors.ListedColormap):
l,r = (field[mask].min(),field[mask].max()) if bounds is None else \ l,r = (field[mask].min(),field[mask].max()) if bounds is None else \
(bounds[0],bounds[1]) (bounds[0],bounds[1])
delta,avg = r-l,0.5*abs(r+l) if abs(delta := r-l) * 1e8 <= (avg := 0.5*abs(r+l)): # delta is similar to numerical noise
if abs(delta) * 1e8 <= avg: # delta is similar to numerical noise
l,r = l-0.5*avg*np.sign(delta),r+0.5*avg*np.sign(delta), # extend range to have actual data centered within l,r = l-0.5*avg*np.sign(delta),r+0.5*avg*np.sign(delta), # extend range to have actual data centered within
return Image.fromarray( return Image.fromarray(

View File

@ -234,8 +234,7 @@ class Grid:
content = f.readlines() content = f.readlines()
for i,line in enumerate(content[:header_length]): for i,line in enumerate(content[:header_length]):
items = line.split('#')[0].lower().strip().split() items = line.split('#')[0].lower().strip().split()
key = items[0] if items else '' if (key := items[0] if items else '') == 'grid':
if key == 'grid':
cells = np.array([ int(dict(zip(items[1::2],items[2::2]))[i]) for i in ['a','b','c']]) cells = np.array([ int(dict(zip(items[1::2],items[2::2]))[i]) for i in ['a','b','c']])
elif key == 'size': elif key == 'size':
size = np.array([float(dict(zip(items[1::2],items[2::2]))[i]) for i in ['x','y','z']]) size = np.array([float(dict(zip(items[1::2],items[2::2]))[i]) for i in ['x','y','z']])
@ -247,8 +246,7 @@ class Grid:
material = np.empty(int(cells.prod())) # initialize as flat array material = np.empty(int(cells.prod())) # initialize as flat array
i = 0 i = 0
for line in content[header_length:]: for line in content[header_length:]:
items = line.split('#')[0].split() if len(items := line.split('#')[0].split()) == 3:
if len(items) == 3:
if items[1].lower() == 'of': if items[1].lower() == 'of':
material_entry = np.ones(int(items[0]))*float(items[2]) material_entry = np.ones(int(items[0]))*float(items[2])
elif items[1].lower() == 'to': elif items[1].lower() == 'to':
@ -813,8 +811,7 @@ class Grid:
# materials: 1 # materials: 1
""" """
valid = ['x','y','z'] if not set(directions).issubset(valid := ['x', 'y', 'z']):
if not set(directions).issubset(valid):
raise ValueError(f'invalid direction {set(directions).difference(valid)} specified') raise ValueError(f'invalid direction {set(directions).difference(valid)} specified')
limits: Sequence[Optional[int]] = [None,None] if reflect else [-2,0] limits: Sequence[Optional[int]] = [None,None] if reflect else [-2,0]
@ -852,8 +849,7 @@ class Grid:
Updated grid-based geometry. Updated grid-based geometry.
""" """
valid = ['x','y','z'] if not set(directions).issubset(valid := ['x', 'y', 'z']):
if not set(directions).issubset(valid):
raise ValueError(f'invalid direction {set(directions).difference(valid)} specified') raise ValueError(f'invalid direction {set(directions).difference(valid)} specified')
@ -1190,8 +1186,7 @@ class Grid:
VTK-based geometry of grain boundary network. VTK-based geometry of grain boundary network.
""" """
valid = ['x','y','z'] if not set(directions).issubset(valid := ['x', 'y', 'z']):
if not set(directions).issubset(valid):
raise ValueError(f'invalid direction {set(directions).difference(valid)} specified') raise ValueError(f'invalid direction {set(directions).difference(valid)} specified')
o = [[0, self.cells[0]+1, np.prod(self.cells[:2]+1)+self.cells[0]+1, np.prod(self.cells[:2]+1)], o = [[0, self.cells[0]+1, np.prod(self.cells[:2]+1)+self.cells[0]+1, np.prod(self.cells[:2]+1)],

View File

@ -319,8 +319,7 @@ class Table:
data = np.loadtxt(content) data = np.loadtxt(content)
shapes = {'eu':3, 'pos':2, 'IQ':1, 'CI':1, 'ID':1, 'intensity':1, 'fit':1} shapes = {'eu':3, 'pos':2, 'IQ':1, 'CI':1, 'ID':1, 'intensity':1, 'fit':1}
remainder = data.shape[1]-sum(shapes.values()) if (remainder := data.shape[1]-sum(shapes.values())) > 0:
if remainder > 0: # 3.8 can do: if (remainder := data.shape[1]-sum(shapes.values())) > 0
shapes['unknown'] = remainder shapes['unknown'] = remainder
return Table(data,shapes,comments) return Table(data,shapes,comments)
@ -376,8 +375,7 @@ class Table:
""" """
dup = self.copy() dup = self.copy()
dup._add_comment(label, data.shape[1:], info) dup._add_comment(label, data.shape[1:], info)
m = re.match(r'(.*)\[((\d+,)*(\d+))\]',label) if m := re.match(r'(.*)\[((\d+,)*(\d+))\]',label):
if m:
key = m.group(1) key = m.group(1)
idx = np.ravel_multi_index(tuple(map(int,m.group(2).split(","))), idx = np.ravel_multi_index(tuple(map(int,m.group(2).split(","))),
self.shapes[key]) self.shapes[key])
@ -495,8 +493,7 @@ class Table:
""" """
labels_ = [labels] if isinstance(labels,str) else labels.copy() labels_ = [labels] if isinstance(labels,str) else labels.copy()
for i,l in enumerate(labels_): for i,l in enumerate(labels_):
m = re.match(r'(.*)\[((\d+,)*(\d+))\]',l) if m := re.match(r'(.*)\[((\d+,)*(\d+))\]',l):
if m:
idx = np.ravel_multi_index(tuple(map(int,m.group(2).split(','))), idx = np.ravel_multi_index(tuple(map(int,m.group(2).split(','))),
self.shapes[m.group(1)]) self.shapes[m.group(1)])
labels_[i] = f'{1+idx}_{m.group(1)}' labels_[i] = f'{1+idx}_{m.group(1)}'

View File

@ -22,7 +22,7 @@ class VTK:
High-level interface to VTK. High-level interface to VTK.
""" """
def __init__(self, def __init__(self,
vtk_data: vtk.vtkDataSet): vtk_data: vtk.vtkDataSet):
""" """
New spatial visualization. New spatial visualization.
@ -202,8 +202,7 @@ class VTK:
""" """
if not os.path.isfile(fname): # vtk has a strange error handling if not os.path.isfile(fname): # vtk has a strange error handling
raise FileNotFoundError(f'No such file: {fname}') raise FileNotFoundError(f'No such file: {fname}')
ext = Path(fname).suffix if (ext := Path(fname).suffix) == '.vtk' or dataset_type is not None:
if ext == '.vtk' or dataset_type is not None:
reader = vtk.vtkGenericDataObjectReader() reader = vtk.vtkGenericDataObjectReader()
reader.SetFileName(str(fname)) reader.SetFileName(str(fname))
if dataset_type is None: if dataset_type is None:

View File

@ -92,10 +92,9 @@ def from_Poisson_disc(size: _FloatSequence,
tree = _spatial.cKDTree(coords[:s],boxsize=size) if periodic else \ tree = _spatial.cKDTree(coords[:s],boxsize=size) if periodic else \
_spatial.cKDTree(coords[:s]) _spatial.cKDTree(coords[:s])
distances = tree.query(candidates)[0] distances = tree.query(candidates)[0]
best = distances.argmax() if distances.max() > distance: # require minimum separation
if distances[best] > distance: # require minimum separation
i = 0 i = 0
coords[s] = candidates[best] # maximum separation to existing point cloud coords[s] = candidates[distances.argmax()] # maximum separation to existing point cloud
s += 1 s += 1
progress.update(s) progress.update(s)

View File

@ -66,8 +66,7 @@ def eigenvectors(T_sym: _np.ndarray,
""" """
(u,v) = _np.linalg.eigh(symmetric(T_sym)) (u,v) = _np.linalg.eigh(symmetric(T_sym))
if RHS: if RHS: v[_np.linalg.det(v) < 0.0,:,2] *= -1.0
v[_np.linalg.det(v) < 0.0,:,2] *= -1.0
return v return v

View File

@ -753,9 +753,8 @@ class ProgressBar:
iteration: int) -> None: iteration: int) -> None:
fraction = (iteration+1) / self.total fraction = (iteration+1) / self.total
filled_length = int(self.bar_length * fraction)
if filled_length > int(self.bar_length * self.fraction_last) or \ if filled_length := int(self.bar_length * fraction) > int(self.bar_length * self.fraction_last) or \
datetime.datetime.now() - self.time_last_update > datetime.timedelta(seconds=10): datetime.datetime.now() - self.time_last_update > datetime.timedelta(seconds=10):
self.time_last_update = datetime.datetime.now() self.time_last_update = datetime.datetime.now()
bar = '' * filled_length + '' * (self.bar_length - filled_length) bar = '' * filled_length + '' * (self.bar_length - filled_length)