Python 3.8 magic: The walrus operator ":="
This commit is contained in:
parent
6fe6be7a34
commit
609f13c590
|
@ -266,9 +266,7 @@ class Colormap(mpl.colors.ListedColormap):
|
|||
l,r = (field[mask].min(),field[mask].max()) if bounds is None else \
|
||||
(bounds[0],bounds[1])
|
||||
|
||||
delta,avg = r-l,0.5*abs(r+l)
|
||||
|
||||
if abs(delta) * 1e8 <= avg: # delta is similar to numerical noise
|
||||
if abs(delta := r-l) * 1e8 <= (avg := 0.5*abs(r+l)): # 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
|
||||
|
||||
return Image.fromarray(
|
||||
|
|
|
@ -234,8 +234,7 @@ class Grid:
|
|||
content = f.readlines()
|
||||
for i,line in enumerate(content[:header_length]):
|
||||
items = line.split('#')[0].lower().strip().split()
|
||||
key = items[0] if items else ''
|
||||
if key == 'grid':
|
||||
if (key := items[0] if items else '') == 'grid':
|
||||
cells = np.array([ int(dict(zip(items[1::2],items[2::2]))[i]) for i in ['a','b','c']])
|
||||
elif key == 'size':
|
||||
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
|
||||
i = 0
|
||||
for line in content[header_length:]:
|
||||
items = line.split('#')[0].split()
|
||||
if len(items) == 3:
|
||||
if len(items := line.split('#')[0].split()) == 3:
|
||||
if items[1].lower() == 'of':
|
||||
material_entry = np.ones(int(items[0]))*float(items[2])
|
||||
elif items[1].lower() == 'to':
|
||||
|
@ -813,8 +811,7 @@ class Grid:
|
|||
# materials: 1
|
||||
|
||||
"""
|
||||
valid = ['x','y','z']
|
||||
if not set(directions).issubset(valid):
|
||||
if not set(directions).issubset(valid := ['x', 'y', 'z']):
|
||||
raise ValueError(f'invalid direction {set(directions).difference(valid)} specified')
|
||||
|
||||
limits: Sequence[Optional[int]] = [None,None] if reflect else [-2,0]
|
||||
|
@ -852,8 +849,7 @@ class Grid:
|
|||
Updated grid-based geometry.
|
||||
|
||||
"""
|
||||
valid = ['x','y','z']
|
||||
if not set(directions).issubset(valid):
|
||||
if not set(directions).issubset(valid := ['x', 'y', 'z']):
|
||||
raise ValueError(f'invalid direction {set(directions).difference(valid)} specified')
|
||||
|
||||
|
||||
|
@ -1190,8 +1186,7 @@ class Grid:
|
|||
VTK-based geometry of grain boundary network.
|
||||
|
||||
"""
|
||||
valid = ['x','y','z']
|
||||
if not set(directions).issubset(valid):
|
||||
if not set(directions).issubset(valid := ['x', 'y', 'z']):
|
||||
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)],
|
||||
|
|
|
@ -319,8 +319,7 @@ class Table:
|
|||
data = np.loadtxt(content)
|
||||
|
||||
shapes = {'eu':3, 'pos':2, 'IQ':1, 'CI':1, 'ID':1, 'intensity':1, 'fit':1}
|
||||
remainder = data.shape[1]-sum(shapes.values())
|
||||
if remainder > 0: # 3.8 can do: if (remainder := data.shape[1]-sum(shapes.values())) > 0
|
||||
if (remainder := data.shape[1]-sum(shapes.values())) > 0:
|
||||
shapes['unknown'] = remainder
|
||||
|
||||
return Table(data,shapes,comments)
|
||||
|
@ -376,8 +375,7 @@ class Table:
|
|||
"""
|
||||
dup = self.copy()
|
||||
dup._add_comment(label, data.shape[1:], info)
|
||||
m = re.match(r'(.*)\[((\d+,)*(\d+))\]',label)
|
||||
if m:
|
||||
if m := re.match(r'(.*)\[((\d+,)*(\d+))\]',label):
|
||||
key = m.group(1)
|
||||
idx = np.ravel_multi_index(tuple(map(int,m.group(2).split(","))),
|
||||
self.shapes[key])
|
||||
|
@ -495,8 +493,7 @@ class Table:
|
|||
"""
|
||||
labels_ = [labels] if isinstance(labels,str) else labels.copy()
|
||||
for i,l in enumerate(labels_):
|
||||
m = re.match(r'(.*)\[((\d+,)*(\d+))\]',l)
|
||||
if m:
|
||||
if m := re.match(r'(.*)\[((\d+,)*(\d+))\]',l):
|
||||
idx = np.ravel_multi_index(tuple(map(int,m.group(2).split(','))),
|
||||
self.shapes[m.group(1)])
|
||||
labels_[i] = f'{1+idx}_{m.group(1)}'
|
||||
|
|
|
@ -22,7 +22,7 @@ class VTK:
|
|||
High-level interface to VTK.
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
def __init__(self,
|
||||
vtk_data: vtk.vtkDataSet):
|
||||
"""
|
||||
New spatial visualization.
|
||||
|
@ -202,8 +202,7 @@ class VTK:
|
|||
"""
|
||||
if not os.path.isfile(fname): # vtk has a strange error handling
|
||||
raise FileNotFoundError(f'No such file: {fname}')
|
||||
ext = Path(fname).suffix
|
||||
if ext == '.vtk' or dataset_type is not None:
|
||||
if (ext := Path(fname).suffix) == '.vtk' or dataset_type is not None:
|
||||
reader = vtk.vtkGenericDataObjectReader()
|
||||
reader.SetFileName(str(fname))
|
||||
if dataset_type is None:
|
||||
|
|
|
@ -92,10 +92,9 @@ def from_Poisson_disc(size: _FloatSequence,
|
|||
tree = _spatial.cKDTree(coords[:s],boxsize=size) if periodic else \
|
||||
_spatial.cKDTree(coords[:s])
|
||||
distances = tree.query(candidates)[0]
|
||||
best = distances.argmax()
|
||||
if distances[best] > distance: # require minimum separation
|
||||
if distances.max() > distance: # require minimum separation
|
||||
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
|
||||
progress.update(s)
|
||||
|
||||
|
|
|
@ -66,8 +66,7 @@ def eigenvectors(T_sym: _np.ndarray,
|
|||
"""
|
||||
(u,v) = _np.linalg.eigh(symmetric(T_sym))
|
||||
|
||||
if RHS:
|
||||
v[_np.linalg.det(v) < 0.0,:,2] *= -1.0
|
||||
if RHS: v[_np.linalg.det(v) < 0.0,:,2] *= -1.0
|
||||
return v
|
||||
|
||||
|
||||
|
|
|
@ -753,9 +753,8 @@ class ProgressBar:
|
|||
iteration: int) -> None:
|
||||
|
||||
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):
|
||||
self.time_last_update = datetime.datetime.now()
|
||||
bar = '█' * filled_length + '░' * (self.bar_length - filled_length)
|
||||
|
|
Loading…
Reference in New Issue