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)):
options.formulas[i]=options.formulas[i].replace(';',',')
# ------------------------------------------ setup file handles ---------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -99,7 +99,7 @@ for file in files:
for label in options.labels:
labelLen[label] = np.size(eval(eval(evaluator[label])))
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
for label,formula in zip(options.labels,options.formulas):
if labelLen[label] == 0:
brokenFormula[label] = True
@ -112,7 +112,7 @@ for file in files:
for label in options.labels: table.data_append(unravel(eval(eval(evaluator[label]))))
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

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

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
import numpy as np
from optparse import OptionParser
import damask
@ -42,13 +42,13 @@ datainfo = {
datainfo['defgrad']['label'].append(options.defgrad)
# ------------------------------------------ setup file handles -------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
for name in filenames:
if os.path.exists(name):
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:
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.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
# --------------- figure out dimension and resolution ----------------------------------------------
# --------------- figure out size and grid ---------------------------------------------------------
try:
locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data
except ValueError:
file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords)
continue
grid = [{},{},{}]
coords = [{},{},{}]
while table.data_read(): # read next data line of ASCII table
for j in xrange(3):
grid[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
res = np.array([len(grid[0]),\
len(grid[1]),\
len(grid[2]),],'i') # resolution is number of distinct coordinates found
geomdim = res/np.maximum(np.ones(3,'d'),res-1.0)* \
np.array([max(map(float,grid[0].keys()))-min(map(float,grid[0].keys())),\
max(map(float,grid[1].keys()))-min(map(float,grid[1].keys())),\
max(map(float,grid[2].keys()))-min(map(float,grid[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness
if res[2] == 1:
geomdim[2] = min(geomdim[:2]/res[:2])
N = res.prod()
coords[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
grid = np.array([len(coords[0]),\
len(coords[1]),\
len(coords[2]),],'i') # grid is number of distinct coordinates found
size = grid/np.maximum(np.ones(3,'d'),grid-1.0)* \
np.array([max(map(float,coords[0].keys()))-min(map(float,coords[0].keys())),\
max(map(float,coords[1].keys()))-min(map(float,coords[1].keys())),\
max(map(float,coords[2].keys()))-min(map(float,coords[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness
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 ---------------------------------------------------
missingColumns = False
@ -93,33 +100,33 @@ for file in files:
if missingColumns:
continue
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
if not options.noShape: table.labels_append(['shapeMismatch(%s)' %options.defgrad])
if not options.noVolume: table.labels_append(['volMismatch(%s)'%options.defgrad])
table.head_write()
# ------------------------------------------ read deformation gradient field -----------------------
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
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
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)
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)
if not options.noShape: shapeMismatch = damask.core.mesh.shapeMismatch( geomdim,F,nodes,centres)
if not options.noVolume: volumeMismatch = damask.core.mesh.volumeMismatch(geomdim,F,nodes)
nodes = damask.core.mesh.nodesAroundCentres(size,Favg,centres)
if not options.noShape: shapeMismatch = damask.core.mesh.shapeMismatch( size,F,nodes,centres)
if not options.noVolume: volumeMismatch = damask.core.mesh.volumeMismatch(size,F,nodes)
# ------------------------------------------ process data ---------------------------------------
# ------------------------------------------ process data ------------------------------------------
table.data_rewind()
idx = 0
outputAlive = True
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
if not options.noShape: table.data_append( shapeMismatch[x,y,z])
if not options.noVolume: table.data_append(volumeMismatch[x,y,z])
@ -128,6 +135,6 @@ for file in files:
# ------------------------------------------ output result ---------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)
file['output'].close() # close output ASCII table (works for stdout)
file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table
os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
import numpy as np
from collections import defaultdict
from optparse import OptionParser
@ -52,7 +52,7 @@ for name in filenames:
if os.path.exists(name):
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:
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.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
# --------------- figure out dimension and resolution ----------------------------------------------
# --------------- figure out size and grid ---------------------------------------------------------
try:
locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data
except ValueError:
file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords)
continue
grid = [{},{},{}]
coords = [{},{},{}]
while table.data_read(): # read next data line of ASCII table
for j in xrange(3):
grid[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
resolution = np.array([len(grid[0]),\
len(grid[1]),\
len(grid[2]),],'i') # resolution is number of distinct coordinates found
dimension = resolution/np.maximum(np.ones(3,'d'),resolution-1.0)* \
np.array([max(map(float,grid[0].keys()))-min(map(float,grid[0].keys())),\
max(map(float,grid[1].keys()))-min(map(float,grid[1].keys())),\
max(map(float,grid[2].keys()))-min(map(float,grid[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness
if resolution[2] == 1:
dimension[2] = min(dimension[:2]/resolution[:2])
N = resolution.prod()
coords[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
grid = np.array([len(coords[0]),\
len(coords[1]),\
len(coords[2]),],'i') # grid is number of distinct coordinates found
size = grid/np.maximum(np.ones(3,'d'),grid-1.0)* \
np.array([max(map(float,coords[0].keys()))-min(map(float,coords[0].keys())),\
max(map(float,coords[1].keys()))-min(map(float,coords[1].keys())),\
max(map(float,coords[2].keys()))-min(map(float,coords[2].keys())),\
],'d') # size from bounding box, corrected for cell-centeredness
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
# --------------- figure out columns to process --------------------------------------------------
N = grid.prod()
# --------------- figure out columns to process ---------------------------------------------------
active = defaultdict(list)
column = defaultdict(dict)
values = defaultdict(dict)
@ -98,11 +105,11 @@ for file in files:
active[datatype].append(label)
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'])]).\
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'])]).\
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 label in labels:
table.labels_append(['%i_curlFFT(%s)'%(i+1,label)
@ -113,7 +120,7 @@ for file in files:
table.data_rewind()
idx = 0
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
for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested curls
@ -125,23 +132,23 @@ for file in files:
# ------------------------------------------ process value field -----------------------------------
for datatype,labels in active.items(): # loop over vector,tensor
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()
idx = 0
outputAlive = True
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
for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested norms
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
file['input'].close() # close input ASCII table (works for stdin)
file['output'].close() # close output ASCII table (works for stdout)
file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table
os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
import numpy as np
from collections import defaultdict
from optparse import OptionParser
@ -39,13 +39,13 @@ datainfo = {
datainfo['defgrad']['label'].append(options.defgrad)
# ------------------------------------------ setup file handles -------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
for name in filenames:
if os.path.exists(name):
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:
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.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
# --------------- figure out dimension and resolution ----------------------------------------------
# --------------- figure out size and grid ---------------------------------------------------------
try:
locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data
except ValueError:
file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords)
continue
grid = [{},{},{}]
coords = [{},{},{}]
while table.data_read(): # read next data line of ASCII table
for j in xrange(3):
grid[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
res = np.array([len(grid[0]),\
len(grid[1]),\
len(grid[2]),],'i') # resolution is number of distinct coordinates found
geomdim = res/np.maximum(np.ones(3,'d'),res-1.0)* \
np.array([max(map(float,grid[0].keys()))-min(map(float,grid[0].keys())),\
max(map(float,grid[1].keys()))-min(map(float,grid[1].keys())),\
max(map(float,grid[2].keys()))-min(map(float,grid[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness
if res[2] == 1:
geomdim[2] = min(geomdim[:2]/res[:2])
N = res.prod()
coords[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
grid = np.array([len(coords[0]),\
len(coords[1]),\
len(coords[2]),],'i') # grid is number of distinct coordinates found
size = grid/np.maximum(np.ones(3,'d'),grid-1.0)* \
np.array([max(map(float,coords[0].keys()))-min(map(float,coords[0].keys())),\
max(map(float,coords[1].keys()))-min(map(float,coords[1].keys())),\
max(map(float,coords[2].keys()))-min(map(float,coords[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness
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 ---------------------------------------------------
missingColumns = False
@ -85,44 +92,44 @@ for file in files:
file['croak'].write('column %s not found...\n'%key)
missingColumns = True
else:
column = table.labels.index(key) # remember columns of requested data
column = table.labels.index(key) # remember columns of requested data
if missingColumns:
continue
# ------------------------------------------ assemble header ---------------------------------------
table.labels_append(['%s_coords'%(coord+1) for coord in xrange(3)]) # extend ASCII header with new labels
# ------------------------------------------ assemble header ---------------------------------------
table.labels_append(['%s_coords'%(coord+1) for coord in xrange(3)]) # extend ASCII header with new labels
table.head_write()
# ------------------------------------------ read deformation gradient field -----------------------
# ------------------------------------------ read deformation gradient field -----------------------
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
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
F[0:3,0:3,x,y,z] = np.array(map(float,table.data[column:column+9]),'d').reshape(3,3)
# ------------------------------------------ calculate coordinates ---------------------------------
Favg = damask.core.math.tensorAvg(F)
if options.linearreconstruction:
centroids = damask.core.mesh.deformedCoordsLin(geomdim,F,Favg)
centroids = damask.core.mesh.deformedCoordsLin(size,F,Favg)
else:
centroids = damask.core.mesh.deformedCoordsFFT(geomdim,F,Favg)
centroids = damask.core.mesh.deformedCoordsFFT(size,F,Favg)
# ------------------------------------------ process data ------------------------------------------
table.data_rewind()
idx = 0
outputAlive = True
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
table.data_append(list(centroids[:,x,y,z]))
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)
file['output'].close() # close output ASCII table (works for stdout)
file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table
os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
from collections import defaultdict
from optparse import OptionParser
import damask
@ -42,7 +42,7 @@ datainfo = {
datainfo['tensor']['label'] += options.tensor
# ------------------------------------------ setup file handles -----------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -51,7 +51,7 @@ else:
if os.path.exists(name):
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:
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')
@ -71,12 +71,12 @@ for file in files:
active.append(label)
column[label] = table.labels.index(key) # remember columns of requested data
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
for label in active:
table.labels_append('det(%s)'%label) # extend ASCII header with new labels
table.head_write()
# ------------------------------------------ process data ---------------------------------------
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table
for label in active:
@ -84,7 +84,7 @@ for file in files:
column[label]+datainfo['tensor']['len']])))
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
from collections import defaultdict
from optparse import OptionParser
import damask
@ -46,7 +46,7 @@ datainfo = {
datainfo['tensor']['label'] += options.tensor
# ------------------------------------------ setup file handles -----------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -55,7 +55,7 @@ else:
if os.path.exists(name):
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:
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')
@ -75,13 +75,13 @@ for file in files:
active.append(label)
column[label] = table.labels.index(key) # remember columns of requested data
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
for label in active:
table.labels_append(['%i_dev(%s)'%(i+1,label) for i in xrange(9)]) # extend ASCII header with new labels
if(options.hydrostatic): table.labels_append('sph(%s)'%label)
table.head_write()
# ------------------------------------------ process data ---------------------------------------
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table
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]))
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
import numpy as np
from collections import defaultdict
from optparse import OptionParser
@ -65,7 +65,7 @@ for name in filenames:
if os.path.exists(name):
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:
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.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
# --------------- figure out dimension and resolution ----------------------------------------------
# --------------- figure out size and grid ---------------------------------------------------------
try:
locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data
except ValueError:
file['croak'].write('no coordinate data (%s.x) found...\n'%options.coords)
continue
grid = [{},{},{}]
coords = [{},{},{}]
while table.data_read(): # read next data line of ASCII table
for j in xrange(3):
grid[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
resolution = np.array([len(grid[0]),\
len(grid[1]),\
len(grid[2]),],'i') # resolution is number of distinct coordinates found
dimension = resolution/np.maximum(np.ones(3,'d'),resolution-1.0)* \
np.array([max(map(float,grid[0].keys()))-min(map(float,grid[0].keys())),\
max(map(float,grid[1].keys()))-min(map(float,grid[1].keys())),\
max(map(float,grid[2].keys()))-min(map(float,grid[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness
if resolution[2] == 1:
dimension[2] = min(dimension[:2]/resolution[:2])
N = resolution.prod()
coords[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
grid = np.array([len(coords[0]),\
len(coords[1]),\
len(coords[2]),],'i') # grid is number of distinct coordinates found
size = grid/np.maximum(np.ones(3,'d'),grid-1.0)* \
np.array([max(map(float,coords[0].keys()))-min(map(float,coords[0].keys())),\
max(map(float,coords[1].keys()))-min(map(float,coords[1].keys())),\
max(map(float,coords[2].keys()))-min(map(float,coords[2].keys())),\
],'d') # size from bounding box, corrected for cell-centeredness
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
# --------------- figure out columns to process --------------------------------------------------
N = grid.prod()
# --------------- figure out columns to process ---------------------------------------------------
active = defaultdict(list)
column = defaultdict(dict)
values = defaultdict(dict)
@ -111,13 +118,13 @@ for file in files:
active[datatype].append(label)
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'])]).\
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] = {}
for accuracy in options.accuracy:
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 label in labels:
for accuracy in options.accuracy:
@ -129,7 +136,7 @@ for file in files:
table.data_rewind()
idx = 0
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
for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested curls
@ -143,26 +150,28 @@ for file in files:
for label in labels: # loop over all requested divergencies
for accuracy in options.accuracy:
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:
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()
idx = 0
outputAlive = True
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
for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested
for accuracy in options.accuracy:
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
file['input'].close() # close input ASCII table (works for stdin)
file['output'].close() # close output ASCII table (works for stdout)
file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table
os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
import numpy as np
from collections import defaultdict
from optparse import OptionParser
@ -49,14 +49,14 @@ parser.set_defaults(hkl = [1,1,1])
if len(options.vector)== 0:
parser.error('no data column specified...')
datainfo = { # list of requested labels per datatype
datainfo = { # list of requested labels per datatype
'vector': {'len':3,
'label':[]},
}
datainfo['vector']['label'] += options.vector
# ------------------------------------------ setup file handles ---------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
@ -66,7 +66,7 @@ else:
if os.path.exists(name):
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:
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')
@ -86,14 +86,14 @@ for file in files:
active.append(label)
column[label] = table.labels.index(key) # remember columns of requested data
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
for label in active:
table.labels_append('E%i%i%i(%s)'%(options.hkl[0],
options.hkl[1],
options.hkl[2],label)) # extend ASCII header with new labels
table.head_write()
# ------------------------------------------ process data ----------------------------------------
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table
for label in active:
@ -101,7 +101,7 @@ for file in files:
column[label]+datainfo['vector']['len']]),options.hkl))
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
import numpy as np
from optparse import OptionParser
from scipy import ndimage
@ -112,7 +112,7 @@ if 'biplane' in options.type and 'boundary' in options.type:
feature_list = []
for i,feature in enumerate(features):
if feature['name'] in options.type: feature_list.append(i) # remember valid features
# ------------------------------------------ setup file handles -----------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
for name in filenames:
@ -138,29 +138,29 @@ for file in files:
file['croak'].write('column %s not found...\n'%options.id)
continue
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
for feature in feature_list:
table.labels_append('ED_%s(%s)'%(features[feature]['name'],options.id)) # extend ASCII header with new labels
table.head_write()
# ------------------------------------------ process data ---------------------------------------
# ------------------------------------------ process data ------------------------------------------
table.data_readArray([options.coords+'.x',options.coords+'.y',options.coords+'.z',options.id])
grid = [{},{},{}]
coords = [{},{},{}]
for i in xrange(len(table.data)):
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
for i,r in enumerate(resolution):
if r > 1: unitlength = max(unitlength,(max(map(float,grid[i].keys()))-min(map(float,grid[i].keys())))/(r-1.0))
for i,r in enumerate(grid):
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]
convoluted = np.empty([len(neighborhood)]+list(resolution+2),'i')
microstructure = periodic_3Dpad(np.array(table.data[:,3].reshape(resolution),'i'))
convoluted = np.empty([len(neighborhood)]+list(grid+2),'i')
microstructure = periodic_3Dpad(np.array(table.data[:,3].reshape(grid),'i'))
for i,p in enumerate(neighborhood):
stencil = np.zeros((3,3,3),'i')
@ -171,11 +171,11 @@ for file in files:
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)
uniques = np.zeros(resolution)
check = np.empty(resolution)
uniques = np.zeros(grid)
check = np.empty(grid)
check[:,:,:] = np.nan
for i in xrange(len(neighborhood)):
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)):
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()
l = 0
while table.data_read():
@ -196,9 +196,9 @@ for file in files:
l += 1
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)
file['output'].close() # close output ASCII table (works for stdout)
file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table
os.rename(file['name']+'_tmp',file['name']) # overwrite old one with tmp new

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
import numpy as np
from collections import defaultdict
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.linalg.norm(pole)
# ------------------------------------------ setup file handles -----------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -104,11 +104,11 @@ for file in files:
if missingColumns:
continue
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
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()
# ------------------------------------------ process data ----------------------------------------
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table
if input == 'eulers':
@ -136,7 +136,7 @@ for file in files:
table.data_append(o.IPFcolor(pole))
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
from optparse import OptionParser
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.special != None: datainfo['special']['label'] += options.special
# ------------------------------------------ processing mapping ASCIItable ---------------------------
# ------------------------------------------ processing mapping ASCIItable -------------------------
if options.asciitable != None and os.path.isfile(options.asciitable):
mappedTable = damask.ASCIItable(open(options.asciitable),None,False)
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:
parser.error('missing mapped ASCIItable...')
# ------------------------------------------ setup file handles ---------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -92,7 +92,7 @@ else:
if os.path.exists(name):
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:
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')
@ -105,21 +105,21 @@ for file in files:
file['croak'].write('column %s not found...\n'%options.map)
continue
# ------------------------------------------ assemble header ------------------------------------
# ------------------------------------------ assemble header --------------------------------------
for datatype,info in datainfo.items():
for label in info['label']:
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
table.head_write()
# ------------------------------------------ process data ----------------------------------------
# ------------------------------------------ process data ------------------------------------------
mappedColumn = table.labels.index(options.map)
outputAlive = True
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
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,math,string
import numpy as np
from collections import defaultdict
from optparse import OptionParser
@ -51,7 +51,7 @@ datainfo = {
if options.strain != None: datainfo['strain']['label'] += options.strain
if options.stress != None: datainfo['stress']['label'] += options.stress
# ------------------------------------------ setup file handles ---------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -60,7 +60,7 @@ else:
if os.path.exists(name):
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:
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')
@ -81,13 +81,13 @@ for file in files:
active[datatype].append(label)
column[datatype][label] = table.labels.index(key) # remember columns of requested data
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested determinants
table.labels_append('Mises(%s)'%label) # extend ASCII header with new labels
table.head_write()
# ------------------------------------------ process data ----------------------------------------
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table
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)))
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,math,string
from collections import defaultdict
from optparse import OptionParser
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.special != None: datainfo['special']['label'] += options.special
# ------------------------------------------ setup file handles ---------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -72,7 +72,7 @@ else:
if os.path.exists(name):
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:
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')
@ -94,21 +94,22 @@ for file in files:
active[datatype].append(label)
column[datatype][label] = table.labels.index(key) # remember columns of requested data
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
for datatype,labels in active.items(): # loop over vector,tensor
for label in labels: # loop over all requested determinants
table.labels_append('norm%s(%s)'%(options.norm.capitalize(),label)) # extend ASCII header with new labels
table.head_write()
# ------------------------------------------ process data ---------------------------------------
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table
for datatype,labels in active.items(): # loop over vector,tensor
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
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,8 @@
#!/usr/bin/env python
# -*- 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 optparse import OptionParser
import damask
@ -60,12 +61,20 @@ datainfo = { # lis
if not set(options.output).issubset(set(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 \
options.b != None and \
options.c != None: datainfo['vector']['label'] += [options.a,options.b,options.c]; input = 'frame'
if options.matrix != None: datainfo['tensor']['label'] += [options.matrix]; input = 'matrix'
if options.quaternion != None: datainfo['quaternion']['label'] += [options.quaternion]; input = 'quaternion'
options.c != None:
datainfo['vector']['label'] += [options.a,options.b,options.c]
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
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:])
# ------------------------------------------ setup file handles ---------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
@ -87,7 +96,7 @@ else:
if os.path.exists(name):
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:
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')
@ -113,7 +122,7 @@ for file in files:
if missingColumns:
continue
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
for output in options.output:
if output == 'quaternion':
table.labels_append(['%i_quaternion_%s'%(i+1,options.symmetry) for i in xrange(4)])
@ -121,29 +130,33 @@ for file in files:
table.labels_append(['%i_eulers_%s'%(i+1,options.symmetry) for i in xrange(3)])
table.head_write()
# ------------------------------------------ process data ----------------------------------------
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table
if input == 'eulers':
o = damask.Orientation(Eulers=toRadians*numpy.array(map(float,table.data[column['vector'][options.eulers]:\
column['vector'][options.eulers]+datainfo['vector']['len']])),
o = damask.Orientation(Eulers=toRadians*\
np.array(map(float,table.data[column['vector'][options.eulers]:\
column['vector'][options.eulers]+datainfo['vector']['len']])),
symmetry=options.symmetry).reduced()
elif input == 'matrix':
o = damask.Orientation(matrix=numpy.array([map(float,table.data[column['tensor'][options.matrix]:\
column['tensor'][options.matrix]+datainfo['tensor']['len']])]),
o = damask.Orientation(matrix=\
np.array([map(float,table.data[column['tensor'][options.matrix]:\
column['tensor'][options.matrix]+datainfo['tensor']['len']])]),
symmetry=options.symmetry).reduced()
elif input == 'frame':
o = damask.Orientation(matrix=numpy.array([map(float,table.data[column['vector'][options.a]:\
column['vector'][options.a]+datainfo['vector']['len']] + \
table.data[column['vector'][options.b]:\
column['vector'][options.b]+datainfo['vector']['len']] + \
table.data[column['vector'][options.c]:\
column['vector'][options.c]+datainfo['vector']['len']]
o = damask.Orientation(matrix=\
np.array([map(float,table.data[column['vector'][options.a]:\
column['vector'][options.a]+datainfo['vector']['len']] + \
table.data[column['vector'][options.b]:\
column['vector'][options.b]+datainfo['vector']['len']] + \
table.data[column['vector'][options.c]:\
column['vector'][options.c]+datainfo['vector']['len']]
)]).reshape(3,3),
symmetry=options.symmetry).reduced()
elif input == 'quaternion':
o = damask.Orientation(quaternion=numpy.array(map(float,table.data[column['quaternion'][options.quaternion]:\
column['quaternion'][options.quaternion]+datainfo['quaternion']['len']])),
o = damask.Orientation(quaternion=\
np.array(map(float,table.data[column['quaternion'][options.quaternion]:\
column['quaternion'][options.quaternion]+datainfo['quaternion']['len']])),
symmetry=options.symmetry).reduced()
o.quaternion = r*o.quaternion
@ -155,7 +168,7 @@ for file in files:
table.data_append(o.asEulers('Bunge'))
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
import numpy as np
from collections import defaultdict
from optparse import OptionParser
@ -38,7 +38,7 @@ datainfo = {
datainfo['defgrad']['label'].append(options.defgrad)
datainfo['stress']['label'].append(options.stress)
# ------------------------------------------ setup file handles ---------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -47,7 +47,7 @@ else:
if os.path.exists(name):
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:
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')
@ -73,11 +73,11 @@ for file in files:
if missingColumns:
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.head_write()
# ------------------------------------------ process data ----------------------------------------
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
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]]:
@ -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]
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,math,string
import numpy as np
from collections import defaultdict
from optparse import OptionParser
@ -309,7 +309,7 @@ if options.lattice=='hex':
slipnormal[options.lattice][i]=normalize(slipnormal[options.lattice][i])
slipdirection[options.lattice][i]=normalize(slipdirection[options.lattice][i])
# ------------------------------------------ setup file handles ---------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout, 'croak':sys.stderr})
@ -318,7 +318,7 @@ else:
if os.path.exists(name):
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:
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')
@ -342,7 +342,7 @@ for file in files:
file['croak'].write('column %s not found...\n'%label)
break
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
table.labels_append(['%i_S(%i_%i_%i)[%i_%i_%i]'%(i+1,
slipnormal[options.lattice][i][0],
@ -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.head_write()
# ------------------------------------------ process data ----------------------------------------
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table
[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]))
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string
import os,sys,string
import numpy as np
from collections import defaultdict
from optparse import OptionParser
@ -41,7 +41,7 @@ for name in filenames:
if os.path.exists(name):
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:
file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
@ -60,13 +60,13 @@ for file in files:
active.append(label)
column[label] = table.labels.index(key) # remember columns of requested data
# ------------------------------------------ assemble header ---------------------------------------
# ------------------------------------------ assemble header ---------------------------------------
for labels in active:
table.labels_append(['%i_eigval(%s)'%(i+1,label) for i in xrange(3)]) # 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()
# ------------------------------------------ process data ----------------------------------------
# ------------------------------------------ process data ------------------------------------------
outputAlive = True
while outputAlive and table.data_read(): # read next data line of ASCII table
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'])))
outputAlive = table.data_write() # output processed line
# ------------------------------------------ output result ---------------------------------------
# ------------------------------------------ output result -----------------------------------------
outputAlive and table.output_flush() # just in case of buffered ASCII table
file['input'].close() # close input ASCII table (works for stdin)

View File

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

View File

@ -1,190 +1,138 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,string,numpy,damask,time
from optparse import OptionParser, Option
# -----------------------------
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] )
import os,sys,string
import numpy as np
from optparse import OptionParser
import damask
scriptID = string.replace('$Id$','\n','\\n')
scriptName = scriptID.split()[1]
# --------------------------------------------------------------------
# MAIN
# --------------------------------------------------------------------
parser = OptionParser(option_class=extendableOption, usage='%prog [options] [file[s]]', description = """
Average each data block of size 'packing' into single values thus reducing the former resolution
to resolution/packing. (Requires numpy.)
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 grid to grid/packing.
""" + 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]')
parser.add_option('-p','--packing', dest='packing', type='int', nargs=3, \
help='dimension of packed group %default')
parser.add_option('-s','--shift', dest='shift', type='int', nargs=3, \
parser.add_option('-p','--packing', dest='packing', action='store', type='int', nargs=3, metavar='int int int',
help='size of packed group %default')
parser.add_option('--shift', dest='shift', action='store', type='int', nargs=3, metavar='int int int',
help='shift vector of packing stencil %default')
parser.add_option('-r','--resolution', dest='resolution', type='int', nargs=3, \
help='resolution in x,y,z [autodetect]')
parser.add_option('-d','--dimension', dest='dimension', type='float', nargs=3, \
help='dimension in x,y,z [autodetect]')
parser.set_defaults(coords = 'ip')
parser.set_defaults(packing = [2,2,2])
parser.set_defaults(shift = [0,0,0])
parser.set_defaults(resolution = [0,0,0])
parser.set_defaults(dimension = [0.0,0.0,0.0])
parser.add_option('-g', '--grid', dest='grid', action='store', type='int', nargs=3, metavar='int int int',
help='grid in x,y,z [autodetect]')
parser.add_option('-s', '--size', dest='size', action='store', type='float', nargs=3, metavar='float float float',
help='size in x,y,z [autodetect]')
parser.set_defaults(coords = 'ip')
parser.set_defaults(packing = [2,2,2])
parser.set_defaults(shift = [0,0,0])
parser.set_defaults(grid = [0,0,0])
parser.set_defaults(size = [0.0,0.0,0.0])
(options,filenames) = parser.parse_args()
if len(options.packing) < 3:
parser.error('packing needs three parameters...')
if len(options.shift) < 3:
parser.error('shift needs three parameters...')
options.packing = numpy.array(options.packing)
options.shift = numpy.array(options.shift)
options.packing = np.array(options.packing)
options.shift = np.array(options.shift)
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])
# ------------------------------------------ setup file handles ---------------------------------------
# ------------------------------------------ setup file handles ------------------------------------
files = []
if 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):
files.append({'name':name, 'input':open(name),
'output':open(os.path.join(os.path.dirname(name),prefix+os.path.basename(name)),'w')})
# ------------------------------------------ loop over input files ---------------------------------------
for name in filenames:
if os.path.exists(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')})
#--- loop over input 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.head_read() # read ASCII header info
table.info_append(string.replace('$Id$','\n','\\n') + \
'\t' + ' '.join(sys.argv[1:]))
table = damask.ASCIItable(file['input'],file['output'],False) # make unbuffered ASCII_table
table.head_read() # read ASCII header info
table.info_append(scriptID + '\t' + ' '.join(sys.argv[1:]))
# --------------- figure out size and grid ----------------------------------------------
try:
locationCol = []
for i,direction in enumerate(['x','y','z']):
locationCol.append(table.labels.index('%s.%s'%(options.coords,direction))) # columns containing location data
elemCol = table.labels.index('elem') # columns containing location data
locationCol = table.labels.index('%s.x'%options.coords) # columns containing location data
elemCol = table.labels.index('elem')
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
if (any(options.resolution)==0 or any(options.dimension)==0.0):
grid = [{},{},{}]
while table.data_read(): # read next data line of ASCII table
for j in range(3):
grid[j][str(table.data[locationCol[j]])] = True # remember coordinate along x,y,z
resolution = numpy.array([len(grid[0]),\
len(grid[1]),\
len(grid[2]),],'i') # resolution is number of distinct coordinates found
dimension = resolution/numpy.maximum(numpy.ones(3,'d'),resolution-1.0)* \
numpy.array([max(map(float,grid[0].keys()))-min(map(float,grid[0].keys())),\
max(map(float,grid[1].keys()))-min(map(float,grid[1].keys())),\
max(map(float,grid[2].keys()))-min(map(float,grid[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness
origin = numpy.array([min(map(float,grid[0].keys())),\
min(map(float,grid[1].keys())),\
min(map(float,grid[2].keys())),\
],'d') - 0.5 * dimension / resolution
if (any(options.grid)==0 or any(options.size)==0.0):
coords = [{},{},{}]
while table.data_read(): # read next data line of ASCII table
for j in xrange(3):
coords[j][str(table.data[locationCol+j])] = True # remember coordinate along x,y,z
grid = np.array([len(coords[0]),\
len(coords[1]),\
len(coords[2]),],'i') # resolution is number of distinct coordinates found
size = grid/np.maximum(np.ones(3,'d'),grid-1.0)* \
np.array([max(map(float,coords[0].keys()))-min(map(float,coords[0].keys())),\
max(map(float,coords[1].keys()))-min(map(float,coords[1].keys())),\
max(map(float,coords[2].keys()))-min(map(float,coords[2].keys())),\
],'d') # dimension from bounding box, corrected for cell-centeredness
origin = np.array([min(map(float,coords[0].keys())),\
min(map(float,coords[1].keys())),\
min(map(float,coords[2].keys())),\
],'d') - 0.5 * size / grid
else:
resolution = numpy.array(options.resolution,'i')
dimension = numpy.array(options.dimension,'d')
origin = numpy.zeros(3,'d')
grid = np.array(options.grid,'i')
size = np.array(options.size,'d')
origin = np.zeros(3,'d')
if resolution[2] == 1:
options.packing[2] = 1
options.shift[2] = 0
dimension[2] = min(dimension[:2]/resolution[:2]) # z spacing equal to smaller of x or y spacing
for i, res in enumerate(grid):
if res == 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
packing = numpy.array(options.packing,'i')
shift = numpy.array(options.shift,'i')
downSized = numpy.maximum(numpy.ones(3,'i'),resolution//packing)
outSize = numpy.ceil(numpy.array(resolution,'d')/numpy.array(packing,'d'))
print '\t%s @ %s --> %s'%(dimension,resolution,downSized)
# ------------------------------------------ assemble header ---------------------------------------
packing = np.array(options.packing,'i')
shift = np.array(options.shift,'i')
downSized = np.maximum(np.ones(3,'i'),grid//packing)
outSize = np.ceil(np.array(grid,'d')/np.array(packing,'d'))
# ------------------------------------------ assemble header ---------------------------------------
table.head_write()
# ------------------------------------------ process data ---------------------------------------
# ------------------------------------------ process data -----------------------------------------
table.data_rewind()
data = numpy.zeros(outSize.tolist()+[len(table.labels)])
p = numpy.zeros(3,'i')
data = np.zeros(outSize.tolist()+[len(table.labels)])
p = np.zeros(3,'i')
for p[2] in xrange(resolution[2]):
for p[1] in xrange(resolution[1]):
for p[0] in xrange(resolution[0]):
d = ((p-shift)%resolution)//packing
for p[2] in xrange(grid[2]):
for p[1] in xrange(grid[1]):
for p[0] in xrange(grid[0]):
d = ((p-shift)%grid)//packing
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()
elementSize = dimension/resolution*packing
elementSize = size/grid*packing
posOffset = (shift+[0.5,0.5,0.5])*elementSize
elem = 1
for c in xrange(downSized[2]):
for b in xrange(downSized[1]):
for a in xrange(downSized[0]):
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
table.data = data[a,b,c,:].tolist()
table.data_write() # output processed line
table.data_write() # output processed line
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
if file['name'] != 'STDIN':
file['output'].close() # close output ASCII table
file['input'].close() # close input ASCII table
file['output'].close() # close output ASCII table