From 609f13c590ea29c0ce835e023d468767be94b8cb Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 29 Jan 2022 18:16:19 +0100 Subject: [PATCH] Python 3.8 magic: The walrus operator ":=" --- python/damask/_colormap.py | 4 +--- python/damask/_grid.py | 15 +++++---------- python/damask/_table.py | 9 +++------ python/damask/_vtk.py | 5 ++--- python/damask/seeds.py | 5 ++--- python/damask/tensor.py | 3 +-- python/damask/util.py | 3 +-- 7 files changed, 15 insertions(+), 29 deletions(-) diff --git a/python/damask/_colormap.py b/python/damask/_colormap.py index 5c77cf61e..e7982ec52 100644 --- a/python/damask/_colormap.py +++ b/python/damask/_colormap.py @@ -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( diff --git a/python/damask/_grid.py b/python/damask/_grid.py index b188873a4..639b4e91f 100644 --- a/python/damask/_grid.py +++ b/python/damask/_grid.py @@ -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)], diff --git a/python/damask/_table.py b/python/damask/_table.py index 44a04b40a..bd82dc134 100644 --- a/python/damask/_table.py +++ b/python/damask/_table.py @@ -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)}' diff --git a/python/damask/_vtk.py b/python/damask/_vtk.py index 601608520..8247bb6c8 100644 --- a/python/damask/_vtk.py +++ b/python/damask/_vtk.py @@ -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: diff --git a/python/damask/seeds.py b/python/damask/seeds.py index 1a3af7a64..47e34d871 100644 --- a/python/damask/seeds.py +++ b/python/damask/seeds.py @@ -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) diff --git a/python/damask/tensor.py b/python/damask/tensor.py index 73cdd7400..0e2118002 100644 --- a/python/damask/tensor.py +++ b/python/damask/tensor.py @@ -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 diff --git a/python/damask/util.py b/python/damask/util.py index e1db35007..c042e4dd4 100644 --- a/python/damask/util.py +++ b/python/damask/util.py @@ -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)