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