def main(): import numpy as np import os import pymef90 options = parse() if os.path.exists(options.outputfile): if options.force: os.remove(options.outputfile) else: if pymef90.confirm( "ExodusII file {0} already exists. Overwrite?".format( options.outputfile)): os.remove(options.outputfile) else: print('\n\t{0} was NOT generated.\n'.format( options.outputfile)) return -1 exoin = exo.exodus(options.inputfile, mode='r') exoout = exoin.copy(options.outputfile) exoout.close() exoout = exo.exodus(options.outputfile, mode='a', array_type='numpy') ### Adding a QA record, needed until visit fixes its exodus reader import datetime import os.path import sys QA_rec_len = 32 QA = [ os.path.basename(sys.argv[0]), os.path.basename(__file__), datetime.date.today().strftime('%Y%m%d'), datetime.datetime.now().strftime("%H:%M:%S") ] exoout.put_qa_records([ [q[0:31] for q in QA], ]) exoformat(exoout, options.plasticity) dim = exoout.num_dimensions() step = 0 for t in np.linspace(options.time_min, options.time_max, options.time_numstep): print("writing step {0}, t = {1:0.4f}".format(step + 1, t)) exoout.put_time(step + 1, t) U = surfingBC(exoout, t, options.initialpos, options.cs, options.vs, options.E, options.nu, options.ampl) X, Y, Z = exoout.get_coords() exoout.put_node_variable_values("Displacement_X", step + 1, U[0, :]) exoout.put_node_variable_values("Displacement_Y", step + 1, U[1, :]) if dim == 3: exoout.put_node_variable_values("Displacement_Z", step + 1, U[2, :]) step += 1 exoout.close()
def main(): import numpy as np import os import pymef90 options = parse() if os.path.exists(options.outputfile): if options.force: os.remove(options.outputfile) else: if pymef90.confirm( "ExodusII file {0} already exists. Overwrite?".format( options.outputfile)): os.remove(options.outputfile) else: print('\n\t{0} was NOT generated.\n'.format( options.outputfile)) return -1 exoin = exo.exodus(options.inputfile, mode='r') exoout = exoin.copy(options.outputfile) exoout.close() exoout = exo.exodus(options.outputfile, mode='a', array_type='numpy') ### Adding a QA record, needed until visit fixes its exodus reader import datetime import os.path import sys QA_rec_len = 32 QA = [ os.path.basename(sys.argv[0]), os.path.basename(__file__), datetime.date.today().strftime('%Y%m%d'), datetime.datetime.now().strftime("%H:%M:%S") ] exoout.put_qa_records([ [q[0:31] for q in QA], ]) exoformat(exoout) if not exoout.num_dimensions() == 3: print("This program only makes sense in 3D") return (-1) T = np.linspace(options.time_min, options.time_max, options.time_numstep) for step in range(options.time_numstep): t = T[step] print "writing step", step + 1, t exoout.put_time(step + 1, t) U = displacementBC(exoout, t, options) exoout.put_node_variable_values("Displacement_X", step + 1, U[0, :]) exoout.put_node_variable_values("Displacement_Y", step + 1, U[1, :]) exoout.put_node_variable_values("Displacement_Z", step + 1, U[1, :]) exoout.close() return (0)
def main(): import numpy as np import os import pymef90 import sys if sys.version_info.major == 3: import exodus3 as exo else: import exodus2 as exo options = parse() exoin = exo.exodus(options.inputfile, mode='r', array_type='numpy') if options.step == None: steps = range(exoin.num_times()) times = exoin.get_times() else: steps = (options.step - 1, ) times = (exoin.get_times()[options.step - 1], ) for s, t in zip(steps, times): thetaMax = max(exoin.get_node_variable_values('Temperature', s)) * options.theta0 print('step {0} time (real) {1:.4e} max temp (real): {2:.4e}'.format( s + 1, t, thetaMax)) exoin.close()
def transfer_database(input_file_name, output_file_name): old_database = exodus.exodus(input_file_name, 'r') block_ids = old_database.get_elem_blk_ids() elem_var_names = {} elem_var_values = {} for block_id in block_ids: attr_names = old_database.get_element_attribute_names(block_id) for i in range(len(attr_names)): if attr_names[i] == '': attr_names[i] = "attribute_" + str(i + 1) # For the case of sphere meshes, there are two unnamed attributes which are the sph_radius and the volume. # In this case, add radius as a variable. add_radius = False if len(attr_names) == 2: if attr_names[0] == 'attribute_1' and attr_names[ 1] == 'attribute_2': add_radius = True num_attr = len(attr_names) attr = old_database.get_elem_attr(block_id) elem_var_names[block_id] = attr_names elem_var_values[block_id] = [] for i in range(num_attr): elem_var_values[block_id].append([]) if add_radius == True: elem_var_names[block_id].append('radius') elem_var_values[block_id].append([]) attr_index = 0 for i_elem in range(old_database.num_elems_in_blk(block_id)): for i_attr in range(num_attr): elem_var_values[block_id][i_attr].append(attr[attr_index]) attr_index += 1 if add_radius == True: volume = elem_var_values[block_id][1][-1] radius = math.pow((3.0 * volume) / (4.0 * math.pi), 1.0 / 3.0) elem_var_values[block_id][-1].append(radius) new_database = old_database.copy(output_file_name) old_database.close() elem_names_and_blocks = {} for block_id in elem_var_names.keys(): for name in elem_var_names[block_id]: if name not in elem_names_and_blocks: elem_names_and_blocks[name] = [] elem_names_and_blocks[name].append(block_id) g_var_names = [] n_var_names = [] e_var_names = [] for var_name in elem_names_and_blocks.keys(): e_var_names.append((var_name, elem_names_and_blocks[var_name])) new_database.put_time(1, 0.0) exodus.add_variables(new_database, g_var_names, n_var_names, e_var_names) for block_id in block_ids: for i_var in range(len(elem_var_names[block_id])): new_database.put_element_variable_values( block_id, elem_var_names[block_id][i_var], 1, elem_var_values[block_id][i_var]) new_database.close()
def write_exodus(self, filename, face_block_mode="one block"): """Write the 3D mesh to ExodusII using arbitrary polyhedra spec""" # put cells in with blocks, which renumbers the cells, so we have to track sidesets. # Therefore we keep a map of old cell to new cell ordering # # also, though not required by the spec, paraview and visit # seem to crash if num_face_blocks != num_elem_blocks. So # make face blocks here too, which requires renumbering the faces. # -- first pass, form all elem blocks and make the map from old-to-new new_to_old_elems = [] elem_blks = [] for i_m,m_id in enumerate(self.material_ids_list): # split out elems of this material, save new_to_old map elems_tuple = [(i,c) for (i,c) in enumerate(self.elem_to_face_conn) if self.material_ids[i] == m_id] new_to_old_elems.extend([i for (i,c) in elems_tuple]) elems = [c for (i,c) in elems_tuple] elem_blks.append(elems) old_to_new_elems = sorted([(old,i) for (i,old) in enumerate(new_to_old_elems)], key=lambda a: a[0]) # -- deal with faces, form all face blocks and make the map from old-to-new face_blks = [] if face_block_mode == "one block": # no reordering of faces needed face_blks.append(self.face_to_node_conn) elif face_block_mode == "n blocks, not duplicated": used_faces = np.zeros((len(self.face_to_node_conn),),'bool') new_to_old_faces = [] for i_m,m_id in enumerate(self.material_ids_list): # split out faces of this material, save new_to_old map def used(f): result = used_faces[f] used_faces[f] = True return result elem_blk = elem_blks[i_m] faces_tuple = [(f,self.face_to_node_conn[f]) for c in elem_blk for (j,f) in enumerate(c) if not used(f)] new_to_old_faces.extend([j for (j,f) in faces_tuple]) faces = [f for (j,f) in faces_tuple] face_blks.append(faces) # get the renumbering in the elems old_to_new_faces = sorted([(old,j) for (j,old) in enumerate(new_to_old_faces)], key=lambda a: a[0]) elem_blks = [[[old_to_new_faces[f][1] for f in c] for c in elem_blk] for elem_blk in elem_blks] elif face_block_mode == "n blocks, duplicated": elem_blks_new = [] offset = 0 for i_m, m_id in enumerate(self.material_ids_list): used_faces = np.zeros((len(self.face_to_node_conn),),'bool') def used(f): result = used_faces[f] used_faces[f] = True return result elem_blk = elem_blks[i_m] tuple_old_f = [(f,self.face_to_node_conn[f]) for c in elem_blk for f in c if not used(f)] tuple_new_old_f = [(new,old,f) for (new,(old,f)) in enumerate(tuple_old_f)] old_to_new_blk = np.zeros((len(self.face_to_node_conn),),'i')-1 for new,old,f in tuple_new_old_f: old_to_new_blk[old] = new + offset elem_blk_new = [[old_to_new_blk[f] for f in c] for c in elem_blk] #offset = offset + len(ftuple_new) elem_blks_new.append(elem_blk_new) face_blks.append([f for i,j,f in tuple_new_old_f]) elem_blks = elem_blks_new elif face_block_mode == "one block, repeated": # no reordering of faces needed, just repeat for eblock in elem_blks: face_blks.append(self.face_to_node_conn) else: raise RuntimeError("Invalid face_block_mode: '%s', valid='one block', 'n blocks, duplicated', 'n blocks, not duplicated'"%face_block_mode) # open the mesh file num_elems = sum(len(elem_blk) for elem_blk in elem_blks) num_faces = sum(len(face_blk) for face_blk in face_blks) filename_base = os.path.split(filename)[-1] ep = exodus.ex_init_params(title=filename_base.encode('ascii'), num_dim=3, num_nodes=self.num_nodes(), num_face=num_faces, num_face_blk=len(face_blks), num_elem=num_elems, num_elem_blk=len(elem_blks), num_side_sets=len(self.side_sets)) e = exodus.exodus(filename, mode='w', array_type='numpy', init_params=ep) # put the coordinates e.put_coord_names(['coordX', 'coordY', 'coordZ']) e.put_coords(self.coords[:,0], self.coords[:,1], self.coords[:,2]) # put the face blocks for i_blk, face_blk in enumerate(face_blks): face_raveled = [n for f in face_blk for n in f] e.put_polyhedra_face_blk(i_blk+1, len(face_blk), len(face_raveled), 0) e.put_node_count_per_face(i_blk+1, np.array([len(f) for f in face_blk])) e.put_face_node_conn(i_blk+1, np.array(face_raveled)+1) # put the elem blocks assert len(elem_blks) == len(self.material_ids_list) for i_blk, (m_id, elem_blk) in enumerate(zip(self.material_ids_list, elem_blks)): elems_raveled = [f for c in elem_blk for f in c] e.put_polyhedra_elem_blk(m_id, len(elem_blk), len(elems_raveled), 0) e.put_elem_blk_name(m_id, 'MATERIAL_ID_%d'%m_id) e.put_face_count_per_polyhedra(m_id, np.array([len(c) for c in elem_blk])) e.put_elem_face_conn(m_id, np.array(elems_raveled)+1) # add sidesets e.put_side_set_names([ss.name for ss in self.side_sets]) for ss in self.side_sets: for elem in ss.elem_list: assert old_to_new_elems[elem][0] == elem new_elem_list = [old_to_new_elems[elem][1] for elem in ss.elem_list] e.put_side_set_params(ss.setid, len(ss.elem_list), 0) e.put_side_set(ss.setid, np.array(new_elem_list)+1, np.array(ss.side_list)+1) # finish and close e.close()
def main(): import sys if sys.version_info.major == 3: import exodus3 as exo else: import exodus2 as exo import numpy as np options = parse() print options exoin = exo.exodus(options.inputFile, mode='r') numNodes = exoin.num_nodes() numElems = exoin.num_elems() numBlocks = exoin.num_blks() numNodeSets = exoin.num_node_sets() exoout = exo.exodus(options.outputFile, mode='w', title=exoin.title(), numDims=2, numNodes=numNodes, numElems=numElems, numBlocks=numBlocks, numNodeSets=numNodeSets, numSideSets=0) exoout.put_coord_names(exoin.get_coord_names()[0:2]) coord = exoin.get_coords() exoout.put_coords(coord[0], coord[1], coord[2]) # cell sets blkids = exoin.get_elem_blk_ids() for id in blkids: blkName = exoin.get_elem_blk_name(id) (elemType, numElemInBlock, numNodesPerElem, numAttr) = exoin.elem_blk_info(id) exoout.put_elem_blk_info(id, elemType, numElemInBlock, numNodesPerElem, 0) #ignoring attributes exoout.put_elem_connectivity(id, exoin.get_elem_connectivity(id)[0]) # node sets setids = exoin.get_node_set_ids() for id in setids: # e.get_node_set_params() -> get number of nodes and distribution factors numNodes, numDistFactors = exoin.get_node_set_params(id) exoout.put_node_set_params(id, numNodes, numDistFactors) exoout.put_node_set_name(id, exoin.get_node_set_name(id)) exoout.put_node_set(id, exoin.get_node_set_nodes(id)) exoin.close() ### Adding a QA record, needed until visit fixes its exodus reader import datetime import os.path import sys QA_rec_len = 32 QA = [ os.path.basename(sys.argv[0]), os.path.basename(__file__), datetime.date.today().strftime('%Y%m%d'), datetime.datetime.now().strftime("%H:%M:%S") ] exoout.put_qa_records([ [q[0:31] for q in QA], ]) exoout.close()
if len(sys.argv) < 3: print("\nUsage: create_data_file.py <input.g> <output.e>\n") sys.exit(1) input_file_name = sys.argv[1] output_file_name = sys.argv[2] print("\n-- create_data_file.py --\n") print("Genesis input file: {}".format(input_file_name)) print("Exodus output file: {}".format(output_file_name)) if os.path.exists(output_file_name): os.remove(output_file_name) old_database = exodus.exodus(input_file_name, 'r') x, y, z = old_database.get_coords() new_database = old_database.copy(output_file_name) old_database.close() field_name = "Fluid_Concentration" num_nodes = len(x) field_values = [0.0]*num_nodes g_var_names = [] n_var_names = [field_name] e_var_names = [] exodus.add_variables(new_database, g_var_names, n_var_names, e_var_names) num_steps = 11 final_time = 0.001
#!/usr/bin/env python import sys if sys.version_info.major == 3: import exodus3 as exo else: import exodus2 as exo import os.path import numpy as np f = sys.argv[-1] if not os.path.isfile(f) or not (len(sys.argv) == 2): print "usage: {0} <filename>".format(sys.argv[0]) exit e = exo.exodus(f,"r") dim = e.num_dimensions() nVertices = e.num_nodes() nCells = e.num_elems() nCSets = e.num_blks() nVSets = e.num_node_sets() print "number of dimensions: {0}".format(dim) print "number of vertices: {0}".format(nVertices) print "number of cells: {0}".format(nCells) print "number of cell sets: {0}".format(nCSets) print "number of vertex sets: {0}".format(nVSets) #listedVertices = np.empty([nVertices,],dtype=bool) listedVertices = [False,]*nVertices maxV = 0 minV = 2*nVertices
def EXODUSwrite(coords,vertexSets,cellSets,numDim,exoFile): #''' # Writes an exodus file #''' cell1D = ("BAR","BAR2","BEAM2","BAR3","BEAM3") cell2D = ("TRI","TRI3","TRIANGLE","TRISHELL","TRISHELL3","TRI6","TRISHELL6","QUAD","QUAD4","SHELL","SHELL4","QUAD9","SHELL9") cell3D = ("TETRA","TETRA4","TETRA10","HEX","HEX8","HEX27") # Reorder blocks with cells of coDimension 0 first if numDim == 2: cellCoDim0 = cell2D cellCoDim1 = cell1D cellCoDim2 = () else: cellCoDim0 = cell3D cellCoDim1 = cell2D cellCoDim2 = cell1D #in 3D, cellCoDim2 cells need to be converted into a vertex set convertedSets = [] for setID in cellSets.keys(): if cellSets[setID]['elemType'].upper() in cellCoDim2: print("Converting set {0} of codimension 2 into a vertex set".format(setID)) vs = [] for v in cellSets[setID]['connect']: if v not in vs: vs.append(v) if setID in vertexSets.keys(): print("Codimension 2 cell set {0} renamed vertex set {1} so as not to clash with existing vertex set".format(setID,max(vertexSets.keys())+1)) setID = max(vertexSets.keys())+1 vertexSets[setID] = {} vertexSets[setID]['vertex'] = vs vertexSets[setID]['name'] = cellSets[setID]['name'] convertedSets.append(setID) for setID in convertedSets: cellSets.pop(setID,'None') # reorder cells so that sets of codimension 0 are written first in the mesh blocksOrder = [] for setID in cellSets.keys(): if cellSets[setID]['elemType'].upper() in cellCoDim0: blocksOrder.append(setID) for setID in cellSets.keys(): if cellSets[setID]['elemType'].upper() in cellCoDim1: blocksOrder.append(setID) #Writting exodusII file numElems = 0 for k in cellSets.keys(): #finding number of elements numElems += len(cellSets[k]['connect'])//EXOCellSize(cellSets[k]['elemType']) numNodes = len(coords[:,0]) ex_pars = exo.ex_init_params(num_dim=numDim, num_nodes=numNodes, num_elem=numElems, num_elem_blk=len(cellSets), num_node_sets=len(vertexSets),num_side_sets=0) e=exo.exodus(exoFile,array_type='numpy',mode='w',init_params=ex_pars) #coordinates if numDim == 3: e.put_coord_names(["x","y","z"]) else: e.put_coord_names(["x","y"]) e.put_coords(coords[:,0],coords[:,1],coords[:,2]) for setID in blocksOrder: elemType = cellSets[setID]['elemType'] ###---setID, elemType, num elems, num nodes per elem, num attributes per elem e.put_elem_blk_info(setID,elemType,len(cellSets[setID]['connect'])//EXOCellSize(elemType),EXOCellSize(elemType),0) ###---setID, connectivity table e.put_elem_connectivity(setID,cellSets[setID]['connect']) if not cellSets[setID]['name'] == '': e.put_elem_blk_name(setID,cellSets[setID]['name']) for setID in vertexSets.keys(): ###---setID, num nodes, num distribution factors in a node set e.put_node_set_params(setID,len(vertexSets[setID]['vertex']),0) ###---setID, nodes e.put_node_set(setID,vertexSets[setID]['vertex']) if not vertexSets[setID]['name'] == '': e.put_node_set_name(setID,vertexSets[setID]['name']) ### Adding a QA record, needed until visit fixes its exodus reader import datetime import os.path import sys QA_rec_len = 32 QA = [os.path.basename(sys.argv[0]),os.path.basename(__file__),datetime.date.today().strftime('%Y%m%d'),datetime.datetime.now().strftime("%H:%M:%S")] e.put_qa_records([[ q[0:31] for q in QA],]) e.close()
import sys # The following points to the location of exodus.py path_to_exodus_py = 'trilinos_install_path/lib' sys.path.append(path_to_exodus_py) if sys.version_info >= (3, 0): import exodus3 as exodus else: import exodus2 as exodus if __name__ == "__main__": inFileName = "WaveInCube.e" inFile = exodus.exodus(inFileName, mode='r') outFileLabel = inFileName.split('.')[0] # Print database parameters from inFile print(" ") print("Database version: " + str(round(inFile.version.value, 2))) print("Database title: " + inFile.title()) print("Database dimensions: " + str(inFile.num_dimensions())) print("Number of nodes: " + str(inFile.num_nodes())) print("Number of elements: " + str(inFile.num_elems())) print("Number of element blocks: " + str(inFile.num_blks())) print("Number of node sets: " + str(inFile.num_node_sets())) print("Number of side sets: " + str(inFile.num_side_sets())) print(" ")
else: import exodus2 as exo import os.path import numpy as np f = sys.argv[-1] if not os.path.isfile(f) or not (len(sys.argv) == 2): print "usage: {0} <filename>".format(sys.argv[0]) exit else: fout = f.split(".gen")[0] + "_fixed.gen" if os.path.exists(fout): print "{0} exists. Delete and run again".format(fout) exit e = exo.exodus(f, "r") dim = e.num_dimensions() nVertices = e.num_nodes() nCells = e.num_elems() nCSets = e.num_blks() nVSets = e.num_node_sets() title = "{0} fixed by {1}".format(e.title(), sys.argv[0]) eout = exo.exodus(fout, 'w', numDims=dim, title=title, numNodes=nVertices - 4, numElems=nCells, numBlocks=nCSets,
def exo2exo(fin, fout): import sys import warnings warnings.filterwarnings( 'ignore', '.*buffer.*', ) cell1D = ("BAR", "BAR2", "BEAM2", "BAR3", "BEAM3") cell2D = ("TRI", "TRI3", "TRIANGLE", "TRISHELL", "TRISHELL3", "TRI6", "TRISHELL6", "QUAD", "QUAD4", "SHELL", "SHELL4", "QUAD9", "SHELL9") cell3D = ("TETRA", "TETRA4", "TETRA10", "HEX", "HEX8", "HEX27") print "Opening {0}".format(fin) e = exo.exodus(fin, "r") dim = e.num_dimensions() nVertices = e.num_nodes() nCells = e.num_elems() nCSets = e.num_blks() nVSets = e.num_node_sets() print "\tnumber of dimensions: {0}".format(dim) print "\tnumber of vertices: {0}".format(nVertices) print "\tnumber of cells: {0}".format(nCells) print "\tnumber of cell sets: {0}".format(nCSets) print "\tnumber of vertex sets: {0}".format(nVSets) ### Reorder cell sets ### List cells of coDIm0 first then cells of coDim 1 ### print "Reordering cell sets by increasing co-dimension" cellsType = [] for set in range(nCSets): setID = e.get_elem_blk_ids()[set] cellType, numCells, numVertexPerCell, numAttr = e.elem_blk_info(setID) cellsType.append(cellType) blocksOrder = [] if dim == 2: cellCoDim0 = cell2D cellCoDim1 = cell1D else: cellCoDim0 = cell3D cellCoDim1 = cell2D for i in range(len(cellsType)): if cellsType[i].upper() in cellCoDim0: blocksOrder.append(i) for i in range(len(cellsType)): if cellsType[i].upper() in cellCoDim1: blocksOrder.append(i) ### Find hanging nodes ### ### 1. find largest vertex index in all connectivity tables print "Removing hanging nodes" minV = 100000000 maxV = 0 for set in range(nCSets): setID = e.get_elem_blk_ids()[set] connect = e.get_elem_connectivity(setID) for v in connect[0]: maxV = max(maxV, v) minV = min(minV, v) print "\tVertex range: {0}/{1}".format(minV, maxV) listedVertices = [ False, ] * maxV for set in range(nCSets): setID = e.get_elem_blk_ids()[set] connect = e.get_elem_connectivity(setID) for v in connect[0]: listedVertices[v - 1] = True numMissing = 0 vertexReordering = np.array(range(maxV), dtype=int) for v in range(len(listedVertices)): if not listedVertices[v]: print "\tvertex {0} is missing.".format(v) vertexReordering[v:] = vertexReordering[v:] - 1 vertexReordering[v] = -1 numMissing += 1 if numMissing > 0: print( "{0} vertices are not referenced in the input file. Was the mesh renumbered?" .format(numMissing)) ### Create fixed file title = "{0} fixed by {1}".format(e.title(), sys.argv[0])[:exo.MAX_LINE_LENGTH] nVertices -= numMissing eout = exo.exodus(fout, 'w', numDims=dim, title=title, numNodes=nVertices, numElems=nCells, numBlocks=nCSets, numNodeSets=nVSets, numSideSets=0) ### Write coordinates ### X, Y, Z = e.get_coords() eout.put_coord_names(["x", "y", "z"][0:dim]) fixedX = np.empty(nVertices, dtype=exo.c_double) fixedY = np.empty(nVertices, dtype=exo.c_double) fixedZ = np.empty(nVertices, dtype=exo.c_double) for i in range(nVertices): if listedVertices[i]: fixedX[i] = X[vertexReordering[i]] fixedY[i] = Y[vertexReordering[i]] fixedZ[i] = Z[vertexReordering[i]] eout.put_coords(fixedX, fixedY, fixedZ) ### Write cell sets ### maxID = 0 usedID = [ 0, ] for set in blocksOrder: setID = e.get_elem_blk_ids()[set] setName = e.get_elem_blk_name(setID) try: setFixedID = int(setName) if setFixedID in usedID: setFixedID = max(usedID) + 1 usedID.append(setFixedID) except ValueError: setFixedID = max(usedID) + 1 usedID.append(setFixedID) cellType, numCells, numVertexPerCell, numAttr = e.elem_blk_info(setID) print( 'Assigning ID {0:4d} to cell set "{1}". \tmef90/vDef name will be cs{0:04}' .format(setFixedID, setName)) print "\tNumber of cells: {0}".format(numCells) print "\tCell type: {0}".format(cellType) print "\tNumber of vertex per cell: {0}".format(numVertexPerCell) eout.put_elem_blk_info(setFixedID, cellType, numCells, numVertexPerCell, 1) eout.put_elem_blk_name(setFixedID, setName) connect = np.array(e.get_elem_connectivity(setID)[0], dtype=exo.c_int) for i in range(len(connect)): connect[i] = 1 + vertexReordering[connect[i] - 1] eout.put_elem_connectivity(setFixedID, connect) ### Write node sets ### setIDs = e.get_node_set_ids() usedID = [ 0, ] for set in setIDs: setName = e.get_node_set_name(set) try: setFixedID = int(setName) if setFixedID in usedID: setFixedID = max(usedID) + 1 usedID.append(setFixedID) except ValueError: setFixedID = max(usedID) + 1 usedID.append(setFixedID) print( 'Assigning ID {0:4d} to vertex set "{1}". \tmef90/vDef name will be vs{0:04}' .format(setFixedID, setName)) num_ns_nodes, num_ns_dist_facts = e.get_node_set_params(set) if num_ns_nodes == 0: print("\tset is empty and will NOT be written to output file") else: print("\tnumber of nodes: {1}".format(set, num_ns_nodes, setName)) eout.put_node_set_params(setFixedID, num_ns_nodes, num_ns_dist_facts) eout.put_node_set(setFixedID, e.get_node_set_nodes(set)) eout.put_node_set_name(setFixedID, setName) ### Adding a QA record, needed until visit fixes its exodus reader import datetime import os.path import sys QA_rec_len = 32 QA = [ os.path.basename(sys.argv[0]), os.path.basename(__file__), datetime.date.today().strftime('%Y%m%d'), datetime.datetime.now().strftime("%H:%M:%S") ] eout.put_qa_records([ [q[0:31] for q in QA], ]) eout.close() e.close()
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Initialize level set function") parser.add_argument("input_mesh", metavar="Input_Mesh", type=str, help="mesh") parser.add_argument("output_mesh", metavar="Output_Mesh", type=str, help="output mesh") args = parser.parse_args() try: input_mesh = exodus.exodus(args.input_mesh) file_to_rem = pathlib.Path(args.output_mesh) file_to_rem.unlink(True) output_mesh = input_mesh.copy(args.output_mesh) except Exception as e: print(e) print("Could not open exodus file", file=sys.stderr) sys.exit(-1) x, y, z = input_mesh.get_coords() output_mesh.set_node_variable_number(2) output_mesh.put_time(1, 0) var = "Y0" output_mesh.put_node_variable_name(var, 1)
def write_exodus_file(textFileName, X, Y, Z, vol, blocks, nodeSets): # Write the Exodus II file exodusFileName = textFileName[:-4] + ".g" exodusTitle = "Text to Genesis translation of " + textFileName[:-4] # Remove old version of the exodus file, if it exists if os.path.exists(exodusFileName): os.remove(exodusFileName) # Open the output Exodus file exodusNumberOfDimensions = 3 exodusNumberOfNodes = len(X) exodusNumberOfElements = len(X) exodusNumberOfBlocks = len(blocks) exodusNumberOfNodeSets = len(nodeSets) exodusNumberOfSideSets = 0 exodusFile = exodus.exodus(exodusFileName, 'w', 'ctype', exodusTitle, exodusNumberOfDimensions, exodusNumberOfNodes, exodusNumberOfElements, exodusNumberOfBlocks, exodusNumberOfNodeSets, exodusNumberOfSideSets) # Write the nodal coordinates coordNames = ["X", "Y", "Z"] exodusFile.put_coord_names(coordNames) exodusFile.put_coords(X, Y, Z) exodusBlockIds = [] for key in blocks.keys(): exodusBlockIds.append(key) # Write the element block information exodusElementTypes = ["SPHERE"] * exodusNumberOfBlocks exodusNumberOfElementsPerBlock = [] for blockId in exodusBlockIds: exodusNumberOfElementsPerBlock.append(len(blocks[blockId])) exodusNumberOfNodesPerElement = [1] * exodusNumberOfBlocks exodusNumberOfAttributes = [2] * exodusNumberOfBlocks exodusDefineMaps = 0 exodusFile.put_concat_elem_blk(exodusBlockIds, exodusElementTypes, exodusNumberOfElementsPerBlock, exodusNumberOfNodesPerElement, exodusNumberOfAttributes, exodusDefineMaps) # Create attribute arrays for the volume and radius # We follow a long-standing convention for legacy codes and record two attributes # 1) The so-called SPH radius, which is NOT the actual radius of the sphere and is NOT used by Peridigm # 2) The element volume for blockId in exodusBlockIds: numberOfPoints = len(blocks[blockId]) exodusElementConnectivity = blocks[blockId] numberOfAttributesPerElement = 2 exodusElementAttributes = [ 0.0 ] * numberOfAttributesPerElement * numberOfPoints index = 0 for nodeId in blocks[blockId]: volume = vol[nodeId - 1] sphRadius = volume**(1. / 3.) exodusElementAttributes[2 * index] = sphRadius exodusElementAttributes[2 * index + 1] = volume index += 1 # Write connectivity array exodusFile.put_elem_connectivity(blockId, exodusElementConnectivity) # Write element attributes exodusFile.put_elem_attr(blockId, exodusElementAttributes) # Write the node sets # node_set_params (id, numSetNodes, numSetDistFacts) # node_set_nodes # node_set_dist_fact # for i in range(len(nodeSets)): distributionFactors = [1.0] * len(nodeSets[i]) exodusFile.put_node_set_params(i + 1, len(nodeSets[i]), len(distributionFactors)) exodusFile.put_node_set(i + 1, nodeSets[i]) exodusFile.put_node_set_dist_fact(i + 1, distributionFactors) # Close the output Exodus file exodusFile.close() print("\nData written to Exodus II file {}\n".format(exodusFileName))
def main(): import sys if sys.version_info.major == 3: import exodus3 as exo else: import exodus2 as exo import os options = parse() exoin = exo.exodus(options.inputfile,mode='r',array_type='numpy') nodalFields = exoin.get_node_variable_names() zonalFields = exoin.get_element_variable_names() if options.deletevariables == []: print('nodal fields: {0}'.format(nodalFields)) print('zonal fields: {0}'.format(zonalFields)) keepNodalFields = nodalFields for deleteField in options.deletevariables: keepNodalFields = [field for field in keepNodalFields if not field.lower().startswith(deleteField.lower())] deleteNodalFields = [field for field in nodalFields if not field in keepNodalFields] keepZonalFields = zonalFields for deleteField in options.deletevariables: keepZonalFields = [field for field in keepZonalFields if not field.lower().startswith(deleteField.lower())] deleteZonalFields = [field for field in zonalFields if not field in keepZonalFields] originalTimes = exoin.get_times() if options.deleteafterstep: keepTimes = originalTimes[:min(options.deleteafterstep,len(originalTimes))] else: keepTimes = originalTimes if len(deleteNodalFields+deleteZonalFields) > 0 or not len(originalTimes) == len(keepTimes): print('\nDeleting the following fields:') for f in deleteNodalFields: print('\t{0} (nodal)'.format(f)) for f in deleteZonalFields: print('\t{0} (zonal)'.format(f)) if not len(originalTimes) == len(keepTimes): print('\nDeleting steps after {0}'.format(options.deleteafterstep)) if options.outputfile == None or options.inputfile == options.outputfile: if not options.force: print('THIS WILL OVERWRITE INPUT FILE {0}'.format(options.inputfile)) if not pymef90.confirm("Is this OK?"): print('Exiting without writing') sys.exit() outputfile = options.inputfile+'.tmp' else: if (os.path.exists(options.outputfile)): if not options.force: print('THIS WILL OVERWRITE OUTPUT FILE {0}'.format(options.outputfile)) if not pymef90.confirm("Is this OK?"): print('Exiting without writing') sys.exit() if os.path.exists(options.outputfile): os.remove(options.outputfile) outputfile = options.outputfile print('inputfile: {0}'.format(options.inputfile)) print('outputfile: {0}'.format(outputfile)) print("Copying geometry in {0}".format(outputfile)) try: exoout = exo.copy_mesh(options.inputfile,outputfile, array_type='numpy') except: print('\n\nCopying the background mesh using exodus.copy_mesh failed, trying again using exodus.copy.') print('Note that the resulting file may not readable with paraview < 5.8.0 or visit\n\n') os.remove(options.outputfile) exoin = exo.exodus(options.inputfile,mode='r') exoout = exoin.copy(outputfile) ### Adding a QA record, needed until visit fixes its exodus reader import datetime import os.path import sys QA_rec_len = 32 QA = [os.path.basename(sys.argv[0]),os.path.basename(__file__),datetime.date.today().strftime('%Y%m%d'),datetime.datetime.now().strftime("%H:%M:%S")] exoout.put_qa_records([[ q[0:31] for q in QA],]) print("formatting {0}".format(outputfile)) exoout.set_global_variable_number(0) exoout.set_node_variable_number(len(keepNodalFields)) for i in range(len(keepNodalFields)): exoout.put_node_variable_name(keepNodalFields[i],i+1) exoout.set_element_variable_number(len(keepZonalFields)) for i in range(len(keepZonalFields)): exoout.put_element_variable_name(keepZonalFields[i],i+1) exoout.set_element_variable_truth_table([True] * exoout.numElemBlk.value * len(keepZonalFields)) step = 1 for t in keepTimes: print("processing time step {0}: t={1:.2e}".format(step,t)) exoout.put_time(step,t) for f in keepNodalFields: exoout.put_node_variable_values(f,step,exoin.get_node_variable_values(f,step)) for f in keepZonalFields: for cs in exoin.get_elem_blk_ids(): exoout.put_element_variable_values(cs,f,step,exoin.get_element_variable_values(cs,f,step)) step += 1 exoout.close() if options.outputfile == None: os.rename(outputfile,options.inputfile) else: print('Nothing to delete') return 0