help now working if no mentat release present.

improved style
This commit is contained in:
Martin Diehl 2015-10-26 19:34:44 +00:00
parent 7ef5323f1e
commit 072be9c1bb
1 changed files with 59 additions and 63 deletions

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 sys,os,pwd,math,string import sys,os,string
import numpy as np import numpy as np
from optparse import OptionParser from optparse import OptionParser
import damask import damask
@ -11,13 +11,7 @@ scriptName = os.path.splitext(scriptID.split()[1])[0]
sys.path.append(damask.solver.Marc().libraryPath('../../')) sys.path.append(damask.solver.Marc().libraryPath('../../'))
try: active=[True,True,True] # directions on which to add PBC
from py_mentat import *
except:
print('error: no valid Mentat release found')
sys.exit(-1)
def outMentat(cmd,locals): def outMentat(cmd,locals):
if cmd[0:3] == '(!)': if cmd[0:3] == '(!)':
exec(cmd[3:]) exec(cmd[3:])
@ -28,26 +22,30 @@ def outMentat(cmd,locals):
py_send(cmd) py_send(cmd)
return return
def outStdout(cmd,locals): #-------------------------------------------------------------------------------------------------
def outFile(cmd,locals,dest):
#-------------------------------------------------------------------------------------------------
if cmd[0:3] == '(!)': if cmd[0:3] == '(!)':
exec(cmd[3:]) exec(cmd[3:])
elif cmd[0:3] == '(?)': elif cmd[0:3] == '(?)':
cmd = eval(cmd[3:]) cmd = eval(cmd[3:])
sys.stdout.write(cmd+'\n') dest.write(cmd+'\n')
else: else:
sys.stdout.write(cmd+'\n') dest.write(cmd+'\n')
return return
#-------------------------------------------------------------------------------------------------
def output(cmds,locals,dest): def output(cmds,locals,dest):
#-------------------------------------------------------------------------------------------------
for cmd in cmds: for cmd in cmds:
if isinstance(cmd,list): if isinstance(cmd,list):
output(cmd,locals,dest) output(cmd,locals,dest)
else: else:
{\ if dest == 'Mentat':
'Mentat': outMentat,\ outMentat(str(cmd),locals)
'Stdout': outStdout,\ else:
}[dest](cmd,locals) outFile(str(cmd),locals,dest)
return return
@ -66,7 +64,6 @@ def servoLink():
NodeCoords[node,0] = py_get_float("node_x(%i)"%(node+1)) NodeCoords[node,0] = py_get_float("node_x(%i)"%(node+1))
NodeCoords[node,1] = py_get_float("node_y(%i)"%(node+1)) NodeCoords[node,1] = py_get_float("node_y(%i)"%(node+1))
NodeCoords[node,2] = py_get_float("node_z(%i)"%(node+1)) NodeCoords[node,2] = py_get_float("node_z(%i)"%(node+1))
box['min'] = NodeCoords.min(axis=0) # find the bounding box box['min'] = NodeCoords.min(axis=0) # find the bounding box
box['max'] = NodeCoords.max(axis=0) box['max'] = NodeCoords.max(axis=0)
box['delta'] = box['max']-box['min'] box['delta'] = box['max']-box['min']
@ -74,13 +71,14 @@ def servoLink():
if box['delta'][coord] != 0.0: if box['delta'][coord] != 0.0:
for extremum in ['min','max']: for extremum in ['min','max']:
rounded = round(box[extremum][coord]*1e+15/box['delta'][coord]) * \ rounded = round(box[extremum][coord]*1e+15/box['delta'][coord]) * \
1e-15*box['delta'][coord] # rounding to 1e-15 of dimension 1e-15*box['delta'][coord] # rounding to 1e-15 of dimension
box[extremum][coord] = {False: rounded, box[extremum][coord] = 0.0 if rounded == 0.0 else rounded # get rid of -0.0 (negative zeros)
True: 0.0}[rounded == 0.0] # get rid of -0.0 (negative zeros)
baseNode = {} baseNode = {}
linkNodes = [] linkNodes = []
for node in xrange(Nnodes): # loop over all nodes #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# loop over all nodes
for node in xrange(Nnodes):
pos = {} pos = {}
key = {} key = {}
maxFlag = [False, False, False] maxFlag = [False, False, False]
@ -89,17 +87,16 @@ def servoLink():
for coord in xrange(3): # for each direction for coord in xrange(3): # for each direction
if box['delta'][coord] != 0.0: if box['delta'][coord] != 0.0:
rounded = round(NodeCoords[node,coord]*1e+15/box['delta'][coord]) * \ rounded = round(NodeCoords[node,coord]*1e+15/box['delta'][coord]) * \
1e-15*box['delta'][coord] # rounding to 1e-15 of dimension 1e-15*box['delta'][coord] # rounding to 1e-15 of dimension
NodeCoords[node,coord] = {False: rounded, NodeCoords[node,coord] = 0.0 if rounded == 0.0 else rounded # get rid of -0.0 (negative zeros)
True: 0.0}[rounded == 0.0] # get rid of -0.0 (negative zeros) key[base[coord]] = "%.8e"%NodeCoords[node,coord] # translate position to string
key[base[coord]] = "%.8e"%NodeCoords[node,coord] # translate position to string if (key[base[coord]] == "%.8e"%box['min'][coord]): # compare to min of bounding box (i.e. is on outer face?)
if (key[base[coord]] == "%.8e"%box['min'][coord]): # compare to min of bounding box (i.e. is on outer face?) Nmin += 1 # count outer (back) face membership
Nmin += 1 # count outer (back) face membership elif (key[base[coord]] == "%.8e"%box['max'][coord]): # compare to max of bounding box (i.e. is on outer face?)
elif (key[base[coord]] == "%.8e"%box['max'][coord]): # compare to max of bounding box (i.e. is on outer face?) Nmax += 1 # count outer (front) face membership
Nmax += 1 # count outer (front) face membership maxFlag[coord] = True # remember face membership (for linked nodes)
maxFlag[coord] = True # remember face membership (for linked nodes)
if Nmin > 0: # node is on a back face
if Nmin > 0 and Nmin > Nmax: # node is on more back than front faces
# prepare for any non-existing entries in the data structure # prepare for any non-existing entries in the data structure
if key['x'] not in baseNode.keys(): if key['x'] not in baseNode.keys():
baseNode[key['x']] = {} baseNode[key['x']] = {}
@ -110,24 +107,22 @@ def servoLink():
baseNode[key['x']][key['y']][key['z']] = node+1 # remember the base node id baseNode[key['x']][key['y']][key['z']] = node+1 # remember the base node id
elif Nmax > 0 and Nmax >= Nmin: # node is on at least as many front than back faces if Nmax > 0 and Nmax >= Nmin: # node is on at least as many front than back faces
linkNodes.append({'id': node+1,'coord': NodeCoords[node], 'onFaces': Nmax,'faceMember': maxFlag}) if any([maxFlag[i] and active[i] for i in xrange(3)]):
linkNodes.append({'id': node+1,'coord': NodeCoords[node], 'faceMember': [maxFlag[i] and active[i] for i in xrange(3)]})
baseCorner = baseNode["%.8e"%box['min'][0]]["%.8e"%box['min'][1]]["%.8e"%box['min'][2]] # detect ultimate base node
baseCorner = baseNode["%.8e"%box['min'][0]]["%.8e"%box['min'][1]]["%.8e"%box['min'][2]] # detect ultimate base node
for node in linkNodes: # loop over all linked nodes for node in linkNodes: # loop over all linked nodes
linkCoord = [node['coord']] # start list of control node coords with my coords linkCoord = [node['coord']] # start list of control node coords with my coords
for dir in xrange(3): # check for each direction for dir in xrange(3): # check for each direction
if node['faceMember'][dir]: # me on this front face if node['faceMember'][dir]: # me on this front face
linkCoord[0][dir] = box['min'][dir] # project me onto rear face along dir linkCoord[0][dir] = box['min'][dir] # project me onto rear face along dir
linkCoord.append(np.array(box['min'])) # append base corner linkCoord.append(np.array(box['min'])) # append base corner
linkCoord[-1][dir] = box['max'][dir] # stretch it to corresponding control leg of "dir"
linkCoord[-1][dir] = box['max'][dir] # stretch it to corresponding control leg of "dir"
nLinks = len(linkCoord) nLinks = len(linkCoord)
for dof in [1,2,3]: for dof in [1,2,3]:
cmds.append([ cmds.append([
"*new_link *link_class servo", "*new_link *link_class servo",
@ -146,13 +141,6 @@ def servoLink():
"*link_class servo *servo_ret_dof %i %i"%(1+nLinks,dof), "*link_class servo *servo_ret_dof %i %i"%(1+nLinks,dof),
"*link_class servo *servo_ret_coef %i -%i"%(1+nLinks,nLinks-1), "*link_class servo *servo_ret_coef %i -%i"%(1+nLinks,nLinks-1),
]) ])
cmds.append([
"*select_nodes",
["%i"%node['id'] for node in linkNodes],
"#",
])
return cmds return cmds
#-------------------------------------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------
@ -172,30 +160,38 @@ parser.set_defaults(verbose = False)
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
outputLocals = {}
if options.verbose: if options.verbose:
file={'croak':sys.stderr} file={'croak':sys.stderr}
else: else:
file={'croak':sys.stdout} file={'croak':sys.stdout}
try:
from py_mentat import *
except:
file['croak'].write('error: no valid Mentat release found')
sys.exit(-1)
outputLocals = {}
file['croak'].write('\033[1m'+scriptName+'\033[0m\n\n') file['croak'].write('\033[1m'+scriptName+'\033[0m\n\n')
file['croak'].write( 'waiting to connect...\n') file['croak'].write( 'waiting to connect...\n')
py_connect('',options.port) try:
file['croak'].write('connected...\n') py_connect('',options.port)
output([\ output(['*draw_manual'],outputLocals,'Mentat') # prevent redrawing in Mentat, should be much faster. Since py_connect has no return value, try this to determine if failed or not
'*draw_manual', # prevent redrawing in "new" Mentat, should be much faster except:
'*remove_all_servos', file['croak'].write('Could not connect. Set Tools/Python/"Run as Separate Process" & "Initiate"...\n')
sys.exit()
file['croak'].write( 'connected...\n')
output(['*remove_all_servos',
'*sweep_all', '*sweep_all',
'*renumber_nodes', '*renumber_nodes',
'*set_links off', '*set_links off',
],outputLocals,'Mentat') # script depends on consecutive numbering of nodes ],outputLocals,'Mentat') # script depends on consecutive numbering of nodes
cmds = servoLink() cmds = servoLink()
output(cmds,outputLocals,'Mentat') output(cmds,outputLocals,'Mentat')
output([\
'*set_links on',
'*draw',
],outputLocals,'Mentat') # script depends on consecutive numbering of nodes
py_disconnect() py_disconnect()
if options.verbose: if options.verbose:
output(cmds,outputLocals,'Stdout') output(cmds,outputLocals,sys.stdout)