def writeSurface(fn,nodes,elems): """Write a tetgen surface model to .node and .smesh files. The provided file name is the .node or the .smesh filename. """ writeNodes(utils.changeExt(fn,'.node'),nodes) writeSmesh(utils.changeExt(fn,'.smesh'),elems)
def writeSurface(fn, coords, elems): """Write a tetgen surface model to .node and .smesh files. The provided file name is the .node or the .smesh filename. """ writeNodes(utils.changeExt(fn, '.node'), coords) writeSmesh(utils.changeExt(fn, '.smesh'), elems)
def read_gambit_neutral(fn): """Read a triangular surface mesh in Gambit neutral format. The .neu file nodes are numbered from 1! Returns a nodes,elems tuple. """ runCommand("%s/external/gambit-neu '%s'" % (GD.cfg['pyformexdir'],fn)) nodesf = changeExt(fn,'.nodes') elemsf = changeExt(fn,'.elems') nodes = fromfile(nodesf,sep=' ',dtype=Float).reshape((-1,3)) elems = fromfile(elemsf,sep=' ',dtype=int32).reshape((-1,3)) return nodes, elems-1
def readSurface(fn): """Read a tetgen surface from a .node/.smesh file pair. The given filename is either the .node or .smesh file. Returns a tuple of (nodes,elems). """ nodes,numbers = readNodes(changeExt(fn,'.node')) print "Read %s nodes" % nodes.shape[0] elems = readSmesh(changeExt(fn,'.smesh')) if numbers[0] > 0: elems = elems-1 return nodes,elems
def read_gambit_neutral(fn): """Read a triangular surface mesh in Gambit neutral format. The .neu file nodes are numbered from 1! Returns a nodes,elems tuple. """ scr = os.path.join(pf.cfg['bindir'],'gambit-neu ') utils.runCommand("%s '%s'" % (scr,fn)) nodesf = utils.changeExt(fn,'.nodes') elemsf = utils.changeExt(fn,'.elems') nodes = fromfile(nodesf,sep=' ',dtype=Float).reshape((-1,3)) elems = fromfile(elemsf,sep=' ',dtype=int32).reshape((-1,3)) return nodes, elems-1
def read_gambit_neutral(fn): """Read a triangular surface mesh in Gambit neutral format. The .neu file nodes are numbered from 1! Returns a nodes,elems tuple. """ scr = os.path.join(pf.cfg['bindir'], 'gambit-neu ') utils.runCommand("%s '%s'" % (scr, fn)) nodesf = utils.changeExt(fn, '.nodes') elemsf = utils.changeExt(fn, '.elems') nodes = fromfile(nodesf, sep=' ', dtype=Float).reshape((-1, 3)) elems = fromfile(elemsf, sep=' ', dtype=int32).reshape((-1, 3)) return nodes, elems - 1
def readSurface(fn): """Read a tetgen surface from a .node/.face file pair. The given filename is either the .node or .face file. Returns a tuple of (nodes,elems). """ nodes,numbers = readNodes(utils.changeExt(fn,'.node')) print("Read %s nodes" % nodes.shape[0]) elems = readFaces(utils.changeExt(fn,'.face')) print("Read %s elems" % elems.shape[0]) #if numbers[0] == 1: # elems -= 1 return nodes,elems
def read_gambit_neutral_hex(fn): """Read an hexahedral mesh in Gambit neutral format. The .neu file nodes are numbered from 1! Returns a nodes,elems tuple. """ scr = os.path.join(pf.cfg['bindir'],'gambit-neu-hex ') pf.message("%s '%s'" % (scr,fn)) utils.runCommand("%s '%s'" % (scr,fn)) nodesf = utils.changeExt(fn,'.nodes') elemsf = utils.changeExt(fn,'.elems') nodes = fromfile(nodesf,sep=' ',dtype=Float).reshape((-1,3)) elems = fromfile(fn_e,sep=' ',dtype=int32).reshape((-1,8)) elems = elems[:,(0,1,3,2,4,5,7,6)] return nodes, elems-1
def read_gambit_neutral_hex(fn): """Read an hexahedral mesh in Gambit neutral format. The .neu file nodes are numbered from 1! Returns a nodes,elems tuple. """ scr = os.path.join(pf.cfg['bindir'], 'gambit-neu-hex ') pf.message("%s '%s'" % (scr, fn)) utils.runCommand("%s '%s'" % (scr, fn)) nodesf = utils.changeExt(fn, '.nodes') elemsf = utils.changeExt(fn, '.elems') nodes = fromfile(nodesf, sep=' ', dtype=Float).reshape((-1, 3)) elems = fromfile(fn_e, sep=' ', dtype=int32).reshape((-1, 8)) elems = elems[:, (0, 1, 3, 2, 4, 5, 7, 6)] return nodes, elems - 1
def readSurface(fn): """Read a tetgen surface from a .node/.face file pair. The given filename is either the .node or .face file. Returns a tuple of (nodes,elems). """ nodeInfo = readNodeFile(utils.changeExt(fn, '.node')) nodes = nodeInfo[0] print("Read %s nodes" % nodes.shape[0]) elemInfo = readFaceFile(utils.changeExt(fn, '.face')) elems = elemInfo[0] print("Read %s elems" % elems.shape[0]) #if numbers[0] == 1: # elems -= 1 return nodes, elems
def stlConvert(stlname,outname=None,options='-d'): """Transform an .stl file to .off or .gts format. If outname is given, it is either '.off' or '.gts' or a filename ending on one of these extensions. If it is only an extension, the stlname will be used with extension changed. If the outname file exists and its mtime is more recent than the stlname, the outname file is considered uptodate and the conversion programwill not be run. The conversion program will be choosen depending on the extension. This uses the external commands 'admesh' or 'stl2gts'. The return value is a tuple of the output file name, the conversion program exit code (0 if succesful) and the stdout of the conversion program (or a 'file is already uptodate' message). """ if not outname: outname = GD.cfg.get('surface/stlread','.off') if outname.startswith('.'): outname = changeExt(stlname,outname) if os.path.exists(outname) and mtime(stlname) < mtime(outname): return outname,0,"File '%s' seems to be up to date" % outname if outname.endswith('.off'): cmd = "admesh %s --write-off '%s' '%s'" % (options,outname,stlname) elif outname.endswith('.gts'): cmd = "stl2gts < '%s' > '%s'" % (stlname,outname) else: return outname,1,"Can not convert file '%s' to '%s'" % (stlname,outname) sta,out = runCommand(cmd) return outname,sta,out
def readTetgen(fn): """Read and draw a tetgen file. This is an experimental function for the geometry import menu. """ res = {} base,ext = os.path.splitext(fn) if ext == '.node': nodes = readNodeFile(fn)[0] res['tetgen'+ext] = nodes elif ext in [ '.ele', '.face' ]: nodes,nodenrs = readNodeFile(utils.changeExt(fn,'.node'))[:2] if ext == '.ele': elems = readEleFile(fn)[0] elif ext == '.face': elems = readFaceFile(fn)[0] if nodenrs.min() == 1 and nodenrs.max()==nodenrs.size: elems = elems-1 M = Mesh(nodes,elems,eltype=elems.eltype) res['tetgen'+ext] = M elif ext == '.smesh': nodes,elems = readSmeshFile(fn) ML = [ Mesh(nodes,elems[e]) for e in elems ] res = dict([('Mesh-%s'%M.nplex(),M) for M in ML]) elif ext == '.poly': nodes,elems = readPolyFile(fn) ML = [ Mesh(nodes,elems[e]) for e in elems ] res = dict([('Mesh-%s'%M.nplex(),M) for M in ML]) return res
def readSmeshFile(fn): """Read a tetgen .smesh file. Returns an array of triangle elements. """ fil = open(fn, 'r') # node section. line = skipComments(fil) npts, ndim, nattr, nbmark = getInts(line, 4) if npts > 0: nodeInfo = readNodesBlock(fil, npts, ndim, nattr, nbmark) else: # corresponding .node file nodeInfo = readNodeFile(utils.changeExt(fn, '.node')) # facet section line = skipComments(fil) nelems, nbmark = getInts(line, 2) facetInfo = readSmeshFacetsBlock(fil, nelems, nbmark) nodenrs = nodeInfo[1] if nodenrs.min() == 1 and nodenrs.max() == nodenrs.size: elems = facetInfo[0] for e in elems: elems[e] -= 1 # We currently do not read the holes and attributes return nodeInfo[0], facetInfo[0]
def readTetgen(fn): """Read and draw a tetgen file. This is an experimental function for the geometry import menu. """ res = {} base, ext = os.path.splitext(fn) if ext == '.node': nodes = readNodeFile(fn)[0] res['tetgen' + ext] = nodes elif ext in ['.ele', '.face']: nodes, nodenrs = readNodeFile(utils.changeExt(fn, '.node'))[:2] if ext == '.ele': elems = readEleFile(fn)[0] elif ext == '.face': elems = readFaceFile(fn)[0] if nodenrs.min() == 1 and nodenrs.max() == nodenrs.size: elems = elems - 1 M = Mesh(nodes, elems, eltype=elems.eltype) res['tetgen' + ext] = M elif ext == '.smesh': nodes, elems = readSmeshFile(fn) ML = [Mesh(nodes, elems[e]) for e in elems] res = dict([('Mesh-%s' % M.nplex(), M) for M in ML]) elif ext == '.poly': nodes, elems = readPolyFile(fn) ML = [Mesh(nodes, elems[e]) for e in elems] res = dict([('Mesh-%s' % M.nplex(), M) for M in ML]) return res
def readSmeshFile(fn): """Read a tetgen .smesh file. Returns an array of triangle elements. """ fil = open(fn,'r') # node section. line = skipComments(fil) npts,ndim,nattr,nbmark = getInts(line,4) if npts > 0: nodeInfo = readNodesBlock(fil,npts,ndim,nattr,nbmark) else: # corresponding .node file nodeInfo = readNodeFile(utils.changeExt(fn,'.node')) # facet section line = skipComments(fil) nelems,nbmark = getInts(line,2) facetInfo = readSmeshFacetsBlock(fil,nelems,nbmark) nodenrs = nodeInfo[1] if nodenrs.min() == 1 and nodenrs.max()==nodenrs.size: elems = facetInfo[0] for e in elems: elems[e] -= 1 # We currently do not read the holes and attributes return nodeInfo[0],facetInfo[0]
def importFlavia(fn=None): """Import a flavia file and select it as the current results. Flavia files are the postprocessing format used by GiD pre- and postprocessor, and can also be written by the FE program calix. There usually are two files named 'BASE.flavia.msh' and 'BASE.flavia.res' which hold the FE mesh and results, respectively. This functions asks the user to select a flavia file (either mesh or results), will then read both the mesh and corrseponding results files, and store the results in a FeResult instance, which will be set as the current results database for the postprocessing menu. """ from plugins.flavia import readFlavia if fn is None: types = [utils.fileDescription('flavia'), utils.fileDescription('all')] fn = askFilename(pf.cfg['workdir'], types) if fn: chdir(fn) if fn.endswith('.msh'): meshfile = fn resfile = utils.changeExt(fn, 'res') else: resfile = fn meshfile = utils.changeExt(fn, 'msh') db = readFlavia(meshfile, resfile) if not isinstance(db, FeResult): warning( "!Something went wrong during the import of the flavia database %s" % fn) return ### ok: export and select the DB name = os.path.splitext(os.path.basename(fn))[0].replace('.flavia', '') export({name: db}) db.printSteps() print(db.R) print(db.datasize) selection.set([name]) selectDB(db)
def importCalculix(fn=None): """Import a CalculiX results file and select it as the current results. CalculiX result files are the .dat files resulting from a run of the ccx program with an .inp file as input. This function will need both files and supposes that the names are the same except for the extension. If no file name is specified, the user is asked to select one (either the .inp or .dat file), will then read both the mesh and corresponding results files, and store the results in a FeResult instance, which will be set as the current results database for the postprocessing menu. """ from plugins import ccxdat from fileread import readInpFile #from plugins.fe import Model if fn is None: types = [ utils.fileDescription('ccx') ] fn = askFilename(pf.cfg['workdir'],types) if fn: chdir(fn) if fn.endswith('.inp'): meshfile = fn resfile = utils.changeExt(fn,'dat') else: resfile = fn meshfile = utils.changeExt(fn,'inp') parts = readInpFile(meshfile) print(type(parts)) print(parts.keys()) meshes = parts.values()[0] print(type(meshes)) #fem = Model(meshes=meshes,fuse=False) DB = ccxdat.createResultDB(meshes) ngp = 8 ccxdat.readResults(resfile,DB,DB.nnodes,DB.nelems,ngp) DB.printSteps() name = 'FeResult-%s' % meshfile[:-4] export({name:DB}) selection.set([name]) selectDB(DB)
def importCalculix(fn=None): """Import a CalculiX results file and select it as the current results. CalculiX result files are the .dat files resulting from a run of the ccx program with an .inp file as input. This function will need both files and supposes that the names are the same except for the extension. If no file name is specified, the user is asked to select one (either the .inp or .dat file), will then read both the mesh and corresponding results files, and store the results in a FeResult instance, which will be set as the current results database for the postprocessing menu. """ from plugins import ccxdat from fileread import readInpFile #from plugins.fe import Model if fn is None: types = [utils.fileDescription('ccx')] fn = askFilename(pf.cfg['workdir'], types) if fn: chdir(fn) if fn.endswith('.inp'): meshfile = fn resfile = utils.changeExt(fn, 'dat') else: resfile = fn meshfile = utils.changeExt(fn, 'inp') parts = readInpFile(meshfile) print(type(parts)) print(parts.keys()) meshes = parts.values()[0] print(type(meshes)) #fem = Model(meshes=meshes,fuse=False) DB = ccxdat.createResultDB(meshes) ngp = 8 ccxdat.readResults(resfile, DB, DB.nnodes, DB.nelems, ngp) DB.printSteps() name = 'FeResult-%s' % meshfile[:-4] export({name: DB}) selection.set([name]) selectDB(DB)
def importFlavia(fn=None): """Import a flavia file and select it as the current results. Flavia files are the postprocessing format used by GiD pre- and postprocessor, and can also be written by the FE program calix. There usually are two files named 'BASE.flavia.msh' and 'BASE.flavia.res' which hold the FE mesh and results, respectively. This functions asks the user to select a flavia file (either mesh or results), will then read both the mesh and corrseponding results files, and store the results in a FeResult instance, which will be set as the current results database for the postprocessing menu. """ from plugins.flavia import readFlavia if fn is None: types = [ utils.fileDescription('flavia'), utils.fileDescription('all') ] fn = askFilename(pf.cfg['workdir'],types) if fn: chdir(fn) if fn.endswith('.msh'): meshfile = fn resfile = utils.changeExt(fn,'res') else: resfile = fn meshfile = utils.changeExt(fn,'msh') db = readFlavia(meshfile,resfile) if not isinstance(db,FeResult): warning("!Something went wrong during the import of the flavia database %s" % fn) return ### ok: export and select the DB name = os.path.splitext(os.path.basename(fn))[0].replace('.flavia','') export({name:db}) db.printSteps() print db.R print db.datasize selection.set([name]) selectDB(db)
def stl_to_off(stlname,offname=None,sanitize=True): """Transform an .stl file to .off format.""" if not offname: offname = changeExt(stlname,'.off') if sanitize: options = '' else: # admesh always wants to perform some actions on the STL. The -c flag # to suppress all actions makes admesh hang. Therefore we include the # action -d (fix normal directions) as the default. options = '-d' runCommand("admesh %s --write-off '%s' '%s'" % (options,offname,stlname)) return offname
def stl_to_femodel(formex,sanitize=True): """Transform an .stl model to FEM model. This is a faster alternative for the Formex feModel() method. It works by writing the model to file, then using admesh to convert the .stl file to .off format, and finally reading back the .off. Returns a tuple of (nodes,elems). If sanitize is False, the result will be such that Formex(nodes[elems]) == formex. By default, admesh sanitizes the STL model and may remove/fix some elements. """ fn = changeExt(os.path.tempnam('.','pyformex-tmp'),'.stl') write_ascii(fn,formex.f) return read_stl(fn,sanitize)
def readSurface(fn,ftype=None): if ftype is None: ftype = os.path.splitext(fn)[1] # deduce from extension ftype = ftype.strip('.').lower() if ftype == 'stl': ofn = changeExt(fn,'.gts') if (not os.path.exists(ofn)) or (mtime(ofn) < mtime(fn)): stl_to_gts(fn) nodes,edges,faces = read_gts(ofn) elems = expandEdges(edges,faces) elif ftype == 'off': nodes,elems = read_off(fn) elif ftype == 'neu': nodes,elems = read_gambit_neutral(fn) elif ftype == 'smesh': nodes,elems = tetgen.readSurface(fn) elif ftype == 'gts': nodes,edges,faces = read_gts(fn) elems = expandEdges(edges,faces) else: print "Cannot read file %s" % fn return nodes,elems
def readPolyFile(fn): """Read a tetgen .poly file. Returns an array of triangle elements. """ fil = open(fn, 'r') # node section. line = skipComments(fil) npts, ndim, nattr, nbmark = getInts(line, 4) if npts > 0: nodeInfo = readNodesBlock(fil, npts, ndim, nattr, nbmark) else: # corresponding .node file nodeInfo = readNodeFile(utils.changeExt(fn, '.node')) # facet section line = skipComments(fil) nelems, nbmark = getInts(line, 2) facetInfo = readFacetsBlock(fil, nelems, nbmark) print("NEXT LINE:") print(line) return nodeInfo[0], facetinfo[0]
def readPolyFile(fn): """Read a tetgen .poly file. Returns an array of triangle elements. """ fil = open(fn,'r') # node section. line = skipComments(fil) npts,ndim,nattr,nbmark = getInts(line,4) if npts > 0: nodeInfo = readNodesBlock(fil,npts,ndim,nattr,nbmark) else: # corresponding .node file nodeInfo = readNodeFile(utils.changeExt(fn,'.node')) # facet section line = skipComments(fil) nelems,nbmark = getInts(line,2) facetInfo = readFacetsBlock(fil,nelems,nbmark) print("NEXT LINE:") print(line) return nodeInfo[0],facetinfo[0]
def off_to_tet(fn): """Transform an .off model to tetgen (.node/.smesh) format.""" GD.message("Transforming .OFF model %s to tetgen .smesh" % fn) nodes,elems = read_off(fn) write_node_smesh(changeExt(fn,'.smesh'),nodes,elems)
def stl_to_gts(stlname,outname=None): """Transform an .stl file to .gts format.""" if not outname: outname = changeExt(stlname,'.gts') runCommand("stl2gts < '%s' > '%s'" % (stlname,outname)) return outname
def createCalixInput(): """Write the Calix input file.""" checkWorkdir() if model is None: warn() return # ask job name from user res = askItems([ _I('jobname',feresult_name.next(),text='Job Name'), _I('header','A Calix example',text='Header Text'), _I('zem','3',text='ZEM control',itemtype='radio',choices=['0','3','6'],), ]) if not res: return jobname = res['jobname'] header = res['header'] nzem = int(res['zem']) if not jobname: print("No Job Name: writing to sys.stdout") jobname = None filnam = jobname+'.dta' print("Writing calix data file %s in %s" % (filnam,os.getcwd())) fil = open(filnam,'w') nnodes = model.coords.shape[0] nelems = model.celems[-1] nplex = [ e.shape[1] for e in model.elems ] if min(nplex) != max(nplex): print([ e.shape for e in model.elems ]) warning("All parts should have same element type") return nodel = nplex[0] # Get materials secprops = PDB.getProp(kind='e',attr=['section']) print(secprops) # need E, nu, thickness, rho mats = array([[sec.young_modulus, sec.poisson_ratio, sec.thickness, sec.density, ] for sec in secprops]) matnr = zeros(nelems,dtype=int32) for i,mat in enumerate(secprops): # proces in same order as above! matnr[mat.set] = i+1 print(matnr) nmats = mats.shape[0] # Header fil.write("""; calix data file generated by %s ; jobname=%s start: %s ;use cmdlog 'calix.log' ;use for messages cmdlog file open 'femodel.tmp' write da 1 yes cmdlog ;yes debug use for cmdlog output femodel elast stress 2 use for cmdlog cmdlog ;----------------------------------------- ; Aantal knopen: %s ; Aantal elementen: %s ; Aantal materialen: %s ; Aantal belastingsgevallen: %s """% (pf.Version,jobname,header,nnodes,nelems,nmats,nsteps)) # Nodal coordinates fil.write(""";----------------------------------------- ; Knopen ;-------- nodes coord %s 1 """ % nnodes) fil.write('\n'.join(["%5i%10.2f%10.2f"%(i,x[0],x[1]) for i,x in zip(arange(nnodes)+1,model.coords)])) fil.write('\n\n') # Boundary conditions fil.write(""";----------------------------------------- ; Verhinderde verplaatsingen ;------------------------- bound bcon plane """) for p in PDB.getProp(kind='n',attr=['bound']): bnd = "%5i" + "%5i"*2 % (p.bound[0],p.bound[1]) if p.set is None: nod = arange(model.nnodes) else: nod = array(p.set) fil.write('\n'.join([ bnd % i for i in nod+1 ])) fil.write('\n') fil.write('\n') fil.write("""print bcon 3 $$$$$$$$$$$$$$$$$$$$$$$ $$ D O F S $$ $$$$$$$$$$$$$$$$$$$$$$$ """) # Materials fil.write(""";----------------------------------------- ; Materialen ;----------- array mat %s 4 """ % len(mats)) print(mats) fil.write('\n'.join([ "%.4e "*4 % tuple(m) for m in mats])) fil.write('\n\n') fil.write("""print mat 3 $$$$$$$$$$$$$$$$$$$$$$$ $$ M A T E R I A L S $$ $$$$$$$$$$$$$$$$$$$$$$$ """) # Elements for igrp,grp in enumerate(model.elems): nelems,nplex = grp.shape fil.write(""";----------------------------------------- ; Elementen ;---------- elements elems-%s matnr-%s %s %s 1 """ % (igrp,igrp,nplex,nelems)) fil.write('\n'.join(["%5i"*(nplex+2) % tuple([i,1]+e.tolist()) for i,e in zip(arange(nelems)+1,grp+1)])) fil.write('\n\n') fil.write("""plane plane-%s coord bcon elems-%s matnr-%s 2 2 """ % (igrp,igrp,igrp)) ######################### # Nodal Loads cloads = [ p for p in PDB.getProp('n',attr=['cload']) ] fil.write("""text 3 1 $$$$$$$$$$$$$$$$$$$$ $$ NODAL LOADS $$ $$$$$$$$$$$$$$$$$$$$ loads f bcon 1 """) if len(cloads) > 0: for p in cloads: loadcase = loadcaseFromTag(p) if p.set is None: nodeset = range(calpyModel.nnodes) else: nodeset = p.set F = [0.0,0.0] for i,v in p.cload: if i in [0,1]: F[i] = v fil.write(''.join(["%5i%5i%10.2f%10.2f\n" % (n+1,loadcase,F[0],F[1]) for n in nodeset])) fil.write('\n') ######################### # Distributed loads eloads = [ p for p in PDB.getProp('e',attr=['eload']) ] if len(eloads) > 0: fil.write("""text 4 1 $$$$$$$$$$$$$$$$$$$$$$$$$$ $$ BOUNDARY ELEMENTS $$ $$$$$$$$$$$$$$$$$$$$$$$$$$ elem loadnr localnodes """) # get the data from database, group by group for igrp in range(len(model.elems)): geloads = [ p for p in eloads if p.group==igrp ] neloads = len(geloads) loaddata = [] fil.write("array randen integer %s 4 0 1\n" % neloads) i = 1 for p in geloads: loadcase = loadcaseFromTag(p) xload = yload = 0. if p.label == 'x': xload = p.value elif p.label == 'y': yload = p.value # Save the load data for later loaddata.append((i,loadcase,xload,yload)) # Because of the way we constructed the database, the set will # contain only one element, but let's loop over it anyway in # case one day we make the storage more effective for e in p.set: fil.write(("%5s"*4+"\n")%(e+1,i,p.edge+1,(p.edge+1)%4+1)) i += 1 fil.write("""print randen tran randen tranden boundary rand-%s coord bcon elems-%s matnr-%s tranden 1 """ % ((igrp,)*3)) fil.write("""text 3 1 $$$$$$$$$$$$$$$$$$$$$$$ $$ BOUNDARY LOADS $$ $$$$$$$$$$$$$$$$$$$$$$$ loadvec boundary rand-%s f 1 """ % igrp) for eload in loaddata: fil.write("%5s%5s%10s%10s\n" % eload) fil.write('\n') ######################### # Print total load vector fil.write(""" print f 3 $$$$$$$$$$$$$$$$$$$$ $$ LOAD VECTOR $$ $$$$$$$$$$$$$$$$$$$$ ; """) # Assemble for igrp in range(len(model.elems)): fil.write("assemble plane-%s mat s 0 0 0 %s\n" % (igrp,nzem)) # Solve and output fil.write(""";------------------------------------------------solve+output flavia mesh '%s.flavia.msh' %s flavia nodes coord """ % (jobname,nplex)) for igrp in range(len(model.elems)): fil.write("flavia elems elems-%s matnr-%s %s\n" % (igrp,igrp,nplex)) fil.write("flavia results '%s.flavia.res'\n" % jobname) fil.write(""" solbnd s f delete s text named 1 "Displacement" "Elastic Analysis" text typed 1 Vector OnNodes text names 1 "Stress" "Elastic Analysis" text types 1 Matrix OnNodes intvar set 1 1 loop 1 displ f bcon displ $1 1 tran displ disp flavia result named typed disp $1 """) for igrp in range(len(model.elems)): fil.write(""" stress plane-%s mat f stresg $1 1 gp2nod plane-%s stresg strese 0 1 nodavg plane-%s elems-%s strese stren nval 1 tran stren stre flavia result names types stre $1 """ % ((igrp,)*4)) fil.write(""" intvar add 1 1 next stop """) # Done: Close data file fil.close() showFile(filnam,mono=True) if ack("Shall I run the Calix analysis?"): # Run the analysis outfile = utils.changeExt(filnam,'res') cmd = "calix %s %s" % (filnam,outfile) utils.runCommand(cmd) showFile(outfile,mono=True) if ack("Shall I read the results for postprocessing?"): from plugins import flavia meshfile = utils.changeExt(filnam,'flavia.msh') resfile = utils.changeExt(filnam,'flavia.res') DB = flavia.readFlavia(meshfile,resfile) postproc_menu.setDB(DB) export({name:DB}) if showInfo("The results have been exported as %s\nYou can now use the postproc menu to display results" % name,actions=['Cancel','OK']) == 'OK': postproc_menu.selection.set(name) postproc_menu.selectDB(DB) postproc_menu.open_dialog()
def export(self, name=None, title=None, description=None, keywords=None, author=None, createdby=False): """Export the WebGL scene. Parameters: - `name`: a string that will be used for the filenames of the HTML, JS and STL files. - `title`: an optional title to be set in the .html file. If not specified, the `name` is used. You can also set the meta tags 'description', 'keywords' and 'author' to be included in the .html file. The first two have defaults if not specified. Returns the name of the exported htmlfile. """ if name is None: name = self.name if title is None: title = '%s WebGL example, created by pyFormex' % name if description is None: description = title if keywords is None: keywords = "pyFormex, WebGL, XTK, HTML, JavaScript" s = """// Script generated by %s window.onload = function() { var r = new X.renderer3D(); r.init(); """ % pf.fullVersion() s += '\n'.join([self.format_object(o) for o in self]) if self.gui: s += self.format_gui() if self._camera: if 'position' in self._camera: s += "r.camera.position = %s;\n" % list(self._camera.position) if 'focus' in self._camera: s += "r.camera.focus = %s;\n" % list(self._camera.focus) if 'up' in self._camera: s += "r.camera.up = %s;\n" % list(self._camera.up) s += """ r.render(); }; """ jsname = utils.changeExt(name, '.js') with open(jsname, 'w') as jsfile: jsfile.write(s) print("Exported WebGL script to %s" % os.path.abspath(jsname)) # TODO: setting DOCTYTPE makes browser initial view not good # s = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> s = """<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="generator" content="%s"> <meta name="description" content="%s"> <meta name="keywords" content="%s"> """ % (pf.fullVersion(), description, keywords) if author: s += '<meta name="author" content="%s">\n' % author s += "<title>%s</title>\n" % title if self.gui: self.scripts.append(pf.cfg['webgl/guiscript']) self.scripts.append(jsname) for scr in self.scripts: s += '<script type="text/javascript" src="%s"></script>\n' % scr s += """ </head> <body>""" if createdby: if type(createdby) is int: width = ' width="%s%%"' % createdby else: width = '' s += """<div id='pyformex' style='position:absolute;top:10px;left:10px;'> <a href='http://pyformex.org' target=_blank><img src='http://pyformex.org/images/pyformex_createdby.png' border=0%s></a> </div>""" % width s += """</body> </html> """ htmlname = utils.changeExt(jsname, '.html') with open(htmlname, 'w') as htmlfile: htmlfile.write(s) print("Exported WebGL model to %s" % os.path.abspath(htmlname)) return htmlname
gp2nod plane stresg strese 0 1 nodavg plane nodes strese stren nval 1 tran stren stre flavia result names types stre $1 intvar add 1 1 next stop """ % (jobname,nplex,nplex,jobname)) # Done: Close data file fil.close() showFile(filnam,mono=True) if ack("Shall I run the Calix analysis?"): # Run the analysis outfile = utils.changeExt(filnam,'res') cmd = "calix %s %s" % (filnam,outfile) utils.runCommand(cmd) showFile(outfile,mono=True) ############################################################################## def runCalpyAnalysis(jobname=None,verbose=False,flavia=False): """Create data for Calpy analysis module and run Calpy on the data. While we could write an analysis file in the Calpy format and then run the Calpy program on it (like we did with Abaqus), we can (and do) take another road here: Calpy has a Python/numpy interface, allowing us to directly present the numerical data in arrays to the analysis
tran stren stre flavia result names types stre $1 """ % ((igrp,)*4)) fil.write(""" intvar add 1 1 next stop """) # Done: Close data file fil.close() showFile(filnam,mono=True) if ack("Shall I run the Calix analysis?"): # Run the analysis outfile = utils.changeExt(filnam,'res') cmd = "calix %s %s" % (filnam,outfile) utils.runCommand(cmd) showFile(outfile,mono=True) if ack("Shall I read the results for postprocessing?"): from plugins import flavia meshfile = utils.changeExt(filnam,'flavia.msh') resfile = utils.changeExt(filnam,'flavia.res') DB = flavia.readFlavia(meshfile,resfile) postproc_menu.setDB(DB) export({name:DB}) if showInfo("The results have been exported as %s\nYou can now use the postproc menu to display results" % name,actions=['Cancel','OK']) == 'OK': postproc_menu.selection.set(name) postproc_menu.selectDB(DB) postproc_menu.open_results_dialog()
def export(self,name=None,title=None,description=None,keywords=None,author=None,createdby=False): """Export the WebGL scene. Parameters: - `name`: a string that will be used for the filenames of the HTML, JS and STL files. - `title`: an optional title to be set in the .html file. If not specified, the `name` is used. You can also set the meta tags 'description', 'keywords' and 'author' to be included in the .html file. The first two have defaults if not specified. Returns the name of the exported htmlfile. """ if name is None: name = self.name if title is None: title = '%s WebGL example, created by pyFormex' % name if description is None: description = title if keywords is None: keywords = "pyFormex, WebGL, XTK, HTML, JavaScript" s = """// Script generated by %s window.onload = function() { var r = new X.renderer3D(); r.init(); """ % pf.fullVersion() s += '\n'.join([self.format_object(o) for o in self ]) if self.gui: s += self.format_gui() if self._camera: if 'position' in self._camera: s += "r.camera.position = %s;\n" % list(self._camera.position) if 'focus' in self._camera: s += "r.camera.focus = %s;\n" % list(self._camera.focus) if 'up' in self._camera: s += "r.camera.up = %s;\n" % list(self._camera.up) s += """ r.render(); }; """ jsname = utils.changeExt(name,'.js') with open(jsname,'w') as jsfile: jsfile.write(s) print("Exported WebGL script to %s" % os.path.abspath(jsname)) # TODO: setting DOCTYTPE makes browser initial view not good # s = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> s = """<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="generator" content="%s"> <meta name="description" content="%s"> <meta name="keywords" content="%s"> """ % (pf.fullVersion(),description,keywords) if author: s += '<meta name="author" content="%s">\n' % author s += "<title>%s</title>\n" % title if self.gui: self.scripts.append(pf.cfg['webgl/guiscript']) self.scripts.append(jsname) for scr in self.scripts: s += '<script type="text/javascript" src="%s"></script>\n' % scr s += """ </head> <body>""" if createdby: if type(createdby) is int: width = ' width="%s%%"' % createdby else: width = '' s += """<div id='pyformex' style='position:absolute;top:10px;left:10px;'> <a href='http://pyformex.org' target=_blank><img src='http://pyformex.org/images/pyformex_createdby.png' border=0%s></a> </div>""" % width s += """</body> </html> """ htmlname = utils.changeExt(jsname,'.html') with open(htmlname,'w') as htmlfile: htmlfile.write(s) print("Exported WebGL model to %s" % os.path.abspath(htmlname)) return htmlname