table.__init__ now has common order of arguments (label, data)

This commit is contained in:
Martin Diehl 2022-03-11 22:31:35 +01:00
parent c5c2763e1f
commit 0d22cfb83d
7 changed files with 36 additions and 33 deletions

@ -1 +1 @@
Subproject commit 9c1f83babb7894bfaa16255d6c15a4a438c7f168 Subproject commit 317345ab8fffbb120630846a47ab25922d466e14

View File

@ -373,7 +373,7 @@ class Colormap(mpl.colors.ListedColormap):
""" """
labels = {'RGBA':4} if self.colors.shape[1] == 4 else {'RGB': 3} labels = {'RGBA':4} if self.colors.shape[1] == 4 else {'RGB': 3}
t = Table(self.colors,labels,f'Creator: {util.execution_stamp("Colormap")}') t = Table(labels,self.colors,f'Creator: {util.execution_stamp("Colormap")}')
t.save(self._get_file_handle(fname,'.txt')) t.save(self._get_file_handle(fname,'.txt'))

View File

@ -13,26 +13,27 @@ class Table:
"""Manipulate multi-dimensional spreadsheet-like data.""" """Manipulate multi-dimensional spreadsheet-like data."""
def __init__(self, def __init__(self,
data: np.ndarray,
shapes: dict, shapes: dict,
data: np.ndarray,
comments: Union[str, list] = None): comments: Union[str, list] = None):
""" """
New spreadsheet. New spreadsheet.
Parameters Parameters
---------- ----------
data : numpy.ndarray or pandas.DataFrame
Data. Column labels from a pandas.DataFrame will be replaced.
shapes : dict with str:tuple pairs shapes : dict with str:tuple pairs
Shapes of the columns. Example 'F':(3,3) for a deformation gradient. Shapes of the data columns.
For instance, 'F':(3,3) for a deformation gradient, or 'r':(1,) for a scalar.
data : numpy.ndarray or pandas.DataFrame
Data. Existing column labels of a pandas.DataFrame will be replaced.
comments : str or iterable of str, optional comments : str or iterable of str, optional
Additional, human-readable information. Additional, human-readable information.
""" """
comments_ = [comments] if isinstance(comments,str) else comments comments_ = [comments] if isinstance(comments,str) else comments
self.comments = [] if comments_ is None else [c for c in comments_] self.comments = [] if comments_ is None else [c for c in comments_]
self.data = pd.DataFrame(data=data)
self.shapes = { k:(v,) if isinstance(v,(np.int64,np.int32,int)) else v for k,v in shapes.items() } self.shapes = { k:(v,) if isinstance(v,(np.int64,np.int32,int)) else v for k,v in shapes.items() }
self.data = pd.DataFrame(data=data)
self._relabel('uniform') self._relabel('uniform')
@ -70,8 +71,8 @@ class Table:
-------- --------
>>> import damask >>> import damask
>>> import numpy as np >>> import numpy as np
>>> tbl = damask.Table(data=np.arange(12).reshape((4,3)), >>> tbl = damask.Table(shapes=dict(colA=(1,),colB=(1,),colC=(1,)),
... shapes=dict(colA=(1,),colB=(1,),colC=(1,))) ... data=np.arange(12).reshape((4,3)))
>>> tbl['colA','colB'] >>> tbl['colA','colB']
colA colB colA colB
0 0 1 0 0 1
@ -282,7 +283,7 @@ class Table:
data = pd.read_csv(f,names=list(range(len(labels))),sep=r'\s+') data = pd.read_csv(f,names=list(range(len(labels))),sep=r'\s+')
return Table(data,shapes,comments) return Table(shapes,data,comments)
@staticmethod @staticmethod
@ -329,7 +330,7 @@ class Table:
if (remainder := data.shape[1]-sum(shapes.values())) > 0: if (remainder := data.shape[1]-sum(shapes.values())) > 0:
shapes['unknown'] = remainder shapes['unknown'] = remainder
return Table(data,shapes,comments) return Table(shapes,data,comments)
@property @property

View File

@ -90,7 +90,7 @@ class TestConfigMaterial:
np.ones(N*2),np.zeros(N*2),np.ones(N*2),np.ones(N*2), np.ones(N*2),np.zeros(N*2),np.ones(N*2),np.ones(N*2),
np.ones(N*2), np.ones(N*2),
)).T )).T
t = Table(a,{'varying':1,'constant':4,'ones':1}) t = Table({'varying':1,'constant':4,'ones':1},a)
c = ConfigMaterial.from_table(t,**{'phase':'varying','O':'constant','homogenization':'ones'}) c = ConfigMaterial.from_table(t,**{'phase':'varying','O':'constant','homogenization':'ones'})
assert len(c['material']) == N assert len(c['material']) == N
for i,m in enumerate(c['material']): for i,m in enumerate(c['material']):
@ -102,7 +102,7 @@ class TestConfigMaterial:
np.ones(N*2),np.zeros(N*2),np.ones(N*2),np.ones(N*2), np.ones(N*2),np.zeros(N*2),np.ones(N*2),np.ones(N*2),
np.ones(N*2), np.ones(N*2),
)).T )).T
t = Table(a,{'varying':1,'constant':4,'ones':1}) t = Table({'varying':1,'constant':4,'ones':1},a)
c = ConfigMaterial.from_table(t,**{'phase':'varying','O':'constant','homogenization':1}) c = ConfigMaterial.from_table(t,**{'phase':'varying','O':'constant','homogenization':1})
assert len(c['material']) == N assert len(c['material']) == N
for i,m in enumerate(c['material']): for i,m in enumerate(c['material']):

View File

@ -435,9 +435,9 @@ class TestGrid:
cells = np.random.randint(60,100,3) cells = np.random.randint(60,100,3)
size = np.ones(3)+np.random.rand(3) size = np.ones(3)+np.random.rand(3)
coords = grid_filters.coordinates0_point(cells,size).reshape(-1,3,order='F') coords = grid_filters.coordinates0_point(cells,size).reshape(-1,3,order='F')
z=np.ones(cells.prod()) z = np.ones(cells.prod())
z[cells[:2].prod()*int(cells[2]/2):]=0 z[cells[:2].prod()*int(cells[2]/2):] = 0
t = Table(np.column_stack((coords,z)),{'coords':3,'z':1}) t = Table({'coords':3,'z':1},np.column_stack((coords,z)))
t = t.add('indicator',t.get('coords')[:,0]) t = t.add('indicator',t.get('coords')[:,0])
g = Grid.from_table(t,'coords',['indicator','z']) g = Grid.from_table(t,'coords',['indicator','z'])
assert g.N_materials == g.cells[0]*2 and (g.material[:,:,-1]-g.material[:,:,0] == cells[0]).all() assert g.N_materials == g.cells[0]*2 and (g.material[:,:,-1]-g.material[:,:,0] == cells[0]).all()
@ -449,7 +449,7 @@ class TestGrid:
s = seeds.from_random(size,np.random.randint(60,100)) s = seeds.from_random(size,np.random.randint(60,100))
grid = Grid.from_Voronoi_tessellation(cells,size,s) grid = Grid.from_Voronoi_tessellation(cells,size,s)
coords = grid_filters.coordinates0_point(cells,size) coords = grid_filters.coordinates0_point(cells,size)
t = Table(np.column_stack((coords.reshape(-1,3,order='F'),grid.material.flatten(order='F'))),{'c':3,'m':1}) t = Table({'c':3,'m':1},np.column_stack((coords.reshape(-1,3,order='F'),grid.material.flatten(order='F'))))
assert grid.sort().renumber() == Grid.from_table(t,'c',['m']) assert grid.sort().renumber() == Grid.from_table(t,'c',['m'])

View File

