fixed calculation of size and dimension in case of 2D (was limited to third dim only)

plus polishing
This commit is contained in:
Martin Diehl 2014-08-06 15:25:18 +00:00
parent cbafad50d0
commit 938352d43a
20 changed files with 365 additions and 371 deletions

View File

@ -41,7 +41,7 @@ if len(options.labels) != len(options.formulas):
for i in xrange(len(options.formulas)): for i in xrange(len(options.formulas)):
options.formulas[i]=options.formulas[i].replace(';',',') options.formulas[i]=options.formulas[i].replace(';',',')
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -112,7 +112,7 @@ for file in files:
for label in options.labels: table.data_append(unravel(eval(eval(evaluator[label])))) for label in options.labels: table.data_append(unravel(eval(eval(evaluator[label]))))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -38,7 +38,7 @@ datainfo = {
datainfo['defgrad']['label'].append(options.defgrad) datainfo['defgrad']['label'].append(options.defgrad)
datainfo['stress']['label'].append(options.stress) datainfo['stress']['label'].append(options.stress)
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -47,7 +47,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
# ------------------------------------------ loop over input files --------------------------------------- # ------------------------------------------ loop over input files ---------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -73,21 +73,23 @@ for file in files:
if missingColumns: if missingColumns:
continue continue
# ------------------------------------------ assemble header ------------------------------------ # ------------------------------------------ assemble header --------------------------------------
table.labels_append(['%i_Cauchy'%(i+1) for i in xrange(9)]) # extend ASCII header with new labels table.labels_append(['%i_Cauchy'%(i+1) for i in xrange(9)]) # extend ASCII header with new labels
table.head_write() table.head_write()
# ------------------------------------------ process data ---------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
F = np.array(map(float,table.data[column['defgrad'][active['defgrad'][0]]: F = np.array(map(float,table.data[column['defgrad'][active['defgrad'][0]]:
column['defgrad'][active['defgrad'][0]]+datainfo['defgrad']['len']]),'d').reshape(3,3) column['defgrad'][active['defgrad'][0]]+datainfo['defgrad']['len']]),\
'd').reshape(3,3)
P = np.array(map(float,table.data[column['stress'][active['stress'][0]]: P = np.array(map(float,table.data[column['stress'][active['stress'][0]]:
column['stress'][active['stress'][0]]+datainfo['stress']['len']]),'d').reshape(3,3) column['stress'][active['stress'][0]]+datainfo['stress']['len']]),\
'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] 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 outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from optparse import OptionParser from optparse import OptionParser
import damask import damask
@ -42,13 +42,13 @@ datainfo = {
datainfo['defgrad']['label'].append(options.defgrad) datainfo['defgrad']['label'].append(options.defgrad)
# ------------------------------------------ setup file handles ------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
for name in filenames: for name in filenames:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
#--- loop over input files ------------------------------------------------------------------------ #--- loop over input files -------------------------------------------------------------------------
for file in files: for file in files:
file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
@ -56,28 +56,35 @@ for file in files:
table.head_read() # read ASCII header info table.head_read() # read ASCII header info
table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:])) table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
# --------------- figure out dimension and resolution ---------------------------------------------- # --------------- figure out size and grid ---------------------------------------------------------
try: try:
locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data
except ValueError: except ValueError:
file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords) file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords)
continue continue
grid = [{},{},{}] coords = [{},{},{}]
while table.data_read(): # read next data line of ASCII table while table.data_read(): # read next data line of ASCII table
for j in xrange(3): for j in xrange(3):
grid[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z coords[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
res = np.array([len(grid[0]),\ grid = np.array([len(coords[0]),\
len(grid[1]),\ len(coords[1]),\
len(grid[2]),],'i') # resolution is number of distinct coordinates found len(coords[2]),],'i') # grid is number of distinct coordinates found
geomdim = res/np.maximum(np.ones(3,'d'),res-1.0)* \ size = grid/np.maximum(np.ones(3,'d'),grid-1.0)* \
np.array([max(map(float,grid[0].keys()))-min(map(float,grid[0].keys())),\ np.array([max(map(float,coords[0].keys()))-min(map(float,coords[0].keys())),\
max(map(float,grid[1].keys()))-min(map(float,grid[1].keys())),\ max(map(float,coords[1].keys()))-min(map(float,coords[1].keys())),\
max(map(float,grid[2].keys()))-min(map(float,grid[2].keys())),\ max(map(float,coords[2].keys()))-min(map(float,coords[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness ],'d') # dimension from bounding box, corrected for cell-centeredness
if res[2] == 1:
geomdim[2] = min(geomdim[:2]/res[:2]) for i, points in enumerate(grid):
N = res.prod() if points == 1:
options.packing[i] = 1
options.shift[i] = 0
mask = np.ones(3,dtype=bool)
mask[i]=0
size[i] = min(size[mask]/grid[mask]) # third spacing equal to smaller of other spacing
N = grid.prod()
# --------------- figure out columns to process --------------------------------------------------- # --------------- figure out columns to process ---------------------------------------------------
missingColumns = False missingColumns = False
@ -100,26 +107,26 @@ for file in files:
# ------------------------------------------ read deformation gradient field ----------------------- # ------------------------------------------ read deformation gradient field -----------------------
table.data_rewind() table.data_rewind()
F = np.array([0.0 for i in xrange(N*9)]).reshape([3,3]+list(res)) F = np.array([0.0 for i in xrange(N*9)]).reshape([3,3]+list(grid))
idx = 0 idx = 0
while table.data_read(): while table.data_read():
(x,y,z) = damask.util.gridLocation(idx,res) # figure out (x,y,z) position from line count (x,y,z) = damask.util.gridLocation(idx,grid) # figure out (x,y,z) position from line count
idx += 1 idx += 1
F[0:3,0:3,x,y,z] = np.array(map(float,table.data[column:column+9]),'d').reshape(3,3) F[0:3,0:3,x,y,z] = np.array(map(float,table.data[column:column+9]),'d').reshape(3,3)
Favg = damask.core.math.tensorAvg(F) Favg = damask.core.math.tensorAvg(F)
centres = damask.core.mesh.deformedCoordsFFT(geomdim,F,Favg,[1.0,1.0,1.0]) centres = damask.core.mesh.deformedCoordsFFT(size,F,Favg,[1.0,1.0,1.0])
nodes = damask.core.mesh.nodesAroundCentres(geomdim,Favg,centres) nodes = damask.core.mesh.nodesAroundCentres(size,Favg,centres)
if not options.noShape: shapeMismatch = damask.core.mesh.shapeMismatch( geomdim,F,nodes,centres) if not options.noShape: shapeMismatch = damask.core.mesh.shapeMismatch( size,F,nodes,centres)
if not options.noVolume: volumeMismatch = damask.core.mesh.volumeMismatch(geomdim,F,nodes) if not options.noVolume: volumeMismatch = damask.core.mesh.volumeMismatch(size,F,nodes)
# ------------------------------------------ process data --------------------------------------- # ------------------------------------------ process data ------------------------------------------
table.data_rewind() table.data_rewind()
idx = 0 idx = 0
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
(x,y,z) = damask.util.gridLocation(idx,res) # figure out (x,y,z) position from line count (x,y,z) = damask.util.gridLocation(idx,grid) # figure out (x,y,z) position from line count
idx += 1 idx += 1
if not options.noShape: table.data_append( shapeMismatch[x,y,z]) if not options.noShape: table.data_append( shapeMismatch[x,y,z])
if not options.noVolume: table.data_append(volumeMismatch[x,y,z]) if not options.noVolume: table.data_append(volumeMismatch[x,y,z])
@ -128,6 +135,6 @@ for file in files:
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result ---------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table (works for stdout) file['output'].close() # close output ASCII table
os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -52,7 +52,7 @@ for name in filenames:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
#--- loop over input files ------------------------------------------------------------------------ #--- loop over input files -------------------------------------------------------------------------
for file in files: for file in files:
file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
@ -60,30 +60,37 @@ for file in files:
table.head_read() # read ASCII header info table.head_read() # read ASCII header info
table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:])) table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
# --------------- figure out dimension and resolution ---------------------------------------------- # --------------- figure out size and grid ---------------------------------------------------------
try: try:
locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data
except ValueError: except ValueError:
file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords) file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords)
continue continue
grid = [{},{},{}] coords = [{},{},{}]
while table.data_read(): # read next data line of ASCII table while table.data_read(): # read next data line of ASCII table
for j in xrange(3): for j in xrange(3):
grid[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z coords[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
resolution = np.array([len(grid[0]),\ grid = np.array([len(coords[0]),\
len(grid[1]),\ len(coords[1]),\
len(grid[2]),],'i') # resolution is number of distinct coordinates found len(coords[2]),],'i') # grid is number of distinct coordinates found
dimension = resolution/np.maximum(np.ones(3,'d'),resolution-1.0)* \ size = grid/np.maximum(np.ones(3,'d'),grid-1.0)* \
np.array([max(map(float,grid[0].keys()))-min(map(float,grid[0].keys())),\ np.array([max(map(float,coords[0].keys()))-min(map(float,coords[0].keys())),\
max(map(float,grid[1].keys()))-min(map(float,grid[1].keys())),\ max(map(float,coords[1].keys()))-min(map(float,coords[1].keys())),\
max(map(float,grid[2].keys()))-min(map(float,grid[2].keys())),\ max(map(float,coords[2].keys()))-min(map(float,coords[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness ],'d') # size from bounding box, corrected for cell-centeredness
if resolution[2] == 1:
dimension[2] = min(dimension[:2]/resolution[:2])
N = resolution.prod()
# --------------- figure out columns to process -------------------------------------------------- for i, points in enumerate(grid):
if points == 1:
options.packing[i] = 1
options.shift[i] = 0
mask = np.ones(3,dtype=bool)
mask[i]=0
size[i] = min(size[mask]/grid[mask]) # third spacing equal to smaller of other spacing
N = grid.prod()
# --------------- figure out columns to process ---------------------------------------------------
active = defaultdict(list) active = defaultdict(list)
column = defaultdict(dict) column = defaultdict(dict)
values = defaultdict(dict) values = defaultdict(dict)
@ -98,9 +105,9 @@ for file in files:
active[datatype].append(label) active[datatype].append(label)
column[datatype][label] = table.labels.index(key) # remember columns of requested data column[datatype][label] = table.labels.index(key) # remember columns of requested data
values[datatype][label] = np.array([0.0 for i in xrange(N*datainfo[datatype]['len'])]).\ values[datatype][label] = np.array([0.0 for i in xrange(N*datainfo[datatype]['len'])]).\
reshape(list(resolution)+[datainfo[datatype]['len']//3,3]) reshape(list(grid)+[datainfo[datatype]['len']//3,3])
curl[datatype][label] = np.array([0.0 for i in xrange(N*datainfo[datatype]['len'])]).\ curl[datatype][label] = np.array([0.0 for i in xrange(N*datainfo[datatype]['len'])]).\
reshape(list(resolution)+[datainfo[datatype]['len']//3,3]) reshape(list(grid)+[datainfo[datatype]['len']//3,3])
# ------------------------------------------ assemble header --------------------------------------- # ------------------------------------------ assemble header ---------------------------------------
for datatype,labels in active.items(): # loop over vector,tensor for datatype,labels in active.items(): # loop over vector,tensor
@ -113,7 +120,7 @@ for file in files:
table.data_rewind() table.data_rewind()
idx = 0 idx = 0
while table.data_read(): # read next data line of ASCII table while table.data_read(): # read next data line of ASCII table
(x,y,z) = damask.util.gridLocation(idx,resolution) # figure out (x,y,z) position from line count (x,y,z) = damask.util.gridLocation(idx,grid) # figure out (x,y,z) position from line count
idx += 1 idx += 1
for datatype,labels in active.items(): # loop over vector,tensor for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested curls for label in labels: # loop over all requested curls
@ -125,23 +132,23 @@ for file in files:
# ------------------------------------------ process value field ----------------------------------- # ------------------------------------------ process value field -----------------------------------
for datatype,labels in active.items(): # loop over vector,tensor for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested curls for label in labels: # loop over all requested curls
curl[datatype][label] = damask.core.math.curlFFT(dimension,values[datatype][label]) curl[datatype][label] = damask.core.math.curlFFT(size,values[datatype][label])
# ------------------------------------------ process data --------------------------------------- # ------------------------------------------ process data ------------------------------------------
table.data_rewind() table.data_rewind()
idx = 0 idx = 0
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
(x,y,z) = damask.util.gridLocation(idx,resolution) # figure out (x,y,z) position from line count (x,y,z) = damask.util.gridLocation(idx,grid) # figure out (x,y,z) position from line count
idx += 1 idx += 1
for datatype,labels in active.items(): # loop over vector,tensor for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested norms for label in labels: # loop over all requested norms
table.data_append(list(curl[datatype][label][x,y,z].reshape(datainfo[datatype]['len']))) table.data_append(list(curl[datatype][label][x,y,z].reshape(datainfo[datatype]['len'])))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table (works for stdout) file['output'].close() # close output ASCII table
os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -39,13 +39,13 @@ datainfo = {
datainfo['defgrad']['label'].append(options.defgrad) datainfo['defgrad']['label'].append(options.defgrad)
# ------------------------------------------ setup file handles ------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
for name in filenames: for name in filenames:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
#--- loop over input files ------------------------------------------------------------------------ #--- loop over input files -------------------------------------------------------------------------
for file in files: for file in files:
file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
@ -53,28 +53,35 @@ for file in files:
table.head_read() # read ASCII header info table.head_read() # read ASCII header info
table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:])) table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
# --------------- figure out dimension and resolution ---------------------------------------------- # --------------- figure out size and grid ---------------------------------------------------------
try: try:
locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data
except ValueError: except ValueError:
file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords) file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords)
continue continue
grid = [{},{},{}] coords = [{},{},{}]
while table.data_read(): # read next data line of ASCII table while table.data_read(): # read next data line of ASCII table
for j in xrange(3): for j in xrange(3):
grid[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z coords[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
res = np.array([len(grid[0]),\ grid = np.array([len(coords[0]),\
len(grid[1]),\ len(coords[1]),\
len(grid[2]),],'i') # resolution is number of distinct coordinates found len(coords[2]),],'i') # grid is number of distinct coordinates found
geomdim = res/np.maximum(np.ones(3,'d'),res-1.0)* \ size = grid/np.maximum(np.ones(3,'d'),grid-1.0)* \
np.array([max(map(float,grid[0].keys()))-min(map(float,grid[0].keys())),\ np.array([max(map(float,coords[0].keys()))-min(map(float,coords[0].keys())),\
max(map(float,grid[1].keys()))-min(map(float,grid[1].keys())),\ max(map(float,coords[1].keys()))-min(map(float,coords[1].keys())),\
max(map(float,grid[2].keys()))-min(map(float,grid[2].keys())),\ max(map(float,coords[2].keys()))-min(map(float,coords[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness ],'d') # dimension from bounding box, corrected for cell-centeredness
if res[2] == 1:
geomdim[2] = min(geomdim[:2]/res[:2]) for i, points in enumerate(grid):
N = res.prod() if points == 1:
options.packing[i] = 1
options.shift[i] = 0
mask = np.ones(3,dtype=bool)
mask[i]=0
size[i] = min(size[mask]/grid[mask]) # third spacing equal to smaller of other spacing
N = grid.prod()
# --------------- figure out columns to process --------------------------------------------------- # --------------- figure out columns to process ---------------------------------------------------
missingColumns = False missingColumns = False
@ -96,33 +103,33 @@ for file in files:
# ------------------------------------------ read deformation gradient field ----------------------- # ------------------------------------------ read deformation gradient field -----------------------
table.data_rewind() table.data_rewind()
F = np.array([0.0 for i in xrange(N*9)]).reshape([3,3]+list(res)) F = np.array([0.0 for i in xrange(N*9)]).reshape([3,3]+list(grid))
idx = 0 idx = 0
while table.data_read(): while table.data_read():
(x,y,z) = damask.util.gridLocation(idx,res) # figure out (x,y,z) position from line count (x,y,z) = damask.util.gridLocation(idx,grid) # figure out (x,y,z) position from line count
idx += 1 idx += 1
F[0:3,0:3,x,y,z] = np.array(map(float,table.data[column:column+9]),'d').reshape(3,3) F[0:3,0:3,x,y,z] = np.array(map(float,table.data[column:column+9]),'d').reshape(3,3)
# ------------------------------------------ calculate coordinates --------------------------------- # ------------------------------------------ calculate coordinates ---------------------------------
Favg = damask.core.math.tensorAvg(F) Favg = damask.core.math.tensorAvg(F)
if options.linearreconstruction: if options.linearreconstruction:
centroids = damask.core.mesh.deformedCoordsLin(geomdim,F,Favg) centroids = damask.core.mesh.deformedCoordsLin(size,F,Favg)
else: else:
centroids = damask.core.mesh.deformedCoordsFFT(geomdim,F,Favg) centroids = damask.core.mesh.deformedCoordsFFT(size,F,Favg)
# ------------------------------------------ process data ------------------------------------------ # ------------------------------------------ process data ------------------------------------------
table.data_rewind() table.data_rewind()
idx = 0 idx = 0
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
(x,y,z) = damask.util.gridLocation(idx,res) # figure out (x,y,z) position from line count (x,y,z) = damask.util.gridLocation(idx,grid) # figure out (x,y,z) position from line count
idx += 1 idx += 1
table.data_append(list(centroids[:,x,y,z])) table.data_append(list(centroids[:,x,y,z]))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table (works for stdout) file['output'].close() # close output ASCII table
os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
import damask import damask
@ -42,7 +42,7 @@ datainfo = {
datainfo['tensor']['label'] += options.tensor datainfo['tensor']['label'] += options.tensor
# ------------------------------------------ setup file handles ----------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -51,7 +51,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
#--- loop over input files ------------------------------------------------------------------------ #--- loop over input files -------------------------------------------------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -76,7 +76,7 @@ for file in files:
table.labels_append('det(%s)'%label) # extend ASCII header with new labels table.labels_append('det(%s)'%label) # extend ASCII header with new labels
table.head_write() table.head_write()
# ------------------------------------------ process data --------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
for label in active: for label in active:
@ -84,7 +84,7 @@ for file in files:
column[label]+datainfo['tensor']['len']]))) column[label]+datainfo['tensor']['len']])))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
import damask import damask
@ -46,7 +46,7 @@ datainfo = {
datainfo['tensor']['label'] += options.tensor datainfo['tensor']['label'] += options.tensor
# ------------------------------------------ setup file handles ----------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -55,7 +55,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
# ------------------------------------------ loop over input files --------------------------------------- # ------------------------------------------ loop over input files ---------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -81,7 +81,7 @@ for file in files:
if(options.hydrostatic): table.labels_append('sph(%s)'%label) if(options.hydrostatic): table.labels_append('sph(%s)'%label)
table.head_write() table.head_write()
# ------------------------------------------ process data --------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
for label in active: for label in active:
@ -91,7 +91,7 @@ for file in files:
if(options.hydrostatic): table.data_append(oneThird*(myTensor[0]+myTensor[4]+myTensor[8])) if(options.hydrostatic): table.data_append(oneThird*(myTensor[0]+myTensor[4]+myTensor[8]))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -65,7 +65,7 @@ for name in filenames:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
#--- loop over input files ------------------------------------------------------------------------ #--- loop over input files -------------------------------------------------------------------------
for file in files: for file in files:
file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
@ -73,30 +73,37 @@ for file in files:
table.head_read() # read ASCII header info table.head_read() # read ASCII header info
table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:])) table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
# --------------- figure out dimension and resolution ---------------------------------------------- # --------------- figure out size and grid ---------------------------------------------------------
try: try:
locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data
except ValueError: except ValueError:
file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords) file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords)
continue continue
grid = [{},{},{}] coords = [{},{},{}]
while table.data_read(): # read next data line of ASCII table while table.data_read(): # read next data line of ASCII table
for j in xrange(3): for j in xrange(3):
grid[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z coords[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
resolution = np.array([len(grid[0]),\ grid = np.array([len(coords[0]),\
len(grid[1]),\ len(coords[1]),\
len(grid[2]),],'i') # resolution is number of distinct coordinates found len(coords[2]),],'i') # grid is number of distinct coordinates found
dimension = resolution/np.maximum(np.ones(3,'d'),resolution-1.0)* \ size = grid/np.maximum(np.ones(3,'d'),grid-1.0)* \
np.array([max(map(float,grid[0].keys()))-min(map(float,grid[0].keys())),\ np.array([max(map(float,coords[0].keys()))-min(map(float,coords[0].keys())),\
max(map(float,grid[1].keys()))-min(map(float,grid[1].keys())),\ max(map(float,coords[1].keys()))-min(map(float,coords[1].keys())),\
max(map(float,grid[2].keys()))-min(map(float,grid[2].keys())),\ max(map(float,coords[2].keys()))-min(map(float,coords[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness ],'d') # size from bounding box, corrected for cell-centeredness
if resolution[2] == 1:
dimension[2] = min(dimension[:2]/resolution[:2])
N = resolution.prod()
# --------------- figure out columns to process -------------------------------------------------- for i, points in enumerate(grid):
if points == 1:
options.packing[i] = 1
options.shift[i] = 0
mask = np.ones(3,dtype=bool)
mask[i]=0
size[i] = min(size[mask]/grid[mask]) # third spacing equal to smaller of other spacing
N = grid.prod()
# --------------- figure out columns to process ---------------------------------------------------
active = defaultdict(list) active = defaultdict(list)
column = defaultdict(dict) column = defaultdict(dict)
values = defaultdict(dict) values = defaultdict(dict)
@ -111,11 +118,11 @@ for file in files:
active[datatype].append(label) active[datatype].append(label)
column[datatype][label] = table.labels.index(key) # remember columns of requested data column[datatype][label] = table.labels.index(key) # remember columns of requested data
values[datatype][label] = np.array([0.0 for i in xrange(N*datainfo[datatype]['len'])]).\ values[datatype][label] = np.array([0.0 for i in xrange(N*datainfo[datatype]['len'])]).\
reshape(list(resolution)+[datainfo[datatype]['len']//3,3]) reshape(list(grid)+[datainfo[datatype]['len']//3,3])
if label not in divergence[datatype]: divergence[datatype][label] = {} if label not in divergence[datatype]: divergence[datatype][label] = {}
for accuracy in options.accuracy: for accuracy in options.accuracy:
divergence[datatype][label][accuracy] = np.array([0.0 for i in xrange(N*datainfo[datatype]['len']//3)]).\ divergence[datatype][label][accuracy] = np.array([0.0 for i in xrange(N*datainfo[datatype]['len']//3)]).\
reshape(list(resolution)+[datainfo[datatype]['len']//3]) reshape(list(grid)+[datainfo[datatype]['len']//3])
# ------------------------------------------ assemble header --------------------------------------- # ------------------------------------------ assemble header ---------------------------------------
for datatype,labels in active.items(): # loop over vector,tensor for datatype,labels in active.items(): # loop over vector,tensor
@ -129,7 +136,7 @@ for file in files:
table.data_rewind() table.data_rewind()
idx = 0 idx = 0
while table.data_read(): # read next data line of ASCII table while table.data_read(): # read next data line of ASCII table
(x,y,z) = damask.util.gridLocation(idx,resolution) # figure out (x,y,z) position from line count (x,y,z) = damask.util.gridLocation(idx,grid) # figure out (x,y,z) position from line count
idx += 1 idx += 1
for datatype,labels in active.items(): # loop over vector,tensor for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested curls for label in labels: # loop over all requested curls
@ -143,16 +150,18 @@ for file in files:
for label in labels: # loop over all requested divergencies for label in labels: # loop over all requested divergencies
for accuracy in options.accuracy: for accuracy in options.accuracy:
if accuracy == 'FFT': if accuracy == 'FFT':
divergence[datatype][label][accuracy] = damask.core.math.divergenceFFT(dimension,values[datatype][label]) divergence[datatype][label][accuracy] =\
damask.core.math.divergenceFFT(size,values[datatype][label])
else: else:
divergence[datatype][label][accuracy] = damask.core.math.divergenceFDM(dimension,eval(accuracy)//2-1,values[datatype][label]) divergence[datatype][label][accuracy] =\
damask.core.math.divergenceFDM(size,eval(accuracy)//2-1,values[datatype][label])
# ------------------------------------------ process data --------------------------------------- # ------------------------------------------ process data ------------------------------------------
table.data_rewind() table.data_rewind()
idx = 0 idx = 0
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
(x,y,z) = damask.util.gridLocation(idx,resolution) # figure out (x,y,z) position from line count (x,y,z) = damask.util.gridLocation(idx,grid) # figure out (x,y,z) position from line count
idx += 1 idx += 1
for datatype,labels in active.items(): # loop over vector,tensor for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested for label in labels: # loop over all requested
@ -160,9 +169,9 @@ for file in files:
table.data_append(list(divergence[datatype][label][accuracy][x,y,z].reshape(datainfo[datatype]['len']//3))) table.data_append(list(divergence[datatype][label][accuracy][x,y,z].reshape(datainfo[datatype]['len']//3)))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table (works for stdout) file['output'].close() # close output ASCII table
os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -56,7 +56,7 @@ datainfo = { # lis
datainfo['vector']['label'] += options.vector datainfo['vector']['label'] += options.vector
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
@ -66,7 +66,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
# ------------------------------------------ loop over input files --------------------------------------- # ------------------------------------------ loop over input files ---------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -93,7 +93,7 @@ for file in files:
options.hkl[2],label)) # extend ASCII header with new labels options.hkl[2],label)) # extend ASCII header with new labels
table.head_write() table.head_write()
# ------------------------------------------ process data ---------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
for label in active: for label in active:
@ -101,7 +101,7 @@ for file in files:
column[label]+datainfo['vector']['len']]),options.hkl)) column[label]+datainfo['vector']['len']]),options.hkl))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from optparse import OptionParser from optparse import OptionParser
from scipy import ndimage from scipy import ndimage
@ -112,7 +112,7 @@ if 'biplane' in options.type and 'boundary' in options.type:
feature_list = [] feature_list = []
for i,feature in enumerate(features): for i,feature in enumerate(features):
if feature['name'] in options.type: feature_list.append(i) # remember valid features if feature['name'] in options.type: feature_list.append(i) # remember valid features
# ------------------------------------------ setup file handles ----------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
for name in filenames: for name in filenames:
@ -144,23 +144,23 @@ for file in files:
table.head_write() table.head_write()
# ------------------------------------------ process data --------------------------------------- # ------------------------------------------ process data ------------------------------------------
table.data_readArray([options.coords+'.x',options.coords+'.y',options.coords+'.z',options.id]) table.data_readArray([options.coords+'.x',options.coords+'.y',options.coords+'.z',options.id])
grid = [{},{},{}] coords = [{},{},{}]
for i in xrange(len(table.data)): for i in xrange(len(table.data)):
for j in xrange(3): for j in xrange(3):
grid[j][str(table.data[i,j])] = True coords[j][str(table.data[i,j])] = True
resolution = np.array(map(len,grid),'i') grid = np.array(map(len,coords),'i')
unitlength = 0.0 unitlength = 0.0
for i,r in enumerate(resolution): for i,r in enumerate(grid):
if r > 1: unitlength = max(unitlength,(max(map(float,grid[i].keys()))-min(map(float,grid[i].keys())))/(r-1.0)) if r > 1: unitlength = max(unitlength,(max(map(float,coords[i].keys()))-min(map(float,coords[i].keys())))/(r-1.0))
neighborhood = neighborhoods[options.neighborhood] neighborhood = neighborhoods[options.neighborhood]
convoluted = np.empty([len(neighborhood)]+list(resolution+2),'i') convoluted = np.empty([len(neighborhood)]+list(grid+2),'i')
microstructure = periodic_3Dpad(np.array(table.data[:,3].reshape(resolution),'i')) microstructure = periodic_3Dpad(np.array(table.data[:,3].reshape(grid),'i'))
for i,p in enumerate(neighborhood): for i,p in enumerate(neighborhood):
stencil = np.zeros((3,3,3),'i') stencil = np.zeros((3,3,3),'i')
@ -171,11 +171,11 @@ for file in files:
convoluted[i,:,:,:] = ndimage.convolve(microstructure,stencil) convoluted[i,:,:,:] = ndimage.convolve(microstructure,stencil)
distance = np.ones((len(feature_list),resolution[0],resolution[1],resolution[2]),'d') distance = np.ones((len(feature_list),grid[0],grid[1],grid[2]),'d')
convoluted = np.sort(convoluted,axis=0) convoluted = np.sort(convoluted,axis=0)
uniques = np.zeros(resolution) uniques = np.zeros(grid)
check = np.empty(resolution) check = np.empty(grid)
check[:,:,:] = np.nan check[:,:,:] = np.nan
for i in xrange(len(neighborhood)): for i in xrange(len(neighborhood)):
uniques += np.where(convoluted[i,1:-1,1:-1,1:-1] == check,0,1) uniques += np.where(convoluted[i,1:-1,1:-1,1:-1] == check,0,1)
@ -185,9 +185,9 @@ for file in files:
for i in xrange(len(feature_list)): for i in xrange(len(feature_list)):
distance[i,:,:,:] = ndimage.morphology.distance_transform_edt(distance[i,:,:,:])*[unitlength]*3 distance[i,:,:,:] = ndimage.morphology.distance_transform_edt(distance[i,:,:,:])*[unitlength]*3
distance.shape = (len(feature_list),resolution.prod()) distance.shape = (len(feature_list),grid.prod())
# ------------------------------------------ process data --------------------------------------- # ------------------------------------------ process data ------------------------------------------
table.data_rewind() table.data_rewind()
l = 0 l = 0
while table.data_read(): while table.data_read():
@ -196,9 +196,9 @@ for file in files:
l += 1 l += 1
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table (works for stdout) file['output'].close() # close output ASCII table
os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -69,7 +69,7 @@ toRadians = math.pi/180.0 if options.degrees else 1.0
pole = np.array(options.pole) pole = np.array(options.pole)
pole /= np.linalg.norm(pole) pole /= np.linalg.norm(pole)
# ------------------------------------------ setup file handles ----------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -108,7 +108,7 @@ for file in files:
table.labels_append(['%i_IPF_%g%g%g'%(i+1,options.pole[0],options.pole[1],options.pole[2]) for i in xrange(3)]) table.labels_append(['%i_IPF_%g%g%g'%(i+1,options.pole[0],options.pole[1],options.pole[2]) for i in xrange(3)])
table.head_write() table.head_write()
# ------------------------------------------ process data ---------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
if input == 'eulers': if input == 'eulers':
@ -136,7 +136,7 @@ for file in files:
table.data_append(o.IPFcolor(pole)) table.data_append(o.IPFcolor(pole))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
from optparse import OptionParser from optparse import OptionParser
import damask import damask
@ -57,7 +57,7 @@ if options.vector != None: datainfo['vector']['label'] += options.vector
if options.tensor != None: datainfo['tensor']['label'] += options.tensor if options.tensor != None: datainfo['tensor']['label'] += options.tensor
if options.special != None: datainfo['special']['label'] += options.special if options.special != None: datainfo['special']['label'] += options.special
# ------------------------------------------ processing mapping ASCIItable --------------------------- # ------------------------------------------ processing mapping ASCIItable -------------------------
if options.asciitable != None and os.path.isfile(options.asciitable): if options.asciitable != None and os.path.isfile(options.asciitable):
mappedTable = damask.ASCIItable(open(options.asciitable),None,False) mappedTable = damask.ASCIItable(open(options.asciitable),None,False)
mappedTable.head_read() # read ASCII header info of mapped table mappedTable.head_read() # read ASCII header info of mapped table
@ -83,7 +83,7 @@ if options.asciitable != None and os.path.isfile(options.asciitable):
else: else:
parser.error('missing mapped ASCIItable...') parser.error('missing mapped ASCIItable...')
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -92,7 +92,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
# ------------------------------------------ loop over input files --------------------------------------- # ------------------------------------------ loop over input files ---------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -105,21 +105,21 @@ for file in files:
file['croak'].write('column %s not found...\n'%options.map) file['croak'].write('column %s not found...\n'%options.map)
continue continue
# ------------------------------------------ assemble header ------------------------------------ # ------------------------------------------ assemble header --------------------------------------
for datatype,info in datainfo.items(): for datatype,info in datainfo.items():
for label in info['label']: for label in info['label']:
table.labels_append({True:['%i_%s'%(i+1,label) for i in xrange(info['len'])], table.labels_append({True:['%i_%s'%(i+1,label) for i in xrange(info['len'])],
False:table.labels_append(label)}[info['len']>1] ) # extend ASCII header of current table with new labels False:table.labels_append(label)}[info['len']>1] ) # extend ASCII header of current table with new labels
table.head_write() table.head_write()
# ------------------------------------------ process data ---------------------------------------- # ------------------------------------------ process data ------------------------------------------
mappedColumn = table.labels.index(options.map) mappedColumn = table.labels.index(options.map)
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
table.data_append(mappedTable.data[int(table.data[mappedColumn])+options.offset-1]) # add all mapped data types table.data_append(mappedTable.data[int(table.data[mappedColumn])+options.offset-1]) # add all mapped data types
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,math,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -51,7 +51,7 @@ datainfo = {
if options.strain != None: datainfo['strain']['label'] += options.strain if options.strain != None: datainfo['strain']['label'] += options.strain
if options.stress != None: datainfo['stress']['label'] += options.stress if options.stress != None: datainfo['stress']['label'] += options.stress
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -60,7 +60,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
# ------------------------------------------ loop over input files --------------------------------------- # ------------------------------------------ loop over input files ---------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -87,7 +87,7 @@ for file in files:
table.labels_append('Mises(%s)'%label) # extend ASCII header with new labels table.labels_append('Mises(%s)'%label) # extend ASCII header with new labels
table.head_write() table.head_write()
# ------------------------------------------ process data ---------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
for datatype,labels in active.items(): # loop over vector,tensor for datatype,labels in active.items(): # loop over vector,tensor
@ -97,7 +97,7 @@ for file in files:
column[datatype][label]+datainfo[datatype]['len']]),'d').reshape(3,3))) column[datatype][label]+datainfo[datatype]['len']]),'d').reshape(3,3)))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,math,string
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
import damask import damask
@ -63,7 +63,7 @@ if options.vector != None: datainfo['vector']['label'] += options.vector
if options.tensor != None: datainfo['tensor']['label'] += options.tensor if options.tensor != None: datainfo['tensor']['label'] += options.tensor
if options.special != None: datainfo['special']['label'] += options.special if options.special != None: datainfo['special']['label'] += options.special
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -72,7 +72,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
#--- loop over input files ------------------------------------------------------------------------ #--- loop over input files -------------------------------------------------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -100,15 +100,16 @@ for file in files:
table.labels_append('norm%s(%s)'%(options.norm.capitalize(),label)) # extend ASCII header with new labels table.labels_append('norm%s(%s)'%(options.norm.capitalize(),label)) # extend ASCII header with new labels
table.head_write() table.head_write()
# ------------------------------------------ process data --------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
for datatype,labels in active.items(): # loop over vector,tensor for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested norms for label in labels: # loop over all requested norms
eval("table.data_append(norm%s(map(float,table.data[column[datatype][label]:column[datatype][label]+datainfo[datatype]['len']])))"%options.norm.capitalize()) eval("table.data_append(norm%s(map(float,table.data[column[datatype][label]:"\
"column[datatype][label]+datainfo[datatype]['len']])))"%options.norm.capitalize())
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,sys,string,itertools,re,math,numpy import os,sys,string,itertools
import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
import damask import damask
@ -60,12 +61,20 @@ datainfo = { # lis
if not set(options.output).issubset(set(outputChoices)): if not set(options.output).issubset(set(outputChoices)):
parser.error('output must be chosen from %s...'%(', '.join(outputChoices))) parser.error('output must be chosen from %s...'%(', '.join(outputChoices)))
if options.eulers != None: datainfo['vector']['label'] += [options.eulers]; input = 'eulers' if options.eulers != None:
datainfo['vector']['label'] += [options.eulers]
input = 'eulers'
if options.a != None and \ if options.a != None and \
options.b != None and \ options.b != None and \
options.c != None: datainfo['vector']['label'] += [options.a,options.b,options.c]; input = 'frame' options.c != None:
if options.matrix != None: datainfo['tensor']['label'] += [options.matrix]; input = 'matrix' datainfo['vector']['label'] += [options.a,options.b,options.c]
if options.quaternion != None: datainfo['quaternion']['label'] += [options.quaternion]; input = 'quaternion' input = 'frame'
if options.matrix != None:
datainfo['tensor']['label'] += [options.matrix]
input = 'matrix'
if options.quaternion != None:
datainfo['quaternion']['label'] += [options.quaternion]
input = 'quaternion'
inputGiven = 0 inputGiven = 0
for datatype,info in datainfo.items(): for datatype,info in datainfo.items():
@ -77,7 +86,7 @@ options.output = map(lambda x: x.lower(), options.output)
r = damask.Quaternion().fromAngleAxis(toRadians*options.rotation[0],options.rotation[1:]) r = damask.Quaternion().fromAngleAxis(toRadians*options.rotation[0],options.rotation[1:])
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
@ -87,7 +96,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
# ------------------------------------------ loop over input files ---------------------------------- # ------------------------------------------ loop over input files ---------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -121,19 +130,22 @@ for file in files:
table.labels_append(['%i_eulers_%s'%(i+1,options.symmetry) for i in xrange(3)]) table.labels_append(['%i_eulers_%s'%(i+1,options.symmetry) for i in xrange(3)])
table.head_write() table.head_write()
# ------------------------------------------ process data ---------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
if input == 'eulers': if input == 'eulers':
o = damask.Orientation(Eulers=toRadians*numpy.array(map(float,table.data[column['vector'][options.eulers]:\ o = damask.Orientation(Eulers=toRadians*\
np.array(map(float,table.data[column['vector'][options.eulers]:\
column['vector'][options.eulers]+datainfo['vector']['len']])), column['vector'][options.eulers]+datainfo['vector']['len']])),
symmetry=options.symmetry).reduced() symmetry=options.symmetry).reduced()
elif input == 'matrix': elif input == 'matrix':
o = damask.Orientation(matrix=numpy.array([map(float,table.data[column['tensor'][options.matrix]:\ o = damask.Orientation(matrix=\
np.array([map(float,table.data[column['tensor'][options.matrix]:\
column['tensor'][options.matrix]+datainfo['tensor']['len']])]), column['tensor'][options.matrix]+datainfo['tensor']['len']])]),
symmetry=options.symmetry).reduced() symmetry=options.symmetry).reduced()
elif input == 'frame': elif input == 'frame':
o = damask.Orientation(matrix=numpy.array([map(float,table.data[column['vector'][options.a]:\ o = damask.Orientation(matrix=\
np.array([map(float,table.data[column['vector'][options.a]:\
column['vector'][options.a]+datainfo['vector']['len']] + \ column['vector'][options.a]+datainfo['vector']['len']] + \
table.data[column['vector'][options.b]:\ table.data[column['vector'][options.b]:\
column['vector'][options.b]+datainfo['vector']['len']] + \ column['vector'][options.b]+datainfo['vector']['len']] + \
@ -142,7 +154,8 @@ for file in files:
)]).reshape(3,3), )]).reshape(3,3),
symmetry=options.symmetry).reduced() symmetry=options.symmetry).reduced()
elif input == 'quaternion': elif input == 'quaternion':
o = damask.Orientation(quaternion=numpy.array(map(float,table.data[column['quaternion'][options.quaternion]:\ o = damask.Orientation(quaternion=\
np.array(map(float,table.data[column['quaternion'][options.quaternion]:\
column['quaternion'][options.quaternion]+datainfo['quaternion']['len']])), column['quaternion'][options.quaternion]+datainfo['quaternion']['len']])),
symmetry=options.symmetry).reduced() symmetry=options.symmetry).reduced()
@ -155,7 +168,7 @@ for file in files:
table.data_append(o.asEulers('Bunge')) table.data_append(o.asEulers('Bunge'))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -38,7 +38,7 @@ datainfo = {
datainfo['defgrad']['label'].append(options.defgrad) datainfo['defgrad']['label'].append(options.defgrad)
datainfo['stress']['label'].append(options.stress) datainfo['stress']['label'].append(options.stress)
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -47,7 +47,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
# ------------------------------------------ loop over input files --------------------------------------- # ------------------------------------------ loop over input files ---------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -73,11 +73,11 @@ for file in files:
if missingColumns: if missingColumns:
continue continue
# ------------------------------------------ assemble header ------------------------------------ # ------------------------------------------ assemble header --------------------------------------
table.labels_append(['%i_S'%(i+1) for i in xrange(datainfo['stress']['len'])]) # extend ASCII header with new labels table.labels_append(['%i_S'%(i+1) for i in xrange(datainfo['stress']['len'])]) # extend ASCII header with new labels
table.head_write() table.head_write()
# ------------------------------------------ process data ---------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
F = np.array(map(float,table.data[column['defgrad'][active['defgrad'][0]]: F = np.array(map(float,table.data[column['defgrad'][active['defgrad'][0]]:
@ -90,7 +90,7 @@ for file in files:
table.data_append(list(np.dot(np.linalg.inv(F),P).reshape(9))) # [S] =[P].[F-1] table.data_append(list(np.dot(np.linalg.inv(F),P).reshape(9))) # [S] =[P].[F-1]
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,math,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -309,7 +309,7 @@ if options.lattice=='hex':
slipnormal[options.lattice][i]=normalize(slipnormal[options.lattice][i]) slipnormal[options.lattice][i]=normalize(slipnormal[options.lattice][i])
slipdirection[options.lattice][i]=normalize(slipdirection[options.lattice][i]) slipdirection[options.lattice][i]=normalize(slipdirection[options.lattice][i])
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -318,7 +318,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
# ------------------------------------------ loop over input files --------------------------------------- # ------------------------------------------ loop over input files ---------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -360,7 +360,7 @@ for file in files:
table.labels_append(['(%i)tx\tty\ttz'%(i+1) for i in range(Nslipsystems[options.lattice])]) table.labels_append(['(%i)tx\tty\ttz'%(i+1) for i in range(Nslipsystems[options.lattice])])
table.head_write() table.head_write()
# ------------------------------------------ process data ---------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
[phi1,Phi,phi2] = Eulers=toRadians*np.array(map(\ [phi1,Phi,phi2] = Eulers=toRadians*np.array(map(\
@ -382,7 +382,7 @@ for file in files:
table.data_append('\t'.join(map(str,trace[SabsSorted[-options.rank][1]])) + '\t%i'%(1+SabsSorted[-options.rank][1])) table.data_append('\t'.join(map(str,trace[SabsSorted[-options.rank][1]])) + '\t%i'%(1+SabsSorted[-options.rank][1]))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -41,7 +41,7 @@ for name in filenames:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
#--- loop over input files ------------------------------------------------------------------------ #--- loop over input files -------------------------------------------------------------------------
for file in files: for file in files:
file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
@ -66,7 +66,7 @@ for file in files:
table.labels_append(['%i_eigvec(%s)'%(i+1,label) for i in xrange(9)]) # extend ASCII header with new labels table.labels_append(['%i_eigvec(%s)'%(i+1,label) for i in xrange(9)]) # extend ASCII header with new labels
table.head_write() table.head_write()
# ------------------------------------------ process data ---------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
for labels in active: # loop over requested data for labels in active: # loop over requested data
@ -77,7 +77,7 @@ for file in files:
table.data_append(list(v.transpose().reshape(datainfo['tensor']['len']))) table.data_append(list(v.transpose().reshape(datainfo['tensor']['len'])))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string import os,sys,string
import numpy as np import numpy as np
from collections import defaultdict from collections import defaultdict
from optparse import OptionParser from optparse import OptionParser
@ -68,7 +68,7 @@ datainfo = {
datainfo['defgrad']['label'] = options.defgrad datainfo['defgrad']['label'] = options.defgrad
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr}) files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -77,7 +77,7 @@ else:
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr}) files.append({'name':name, 'input':open(name), 'output':open(name+'_tmp','w'), 'croak':sys.stderr})
# ------------------------------------------ loop over input files --------------------------------------- # ------------------------------------------ loop over input files ---------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n') else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
@ -106,7 +106,7 @@ for file in files:
{True: label,False: ''}[label!='f'])for i in xrange(9)]) # extend ASCII header with new labels {True: label,False: ''}[label!='f'])for i in xrange(9)]) # extend ASCII header with new labels
table.head_write() table.head_write()
# ------------------------------------------ process data ---------------------------------------- # ------------------------------------------ process data ------------------------------------------
outputAlive = True outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table while outputAlive and table.data_read(): # read next data line of ASCII table
for label in active: # loop over all requested norms for label in active: # loop over all requested norms
@ -135,7 +135,7 @@ for file in files:
table.data_append(list(eps)) table.data_append(list(eps))
outputAlive = table.data_write() # output processed line outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin) file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,190 +1,138 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string,numpy,damask,time import os,sys,string
from optparse import OptionParser, Option import numpy as np
from optparse import OptionParser
# ----------------------------- import damask
class extendableOption(Option):
# -----------------------------
# used for definition of new option parser action 'extend', which enables to take multiple option arguments
# taken from online tutorial http://docs.python.org/library/optparse.html
ACTIONS = Option.ACTIONS + ("extend",)
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
def take_action(self, action, dest, opt, value, values, parser):
if action == "extend":
lvalue = value.split(",")
values.ensure_value(dest, []).extend(lvalue)
else:
Option.take_action(self, action, dest, opt, value, values, parser)
def location(idx,res):
return numpy.array([ idx % res[0], \
(idx // res[0]) % res[1], \
(idx // res[0] // res[1]) % res[2] ])
def index(location,res):
return ( location[0] % res[0] + \
(location[1] % res[1]) * res[0] + \
(location[2] % res[2]) * res[0] * res[1] )
scriptID = string.replace('$Id$','\n','\\n')
scriptName = scriptID.split()[1]
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# MAIN # MAIN
# -------------------------------------------------------------------- # --------------------------------------------------------------------
parser = OptionParser(option_class=extendableOption, usage='%prog [options] [file[s]]', description = """ parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [file[s]]', description = """
Average each data block of size 'packing' into single values thus reducing the former resolution Average each data block of size 'packing' into single values thus reducing the former grid to grid/packing.
to resolution/packing. (Requires numpy.)
""" + string.replace('$Id$','\n','\\n') """, version = scriptID)
)
parser.add_option('-c','--coordinates', dest='coords', type='string',\ parser.add_option('-c','--coordinates', dest='coords', action='store', type='string', metavar='string',
help='column heading for coordinates [%default]') help='column heading for coordinates [%default]')
parser.add_option('-p','--packing', dest='packing', type='int', nargs=3, \ parser.add_option('-p','--packing', dest='packing', action='store', type='int', nargs=3, metavar='int int int',
help='dimension of packed group %default') help='size of packed group %default')
parser.add_option('-s','--shift', dest='shift', type='int', nargs=3, \ parser.add_option('--shift', dest='shift', action='store', type='int', nargs=3, metavar='int int int',
help='shift vector of packing stencil %default') help='shift vector of packing stencil %default')
parser.add_option('-r','--resolution', dest='resolution', type='int', nargs=3, \ parser.add_option('-g', '--grid', dest='grid', action='store', type='int', nargs=3, metavar='int int int',
help='resolution in x,y,z [autodetect]') help='grid in x,y,z [autodetect]')
parser.add_option('-d','--dimension', dest='dimension', type='float', nargs=3, \ parser.add_option('-s', '--size', dest='size', action='store', type='float', nargs=3, metavar='float float float',
help='dimension in x,y,z [autodetect]') help='size in x,y,z [autodetect]')
parser.set_defaults(coords = 'ip') parser.set_defaults(coords = 'ip')
parser.set_defaults(packing = [2,2,2]) parser.set_defaults(packing = [2,2,2])
parser.set_defaults(shift = [0,0,0]) parser.set_defaults(shift = [0,0,0])
parser.set_defaults(resolution = [0,0,0]) parser.set_defaults(grid = [0,0,0])
parser.set_defaults(dimension = [0.0,0.0,0.0]) parser.set_defaults(size = [0.0,0.0,0.0])
(options,filenames) = parser.parse_args() (options,filenames) = parser.parse_args()
if len(options.packing) < 3: options.packing = np.array(options.packing)
parser.error('packing needs three parameters...') options.shift = np.array(options.shift)
if len(options.shift) < 3:
parser.error('shift needs three parameters...')
options.packing = numpy.array(options.packing)
options.shift = numpy.array(options.shift)
prefix = 'averagedDown%ix%ix%i_'%(options.packing[0],options.packing[1],options.packing[2]) prefix = 'averagedDown%ix%ix%i_'%(options.packing[0],options.packing[1],options.packing[2])
if numpy.any(options.shift != 0): if np.any(options.shift != 0):
prefix += 'shift%+i%+i%+i_'%(options.shift[0],options.shift[1],options.shift[2]) prefix += 'shift%+i%+i%+i_'%(options.shift[0],options.shift[1],options.shift[2])
# ------------------------------------------ setup file handles --------------------------------------- # ------------------------------------------ setup file handles ------------------------------------
files = [] files = []
if filenames == []: for name in filenames:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout})
else:
for name in filenames:
name = os.path.relpath(name)
if os.path.exists(name): if os.path.exists(name):
files.append({'name':name, 'input':open(name), files.append({'name':name, 'input':open(name), 'croak':sys.stderr,\
'output':open(os.path.join(os.path.dirname(name),prefix+os.path.basename(name)),'w')}) 'output':open(os.path.join(os.path.dirname(name),prefix+os.path.basename(name)),'w')})
#--- loop over input files ------------------------------------------------------------------------
# ------------------------------------------ loop over input files ---------------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': print file['name'], file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
table = damask.ASCIItable(file['input'],file['output'],False) # make unbuffered ASCII_table table = damask.ASCIItable(file['input'],file['output'],False) # make unbuffered ASCII_table
table.head_read() # read ASCII header info table.head_read() # read ASCII header info
table.info_append(string.replace('$Id$','\n','\\n') + \ table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
'\t' + ' '.join(sys.argv[1:]))
# --------------- figure out size and grid ----------------------------------------------
try: try:
locationCol = [] locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data
for i,direction in enumerate(['x','y','z']): elemCol = table.labels.index('elem')
locationCol.append(table.labels.index('%s.%s'%(options.coords,direction))) # columns containing location data
elemCol = table.labels.index('elem') # columns containing location data
except ValueError: except ValueError:
print 'no coordinate data or element data found...' file['croak'].write('no coordinate (%s.x) and/or elem data found...\n'%options.coords)
continue continue
if (any(options.resolution)==0 or any(options.dimension)==0.0): if (any(options.grid)==0 or any(options.size)==0.0):
grid = [{},{},{}] coords = [{},{},{}]
while table.data_read(): # read next data line of ASCII table while table.data_read(): # read next data line of ASCII table
for j in range(3): for j in xrange(3):
grid[j][str(table.data[locationCol[j]])] = True # remember coordinate along x,y,z coords[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
resolution = numpy.array([len(grid[0]),\ grid = np.array([len(coords[0]),\
len(grid[1]),\ len(coords[1]),\
len(grid[2]),],'i') # resolution is number of distinct coordinates found len(coords[2]),],'i') # resolution is number of distinct coordinates found
dimension = resolution/numpy.maximum(numpy.ones(3,'d'),resolution-1.0)* \ size = grid/np.maximum(np.ones(3,'d'),grid-1.0)* \
numpy.array([max(map(float,grid[0].keys()))-min(map(float,grid[0].keys())),\ np.array([max(map(float,coords[0].keys()))-min(map(float,coords[0].keys())),\
max(map(float,grid[1].keys()))-min(map(float,grid[1].keys())),\ max(map(float,coords[1].keys()))-min(map(float,coords[1].keys())),\
max(map(float,grid[2].keys()))-min(map(float,grid[2].keys())),\ max(map(float,coords[2].keys()))-min(map(float,coords[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness ],'d') # dimension from bounding box, corrected for cell-centeredness
origin = numpy.array([min(map(float,grid[0].keys())),\ origin = np.array([min(map(float,coords[0].keys())),\
min(map(float,grid[1].keys())),\ min(map(float,coords[1].keys())),\
min(map(float,grid[2].keys())),\ min(map(float,coords[2].keys())),\
],'d') - 0.5 * dimension / resolution ],'d') - 0.5 * size / grid
else: else:
resolution = numpy.array(options.resolution,'i') grid = np.array(options.grid,'i')
dimension = numpy.array(options.dimension,'d') size = np.array(options.size,'d')
origin = numpy.zeros(3,'d') origin = np.zeros(3,'d')
if resolution[2] == 1: for i, res in enumerate(grid):
options.packing[2] = 1 if res == 1:
options.shift[2] = 0 options.packing[i] = 1
dimension[2] = min(dimension[:2]/resolution[:2]) # z spacing equal to smaller of x or y spacing options.shift[i] = 0
mask = np.ones(3,dtype=bool)
mask[i]=0
size[i] = min(size[mask]/grid[mask]) # third spacing equal to smaller of other spacing
packing = numpy.array(options.packing,'i') packing = np.array(options.packing,'i')
shift = numpy.array(options.shift,'i') shift = np.array(options.shift,'i')
downSized = numpy.maximum(numpy.ones(3,'i'),resolution//packing) downSized = np.maximum(np.ones(3,'i'),grid//packing)
outSize = numpy.ceil(numpy.array(resolution,'d')/numpy.array(packing,'d')) outSize = np.ceil(np.array(grid,'d')/np.array(packing,'d'))
print '\t%s @ %s --> %s'%(dimension,resolution,downSized)
# ------------------------------------------ assemble header --------------------------------------- # ------------------------------------------ assemble header ---------------------------------------
table.head_write() table.head_write()
# ------------------------------------------ process data --------------------------------------- # ------------------------------------------ process data -----------------------------------------
table.data_rewind() table.data_rewind()
data = numpy.zeros(outSize.tolist()+[len(table.labels)]) data = np.zeros(outSize.tolist()+[len(table.labels)])
p = numpy.zeros(3,'i') p = np.zeros(3,'i')
for p[2] in xrange(resolution[2]): for p[2] in xrange(grid[2]):
for p[1] in xrange(resolution[1]): for p[1] in xrange(grid[1]):
for p[0] in xrange(resolution[0]): for p[0] in xrange(grid[0]):
d = ((p-shift)%resolution)//packing d = ((p-shift)%grid)//packing
table.data_read() table.data_read()
data[d[0],d[1],d[2],:] += numpy.array(table.data_asFloat(),'d') # convert to numpy array data[d[0],d[1],d[2],:] += np.array(table.data_asFloat(),'d') # convert to np array
data /= packing.prod() data /= packing.prod()
elementSize = size/grid*packing
elementSize = dimension/resolution*packing
posOffset = (shift+[0.5,0.5,0.5])*elementSize posOffset = (shift+[0.5,0.5,0.5])*elementSize
elem = 1 elem = 1
for c in xrange(downSized[2]): for c in xrange(downSized[2]):
for b in xrange(downSized[1]): for b in xrange(downSized[1]):
for a in xrange(downSized[0]): for a in xrange(downSized[0]):
for i,x in enumerate([a,b,c]): for i,x in enumerate([a,b,c]):
data[a,b,c,locationCol[i]] = posOffset[i] + x*elementSize[i] + origin[i] data[a,b,c,locationCol+i] = posOffset[i] + x*elementSize[i] + origin[i]
data[a,b,c,elemCol] = elem data[a,b,c,elemCol] = elem
table.data = data[a,b,c,:].tolist() table.data = data[a,b,c,:].tolist()
table.data_write() # output processed line table.data_write() # output processed line
elem += 1 elem += 1
# ------------------------------------------ output result ----------------------------------------
# ------------------------------------------ output result ---------------------------------------
table.output_flush() # just in case of buffered ASCII table table.output_flush() # just in case of buffered ASCII table
# ------------------------------------------ close file handles ---------------------------------------
for file in files:
file['input'].close() # close input ASCII table file['input'].close() # close input ASCII table
if file['name'] != 'STDIN':
file['output'].close() # close output ASCII table file['output'].close() # close output ASCII table