[skip sc] first draft

This commit is contained in:
Martin Diehl 2019-10-31 10:45:34 +01:00
parent 1c10459a5a
commit fb286af354
3 changed files with 83 additions and 52 deletions

View File

@ -1,11 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os import os
import sys
from optparse import OptionParser from optparse import OptionParser
import numpy as np
import damask import damask
@ -37,53 +34,9 @@ parser.set_defaults(defgrad = 'f',
(options,filenames) = parser.parse_args() (options,filenames) = parser.parse_args()
# --- loop over input files -------------------------------------------------------------------------
if filenames == []: filenames = [None]
for name in filenames: for name in filenames:
try: table = damask.Table(name)
table = damask.ASCIItable(name = name, buffered = False) table.add_array('Cauchy',damask.mechanics.Cauchy(table.get_array(options.defgrad).reshape(-1,3,3),
except: table.get_array(options.stress).reshape(-1,3,3)).reshape(-1,9),
continue scriptID)
damask.util.report(scriptName,name) table.to_ASCII()
# ------------------------------------------ read header ------------------------------------------
table.head_read()
# ------------------------------------------ sanity checks ----------------------------------------
errors = []
column = {}
for tensor in [options.defgrad,options.stress]:
dim = table.label_dimension(tensor)
if dim < 0: errors.append('column {} not found.'.format(tensor))
elif dim != 9: errors.append('column {} is not a tensor.'.format(tensor))
else:
column[tensor] = table.label_index(tensor)
if errors != []:
damask.util.croak(errors)
table.close(dismiss = True)
continue
# ------------------------------------------ assemble header --------------------------------------
table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
table.labels_append(['{}_Cauchy'.format(i+1) for i in range(9)]) # extend ASCII header with new labels
table.head_write()
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table
F = np.array(list(map(float,table.data[column[options.defgrad]:column[options.defgrad]+9])),'d').reshape(3,3)
P = np.array(list(map(float,table.data[column[options.stress ]:column[options.stress ]+9])),'d').reshape(3,3)
table.data_append(list(1.0/np.linalg.det(F)*np.dot(P,F.T).reshape(9))) # [Cauchy] = (1/det(F)) * [P].[F_transpose]
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output finalization -----------------------------------
table.close() # close input ASCII table (works for stdin)

View File

@ -9,6 +9,7 @@ name = 'damask'
# classes # classes
from .environment import Environment # noqa from .environment import Environment # noqa
from .asciitable import ASCIItable # noqa from .asciitable import ASCIItable # noqa
from .table import Table # noqa
from .config import Material # noqa from .config import Material # noqa
from .colormaps import Colormap, Color # noqa from .colormaps import Colormap, Color # noqa

77
python/damask/table.py Normal file
View File

@ -0,0 +1,77 @@
import re
import pandas as pd
import numpy as np
class Table():
"""Read and write to ASCII tables"""
def __init__(self,name):
self.name = name
with open(self.name) as f:
header,keyword = f.readline().split()
if keyword == 'header':
header = int(header)
else:
raise Exception
self.comments = [f.readline()[:-1] for i in range(header-1)]
labels_raw = f.readline().split()
self.data = pd.read_csv(f,delim_whitespace=True,header=None)
labels_repeated = [l.split('_',1)[1] if '_' in l else l for l in labels_raw]
self.data.rename(columns=dict(zip([l for l in self.data.columns],labels_repeated)),inplace=True)
self.shape = {}
for l in labels_raw:
tensor_column = re.search(':.*?_',l)
if tensor_column:
my_shape = tensor_column.group()[1:-1].split('x')
self.shape[l.split('_',1)[1]] = tuple([int(d) for d in my_shape])
else:
vector_column = re.match('.*?_',l)
if vector_column:
self.shape[l.split('_',1)[1]] = (int(l.split('_',1)[0]),)
else:
self.shape[l]=(1,)
self.labels = list(dict.fromkeys(labels_repeated))
def get_array(self,label):
return self.data[label].to_numpy().reshape((-1,)+self.shape[label])
def add_array(self,label,array,info):
if np.product(array.shape[1:],dtype=int) == 1:
self.comments.append('{}: {}'.format(label,info))
else:
self.comments.append('{} {}: {}'.format(label,array.shape[1:],info))
self.shape[label] = array.shape[1:]
self.labels.append(label)
size = np.product(array.shape[1:])
new_data = pd.DataFrame(data=array.reshape(-1,size),
columns=[label for l in range(size)])
self.data = pd.concat([self.data,new_data],axis=1)
def to_ASCII(self,name=None):
labels = []
for l in self.labels:
if(self.shape[l] == (1,)):
labels.append('{}'.format(l))
elif(len(self.shape[l]) == 1):
labels+=['{}_{}'.format(i+1,l)\
for i in range(self.shape[l][0])]
else:
labels+=['{}:{}_{}'.format(i+1,'x'.join([str(d) for d in self.shape[l]]),l)\
for i in range(np.product(self.shape[l]))]
header = ['{} header'.format(len(self.comments)+1)]\
+ self.comments\
+ [' '.join(labels)]
with open(name if name is not None else self.name,'w') as f:
for line in header: f.write(line+'\n')
self.data.to_csv(f,sep=' ',index=False,header=False)