@ -8,7 +8,9 @@ from damask import Table
def default(): def default():
"""Simple Table.""" """Simple Table."""
x = np.ones((5,13),dtype=float) x = np.ones((5,13),dtype=float)
return Table(x,{'F':(3,3),'v':(3,),'s':(1,)},['test data','contains five rows of only ones']) return Table({'F':(3,3),'v':(3,),'s':(1,)},
x,
['test data','contains five rows of only ones'])
@pytest.fixture @pytest.fixture
def ref_path(ref_path_base): def ref_path(ref_path_base):
@ -22,7 +24,7 @@ class TestTable:
@pytest.mark.parametrize('N',[10,40]) @pytest.mark.parametrize('N',[10,40])
def test_len(self,N): def test_len(self,N):
assert len(Table(np.random.rand(N,3),{'X':3})) == N assert len(Table({'X':3},np.random.rand(N,3))) == N
def test_get_scalar(self,default): def test_get_scalar(self,default):
d = default.get('s') d = default.get('s')
@ -110,7 +112,7 @@ class TestTable:
def test_rename_equivalent(self): def test_rename_equivalent(self):
x = np.random.random((5,13)) x = np.random.random((5,13))
t = Table(x,{'F':(3,3),'v':(3,),'s':(1,)},['random test data']) t = Table({'F':(3,3),'v':(3,),'s':(1,)},x,['random test data'])
s = t.get('s') s = t.get('s')
u = t.rename('s','u').get('u') u = t.rename('s','u').get('u')
assert np.all(s == u) assert np.all(s == u)
@ -129,35 +131,35 @@ class TestTable:
def test_join(self): def test_join(self):
x = np.random.random((5,13)) x = np.random.random((5,13))
a = Table(x,{'F':(3,3),'v':(3,),'s':(1,)},['random test data']) a = Table({'F':(3,3),'v':(3,),'s':(1,)},x,['random test data'])
y = np.random.random((5,3)) y = np.random.random((5,3))
b = Table(y,{'u':(3,)},['random test data']) b = Table({'u':(3,)},y,['random test data'])
c = a.join(b) c = a.join(b)
assert np.array_equal(c.get('u'), b.get('u')) assert np.array_equal(c.get('u'), b.get('u'))
def test_join_invalid(self): def test_join_invalid(self):
x = np.random.random((5,13)) x = np.random.random((5,13))
a = Table(x,{'F':(3,3),'v':(3,),'s':(1,)},['random test data']) a = Table({'F':(3,3),'v':(3,),'s':(1,)},x,['random test data'])
with pytest.raises(KeyError): with pytest.raises(KeyError):
a.join(a) a.join(a)
def test_append(self): def test_append(self):
x = np.random.random((5,13)) x = np.random.random((5,13))
a = Table(x,{'F':(3,3),'v':(3,),'s':(1,)},['random test data']) a = Table({'F':(3,3),'v':(3,),'s':(1,)},x,['random test data'])
b = a.append(a) b = a.append(a)
assert np.array_equal(b.data[:5].to_numpy(),b.data[5:].to_numpy()) assert np.array_equal(b.data[:5].to_numpy(),b.data[5:].to_numpy())
def test_append_invalid(self): def test_append_invalid(self):
x = np.random.random((5,13)) x = np.random.random((5,13))
a = Table(x,{'F':(3,3),'v':(3,),'s':(1,)},['random test data']) a = Table({'F':(3,3),'v':(3,),'s':(1,)},x,['random test data'])
b = Table(x,{'F':(3,3),'u':(3,),'s':(1,)},['random test data']) b = Table({'F':(3,3),'u':(3,),'s':(1,)},x,['random test data'])
with pytest.raises(KeyError): with pytest.raises(KeyError):
a.append(b) a.append(b)
def test_invalid_initialization(self): def test_invalid_initialization(self):
x = np.random.random((5,10)) x = np.random.random((5,10))
with pytest.raises(ValueError): with pytest.raises(ValueError):
Table(x,{'F':(3,3)}) Table({'F':(3,3)},x)
def test_invalid_set(self,default): def test_invalid_set(self,default):
x = default.get('v') x = default.get('v')
@ -170,27 +172,27 @@ class TestTable:
def test_sort_scalar(self): def test_sort_scalar(self):
x = np.random.random((5,13)) x = np.random.random((5,13))
t = Table(x,{'F':(3,3),'v':(3,),'s':(1,)},['random test data']) t = Table({'F':(3,3),'v':(3,),'s':(1,)},x,['random test data'])
unsort = t.get('s') unsort = t.get('s')
sort = t.sort_by('s').get('s') sort = t.sort_by('s').get('s')
assert np.all(np.sort(unsort,0)==sort) assert np.all(np.sort(unsort,0)==sort)
def test_sort_component(self): def test_sort_component(self):
x = np.random.random((5,12)) x = np.random.random((5,12))
t = Table(x,{'F':(3,3),'v':(3,)},['random test data']) t = Table({'F':(3,3),'v':(3,)},x,['random test data'])
unsort = t.get('F')[:,1,0] unsort = t.get('F')[:,1,0]
sort = t.sort_by('F[1,0]').get('F')[:,1,0] sort = t.sort_by('F[1,0]').get('F')[:,1,0]
assert np.all(np.sort(unsort,0)==sort) assert np.all(np.sort(unsort,0)==sort)
def test_sort_revert(self): def test_sort_revert(self):
x = np.random.random((5,12)) x = np.random.random((5,12))
t = Table(x,{'F':(3,3),'v':(3,)},['random test data']) t = Table({'F':(3,3),'v':(3,)},x,['random test data'])
sort = t.sort_by('F[1,0]',ascending=False).get('F')[:,1,0] sort = t.sort_by('F[1,0]',ascending=False).get('F')[:,1,0]
assert np.all(np.sort(sort,0)==sort[::-1]) assert np.all(np.sort(sort,0)==sort[::-1])
def test_sort(self): def test_sort(self):
t = Table(np.array([[0,1,],[2,1,]]), t = Table({'v':(2,)},
{'v':(2,)}, np.array([[0,1,],[2,1,]]),
['test data'])\ ['test data'])\
.add('s',np.array(['b','a']))\ .add('s',np.array(['b','a']))\
.sort_by('s') .sort_by('s')

View File

@ -179,7 +179,7 @@ class TestVTK:
for k,s in shapes.items(): for k,s in shapes.items():
d[k] = dict(shape = s, d[k] = dict(shape = s,
data = np.random.random(N*np.prod(s)).reshape((N,-1))) data = np.random.random(N*np.prod(s)).reshape((N,-1)))
new = default.add(Table(np.column_stack([d[k]['data'] for k in shapes.keys()]),shapes)) new = default.add(Table(shapes,np.column_stack([d[k]['data'] for k in shapes.keys()])))
for k,s in shapes.items(): for k,s in shapes.items():
assert np.allclose(np.squeeze(d[k]['data']),new.get(k),rtol=1e-7) assert np.allclose(np.squeeze(d[k]['data']),new.get(k),rtol=1e-7)