From 56c33b8a5ce2b0efe2168022825554bb2b4f1552 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Fri, 11 Mar 2022 20:07:18 -0500 Subject: [PATCH] flipped VTK.add to use (label,data) to be consistent with other functionality --- python/damask/_grid.py | 6 +++--- python/damask/_result.py | 4 ++-- python/damask/_vtk.py | 39 ++++++++++++++++++++++++++------------- python/tests/test_Grid.py | 2 +- python/tests/test_VTK.py | 28 +++++++++++++++++----------- 5 files changed, 49 insertions(+), 30 deletions(-) diff --git a/python/damask/_grid.py b/python/damask/_grid.py index 733cc3f44..1b184d6e7 100644 --- a/python/damask/_grid.py +++ b/python/damask/_grid.py @@ -662,9 +662,9 @@ class Grid: """ v = VTK.from_image_data(self.cells,self.size,self.origin)\ - .add(self.material.flatten(order='F'),'material') + .add('material',self.material.flatten(order='F')) for label,data in self.ic.items(): - v = v.add(data.flatten(order='F'),label) + v = v.add(label,data.flatten(order='F')) v.comments = self.comments v.save(fname,parallel=False,compress=compress) @@ -713,7 +713,7 @@ class Grid: """ VTK.from_image_data(self.cells,self.size,self.origin) \ - .add(self.material.flatten('F'),'material') \ + .add('material',self.material.flatten('F'),) \ .show('material',colormap) diff --git a/python/damask/_result.py b/python/damask/_result.py index fb6ba2ae2..227685b59 100644 --- a/python/damask/_result.py +++ b/python/damask/_result.py @@ -1621,7 +1621,7 @@ class Result: for inc in util.show_progress(self.visible['increments']): u = _read(f['/'.join([inc,'geometry','u_n' if mode.lower() == 'cell' else 'u_p'])]) - v = v.add(u,'u') + v = v.add('u',u) for ty in ['phase','homogenization']: for field in self.visible['fields']: @@ -1648,7 +1648,7 @@ class Result: outs[out][at_cell_ho[label]] = data[in_data_ho[label]] for label,dataset in outs.items(): - v = v.add(dataset,' / '.join(['/'.join([ty,field,label]),dataset.dtype.metadata['unit']])) + v = v.add(' / '.join(['/'.join([ty,field,label]),dataset.dtype.metadata['unit']]),dataset) v.save(f'{self.fname.stem}_inc{inc[10:].zfill(N_digits)}',parallel=parallel) diff --git a/python/damask/_vtk.py b/python/damask/_vtk.py index f8dce1754..4f2658cd7 100644 --- a/python/damask/_vtk.py +++ b/python/damask/_vtk.py @@ -402,24 +402,32 @@ class VTK: # Check https://blog.kitware.com/ghost-and-blanking-visibility-changes/ for missing data def add(self, - data: Union[np.ndarray, np.ma.MaskedArray, 'Table'], - label: str = None): + label: str = None, + data: Union[np.ndarray, np.ma.MaskedArray] = None, + *, + table: 'Table' = None): """ Add data to either cells or points. + Data can either be a numpy.array, which requires a corresponding label, + or a damask.Table. + Parameters ---------- - data : numpy.ndarray, numpy.ma.MaskedArray, or damask.Table + label : str, optional + Label of data array. + data : numpy.ndarray or numpy.ma.MaskedArray, optional Data to add. First dimension needs to match either number of cells or number of points. - label : str, optional if data is damask.Table - Data label. + table: damask.Table, optional + Data to add. Number of rows needs to match either + number of cells or number of points. """ def _add_array(vtk_data, - data: np.ndarray, - label: str): + label: str, + data: np.ndarray): N_data = data.shape[0] data_ = data.reshape(N_data,-1) \ @@ -441,17 +449,22 @@ class VTK: else: raise ValueError(f'data count mismatch ({N_data} ≠ {self.N_points} & {self.N_cells})') + if data is None and table is None: + raise KeyError('no data given') + if data is not None and table is not None: + raise KeyError('cannot use both, data and table') + dup = self.copy() if isinstance(data,np.ndarray): if label is not None: _add_array(dup.vtk_data, - np.where(data.mask,data.fill_value,data) if isinstance(data,np.ma.MaskedArray) else data, - label) + label, + np.where(data.mask,data.fill_value,data) if isinstance(data,np.ma.MaskedArray) else data) else: - raise ValueError('no label defined for numpy.ndarray') - elif isinstance(data,Table): - for l in data.labels: - _add_array(dup.vtk_data,data.get(l),l) + raise ValueError('no label defined for data') + elif isinstance(table,Table): + for l in table.labels: + _add_array(dup.vtk_data,l,table.get(l)) else: raise TypeError diff --git a/python/tests/test_Grid.py b/python/tests/test_Grid.py index 3ac8bcb6c..eedf05ae6 100644 --- a/python/tests/test_Grid.py +++ b/python/tests/test_Grid.py @@ -58,7 +58,7 @@ class TestGrid: def test_repr(self,default): print(default) - def test_read_write_vtr(self,default,tmp_path): + def test_read_write_vti(self,default,tmp_path): default.save(tmp_path/'default') new = Grid.load(tmp_path/'default.vti') assert new == default diff --git a/python/tests/test_VTK.py b/python/tests/test_VTK.py index 4b0f9aa20..44226bf44 100644 --- a/python/tests/test_VTK.py +++ b/python/tests/test_VTK.py @@ -147,16 +147,22 @@ class TestVTK: def test_invalid_add_shape(self,default): with pytest.raises(ValueError): - default.add(np.ones(3),'valid') + default.add('valid',np.ones(3)) def test_invalid_add_missing_label(self,default): data = np.random.randint(9,size=np.prod(np.array(default.vtk_data.GetDimensions())-1)) with pytest.raises(ValueError): - default.add(data) + default.add(data=data) def test_invalid_add_type(self,default): with pytest.raises(TypeError): - default.add('invalid_type','valid') + default.add(label='valid',data='invalid_type') + with pytest.raises(TypeError): + default.add(label='valid',table='invalid_type') + + def test_invalid_add_dual(self,default): + with pytest.raises(KeyError): + default.add(label='valid',data=0,table=0) @pytest.mark.parametrize('data_type,shape',[(float,(3,)), (float,(3,3)), @@ -166,7 +172,7 @@ class TestVTK: @pytest.mark.parametrize('N_values',[5*6*7,6*7*8]) def test_add_get(self,default,data_type,shape,N_values): data = np.squeeze(np.random.randint(0,100,(N_values,)+shape)).astype(data_type) - new = default.add(data,'data') + new = default.add('data',data) assert (np.squeeze(data.reshape(N_values,-1)) == new.get('data')).all() @@ -179,7 +185,7 @@ class TestVTK: for k,s in shapes.items(): d[k] = dict(shape = s, data = np.random.random(N*np.prod(s)).reshape((N,-1))) - new = default.add(Table(shapes,np.column_stack([d[k]['data'] for k in shapes.keys()]))) + new = default.add(table=Table(shapes,np.column_stack([d[k]['data'] for k in shapes.keys()]))) for k,s in shapes.items(): assert np.allclose(np.squeeze(d[k]['data']),new.get(k),rtol=1e-7) @@ -187,8 +193,8 @@ class TestVTK: def test_add_masked(self,default): data = np.random.rand(5*6*7,3) masked = ma.MaskedArray(data,mask=data<.4,fill_value=42.) - mask_auto = default.add(masked,'D') - mask_manual = default.add(np.where(masked.mask,masked.fill_value,masked),'D') + mask_auto = default.add('D',masked) + mask_manual = default.add('D',np.where(masked.mask,masked.fill_value,masked)) assert mask_manual == mask_auto @@ -202,7 +208,7 @@ class TestVTK: data = np.squeeze(np.random.randint(0,100,(N_values,)+shape)).astype(data_type) ALPHABET = np.array(list(string.ascii_lowercase + ' ')) label = ''.join(np.random.choice(ALPHABET, size=10)) - new = default.add(data,label) + new = default.add(label,data) if N_values == default.N_points: assert label in new.labels['Point Data'] if N_values == default.N_cells: assert label in new.labels['Cell Data'] @@ -217,7 +223,7 @@ class TestVTK: @pytest.mark.xfail(int(vtk.vtkVersion.GetVTKVersion().split('.')[0])<8, reason='missing METADATA') def test_compare_reference_polyData(self,update,ref_path,tmp_path): points=np.dstack((np.linspace(0.,1.,10),np.linspace(0.,2.,10),np.linspace(-1.,1.,10))).squeeze() - polyData = VTK.from_poly_data(points).add(points,'coordinates') + polyData = VTK.from_poly_data(points).add('coordinates',points) if update: polyData.save(ref_path/'polyData') else: @@ -234,8 +240,8 @@ class TestVTK: c = coords[:-1,:-1,:-1,:].reshape(-1,3,order='F') n = coords[:,:,:,:].reshape(-1,3,order='F') rectilinearGrid = VTK.from_rectilinear_grid(grid) \ - .add(np.ascontiguousarray(c),'cell') \ - .add(np.ascontiguousarray(n),'node') + .add('cell',np.ascontiguousarray(c)) \ + .add('node',np.ascontiguousarray(n)) if update: rectilinearGrid.save(ref_path/'rectilinearGrid') else: