# -*- coding: utf-8 -*- ### ### This file is generated automatically by SALOME v8.3.0 with dump python functionality ###### Run with DPS_lead_position_V9.py import sys import salome salome.salome_init() theStudy = salome.myStudy import salome_notebook notebook = salome_notebook.NoteBook(theStudy) sys.path.insert( 0, r'/home/trieu/electrode_dir') ### ### GEOM component ### ########################################### extra code 1 V10 15/12/18############################################# ###### This file runs with DBS_lead_position_V10.py import os sys.path.insert( 0, r'{}'.format(os.getcwd())) sys.path.append('/usr/local/lib/python2.7/dist-packages') #from pandas import read_csv ##### DEFAULT LIST ##### #Lead2nd_Enable = True #Xt = 0 #Yt = 5
#!/usr/bin/env python import sys import salome import os import tempfile salome.salome_init() import salome_notebook notebook = salome_notebook.NoteBook() import salome_version #Prendre la version du SALOME #Salome version if salome_version.getVersions() >= [9, 4, 0]: #Si le dossier "WORK" n'existe pas, créez-le, sinon il passe. #pour la version 9.4.0 try: os.makedirs("WORK") except OSError: pass adresseAUX = os.getcwd() + '/WORK' else: #Salome 9.3.0 adresseAUX = os.getcwd() #Adresse du dossier adresse = adresseAUX #C'est possible de mettre autre dossier(Si le dossier WORK est protege), par exemple: adresse = "C:/Users/Daniel ~/Desktop" sys.path.insert(0, r'%s' % (adresse))
def create(self): # Read data from input file with open(self.dataFilename) as dataFile: data = json.load(dataFile) elements = data['elements'] connections = data['connections'] # --> Delete this reference data and repopulate it with the objects # while going through elements for conn in connections: conn['relatedElements'] = [] # End <-- meshSize = self.meshSize dec = 7 # 4 decimals for length in mm tol = 10**(-dec - 3 + 1) self.tolLoc = tol * 10 * 2 tolLoc = self.tolLoc NEW_SALOME = int(salome_version.getVersion()[0]) >= 9 salome.salome_init() theStudy = salome.myStudy notebook = salome_notebook.NoteBook(theStudy) ### ### GEOM component ### import GEOM from salome.geom import geomBuilder import math import SALOMEDS gg = salome.ImportComponentGUI('GEOM') if NEW_SALOME: geompy = geomBuilder.New() else: geompy = geomBuilder.New(theStudy) self.geompy = geompy O = geompy.MakeVertex(0, 0, 0) OX = geompy.MakeVectorDXDYDZ(1, 0, 0) OY = geompy.MakeVectorDXDYDZ(0, 1, 0) OZ = geompy.MakeVectorDXDYDZ(0, 0, 1) geompy.addToStudy(O, 'O') geompy.addToStudy(OX, 'OX') geompy.addToStudy(OY, 'OY') geompy.addToStudy(OZ, 'OZ') if len([e for e in elements if e['geometryType'] == 'line']) > 0: buildingShapeType = 'EDGE' if len([e for e in elements if e['geometryType'] == 'surface']) > 0: buildingShapeType = 'FACE' ### Define entities ### start_time = time.time() print('Defining Object Geometry') init_time = start_time # Loop 1 for el in elements: el['elemObj'] = self.makeObject(el['geometry'], el['geometryType']) el['connObjs'] = [None for _ in el['connections']] el['linkObjs'] = [None for _ in el['connections']] el['linkPointObjs'] = [[None, None] for _ in el['connections']] for j, rel in enumerate(el['connections']): conn = [ c for c in connections if c['ifcName'] == rel['relatedConnection'] ][0] if rel['eccentricity']: rel['index'] = len(conn['relatedElements']) + 1 conn['relatedElements'].append(rel) if not rel['eccentricity']: el['connObjs'][j] = self.makeObject( conn['geometry'], conn['geometryType']) else: if conn['geometryType'] == 'point': geometry = self.getLinkGeometry( rel['eccentricity'], el['orientation'], conn['geometry']) el['connObjs'][j] = self.makeObject( geometry[0], conn['geometryType']) el['linkPointObjs'][j][0] = self.geompy.MakeVertex( geometry[0][0], geometry[0][1], geometry[0][2]) el['linkPointObjs'][j][1] = self.geompy.MakeVertex( geometry[1][0], geometry[1][1], geometry[1][2]) el['linkObjs'][j] = self.geompy.MakeLineTwoPnt( el['linkPointObjs'][j][0], el['linkPointObjs'][j][1]) else: print('Eccentricity defined for a %s geometryType' % conn['geometryType']) el['partObj'] = self.makePartition( [el['elemObj']] + el['connObjs'], el['geometryType']) el['elemObj'] = geompy.GetInPlace(el['partObj'], el['elemObj']) for j, rel in enumerate(el['connections']): el['connObjs'][j] = geompy.GetInPlace(el['partObj'], el['connObjs'][j]) for conn in connections: conn['connObj'] = self.makeObject(conn['geometry'], conn['geometryType']) # Make assemble of Building Object bldObjs = [] bldObjs.extend([el['partObj'] for el in elements]) bldObjs.extend( flatten([[link for link in el['linkObjs'] if link] for el in elements])) bldObjs.extend([conn['connObj'] for conn in connections]) bldComp = geompy.MakeCompound(bldObjs) # bldComp = geompy.MakePartition(bldObjs, [], [], [], self.geompy.ShapeType[buildingShapeType], 0, [], 1) geompy.addToStudy(bldComp, 'bldComp') # Loop 2 for el in elements: # geompy.addToStudy(el['partObj'], self.getGroupName(el['ifcName'])) geompy.addToStudyInFather(el['partObj'], el['elemObj'], self.getGroupName(el['ifcName'])) for j, rel in enumerate(el['connections']): conn = [ c for c in connections if c['ifcName'] == rel['relatedConnection'] ][0] rel['conn_string'] = None if conn['geometryType'] == 'point': rel['conn_string'] = '_0DC_' if conn['geometryType'] == 'line': rel['conn_string'] = '_1DC_' if conn['geometryType'] == 'surface': rel['conn_string'] = '_2DC_' geompy.addToStudyInFather( el['partObj'], el['connObjs'][j], self.getGroupName(el['ifcName']) + rel['conn_string'] + self.getGroupName(rel['relatedConnection'])) if rel['eccentricity']: pass # geompy.addToStudy(el['linkObjs'][j], self.getGroupName(el['ifcName']) + '_1DR_' + self.getGroupName(rel['relatedConnection'])) # geompy.addToStudyInFather(el['linkObjs'][j], el['linkPointObjs'][j][0], self.getGroupName(rel['relatedConnection']) + '_0DC_' + self.getGroupName(el['ifcName'])) # geompy.addToStudyInFather(el['linkObjs'][j], el['linkPointObjs'][j][0], self.getGroupName(rel['relatedConnection']) + '_0DC_%g' % rel['index']) for conn in connections: # geompy.addToStudy(conn['connObj'], self.getGroupName(conn['ifcName'])) geompy.addToStudyInFather(conn['connObj'], conn['connObj'], self.getGroupName(conn['ifcName'])) elapsed_time = time.time() - init_time init_time += elapsed_time print('Building Geometry Defined in %g sec' % (elapsed_time)) if len([e for e in elements if e['geometryType'] == 'line']) > 0: buildingShapeType = 'EDGE' if len([e for e in elements if e['geometryType'] == 'surface']) > 0: buildingShapeType = 'FACE' # Define and add groups for all curve and surface members if len([e for e in elements if e['geometryType'] == 'line']) > 0: # Make compound of requested group compoundTemp = geompy.MakeCompound([ e['elemObj'] for e in elements if e['geometryType'] == 'line' ]) # Define group object and add to study curveCompound = geompy.GetInPlace(bldComp, compoundTemp) geompy.addToStudyInFather(bldComp, curveCompound, 'CurveMembers') if len([e for e in elements if e['geometryType'] == 'surface']) > 0: # Make compound of requested group compoundTemp = geompy.MakeCompound([ e['elemObj'] for e in elements if e['geometryType'] == 'surface' ]) # Define group object and add to study surfaceCompound = geompy.GetInPlace(bldComp, compoundTemp) geompy.addToStudyInFather(bldComp, surfaceCompound, 'SurfaceMembers') # Loop 3 for el in elements: # el['partObj'] = geompy.RestoreGivenSubShapes(bldComp, [el['partObj']], GEOM.FSM_GetInPlace, False, False)[0] geompy.addToStudyInFather(bldComp, el['elemObj'], self.getGroupName(el['ifcName'])) for j, rel in enumerate(el['connections']): geompy.addToStudyInFather( bldComp, el['connObjs'][j], self.getGroupName(el['ifcName']) + rel['conn_string'] + self.getGroupName(rel['relatedConnection'])) if rel['eccentricity']: # point geometry geompy.addToStudyInFather( bldComp, el['linkObjs'][j], self.getGroupName(el['ifcName']) + '_1DR_' + self.getGroupName(rel['relatedConnection'])) geompy.addToStudyInFather( bldComp, el['linkPointObjs'][j][0], self.getGroupName(rel['relatedConnection']) + '_0DC_' + self.getGroupName(el['ifcName'])) geompy.addToStudyInFather( bldComp, el['linkPointObjs'][j][1], self.getGroupName(rel['relatedConnection']) + '_0DC_%g' % rel['index']) for conn in connections: # conn['connObj'] = geompy.RestoreGivenSubShapes(bldComp, [conn['connObj']], GEOM.FSM_GetInPlace, False, False)[0] geompy.addToStudyInFather(bldComp, conn['connObj'], self.getGroupName(conn['ifcName'])) elapsed_time = time.time() - init_time init_time += elapsed_time print('Building Geometry Groups Defined in %g sec' % (elapsed_time)) ### ### SMESH component ### import SMESH from salome.smesh import smeshBuilder print('Defining Mesh Components') if NEW_SALOME: smesh = smeshBuilder.New() else: smesh = smeshBuilder.New(theStudy) bldMesh = smesh.Mesh(bldComp) Regular_1D = bldMesh.Segment() Local_Length_1 = Regular_1D.LocalLength(meshSize, None, tolLoc) if buildingShapeType == 'FACE': NETGEN2D_ONLY = bldMesh.Triangle(algo=smeshBuilder.NETGEN_2D) NETGEN2D_Pars = NETGEN2D_ONLY.Parameters() NETGEN2D_Pars.SetMaxSize(meshSize) NETGEN2D_Pars.SetOptimize(1) NETGEN2D_Pars.SetFineness(2) NETGEN2D_Pars.SetMinSize(meshSize / 5.0) NETGEN2D_Pars.SetUseSurfaceCurvature(1) NETGEN2D_Pars.SetQuadAllowed(1) NETGEN2D_Pars.SetSecondOrder(0) NETGEN2D_Pars.SetFuseEdges(254) isDone = bldMesh.Compute() ## Set names of Mesh objects smesh.SetName(Regular_1D.GetAlgorithm(), 'Regular_1D') smesh.SetName(Local_Length_1, 'Local_Length_1') if buildingShapeType == 'FACE': smesh.SetName(NETGEN2D_ONLY.GetAlgorithm(), 'NETGEN2D_ONLY') smesh.SetName(NETGEN2D_Pars, 'NETGEN2D_Pars') smesh.SetName(bldMesh.GetMesh(), 'bldMesh') elapsed_time = time.time() - init_time init_time += elapsed_time print('Meshing Operations Completed in %g sec' % (elapsed_time)) # Define and add groups for all curve and surface members if len([e for e in elements if e['geometryType'] == 'line']) > 0: tempgroup = bldMesh.GroupOnGeom(curveCompound, 'CurveMembers', SMESH.EDGE) smesh.SetName(tempgroup, 'CurveMembers') if len([e for e in elements if e['geometryType'] == 'surface']) > 0: tempgroup = bldMesh.GroupOnGeom(surfaceCompound, 'SurfaceMembers', SMESH.FACE) smesh.SetName(tempgroup, 'SurfaceMembers') # Define groups in Mesh for el in elements: if el['geometryType'] == 'line': shapeType = SMESH.EDGE if el['geometryType'] == 'surface': shapeType = SMESH.FACE tempgroup = bldMesh.GroupOnGeom(el['elemObj'], self.getGroupName(el['ifcName']), shapeType) smesh.SetName(tempgroup, self.getGroupName(el['ifcName'])) for j, rel in enumerate(el['connections']): tempgroup = bldMesh.GroupOnGeom( el['connObjs'][j], self.getGroupName(el['ifcName']) + rel['conn_string'] + self.getGroupName(rel['relatedConnection']), SMESH.NODE) smesh.SetName( tempgroup, self.getGroupName(el['ifcName']) + rel['conn_string'] + self.getGroupName(rel['relatedConnection'])) rel['node'] = (bldMesh.GetIDSource(tempgroup.GetNodeIDs(), SMESH.NODE)).GetIDs()[0] if rel['eccentricity']: tempgroup = bldMesh.GroupOnGeom( el['linkObjs'][j], self.getGroupName(el['ifcName']) + '_1DR_' + self.getGroupName(rel['relatedConnection']), SMESH.EDGE) smesh.SetName( tempgroup, self.getGroupName(el['ifcName']) + '_1DR_' + self.getGroupName(rel['relatedConnection'])) tempgroup = bldMesh.GroupOnGeom( el['linkPointObjs'][j][0], self.getGroupName(rel['relatedConnection']) + '_0DC_' + self.getGroupName(el['ifcName']), SMESH.NODE) smesh.SetName( tempgroup, self.getGroupName(rel['relatedConnection']) + '_0DC_' + self.getGroupName(el['ifcName'])) rel['eccNode'] = (bldMesh.GetIDSource( tempgroup.GetNodeIDs(), SMESH.NODE)).GetIDs()[0] tempgroup = bldMesh.GroupOnGeom( el['linkPointObjs'][j][1], self.getGroupName(rel['relatedConnection']) + '_0DC_' + self.getGroupName(rel['relatedConnection']), SMESH.NODE) smesh.SetName( tempgroup, self.getGroupName(rel['relatedConnection']) + '_0DC_%g' % rel['index']) for conn in connections: tempgroup = bldMesh.GroupOnGeom(conn['connObj'], self.getGroupName(conn['ifcName']), SMESH.NODE) smesh.SetName(tempgroup, self.getGroupName(conn['ifcName'])) nodesId = bldMesh.GetIDSource(tempgroup.GetNodeIDs(), SMESH.NODE) tempgroup = bldMesh.Add0DElementsToAllNodes( nodesId, self.getGroupName(conn['ifcName'])) smesh.SetName(tempgroup, self.getGroupName(conn['ifcName'] + '_0D')) if conn['geometryType'] == 'point': conn['node'] = nodesId.GetIDs()[0] if conn['geometryType'] == 'line': tempgroup = bldMesh.GroupOnGeom( conn['connObj'], self.getGroupName(conn['ifcName']), SMESH.EDGE) smesh.SetName(tempgroup, self.getGroupName(conn['ifcName'])) if conn['geometryType'] == 'surface': tempgroup = bldMesh.GroupOnGeom( conn['connObj'], self.getGroupName(conn['ifcName']), SMESH.FACE) smesh.SetName(tempgroup, self.getGroupName(conn['ifcName'])) # create 1D SEG2 spring elements for el in elements: for j, rel in enumerate(el['connections']): conn = [ c for c in connections if c['ifcName'] == rel['relatedConnection'] ][0] if conn['geometryType'] == 'point': grpName = bldMesh.CreateEmptyGroup( SMESH.EDGE, self.getGroupName(el['ifcName']) + '_1DS_' + self.getGroupName(rel['relatedConnection'])) smesh.SetName( grpName, self.getGroupName(el['ifcName']) + '_1DS_' + self.getGroupName(rel['relatedConnection'])) if not rel['eccentricity']: conn = [ conn for conn in connections if conn['ifcName'] == rel['relatedConnection'] ][0] grpName.Add( [bldMesh.AddEdge([conn['node'], rel['node']])]) else: grpName.Add( [bldMesh.AddEdge([rel['eccNode'], rel['node']])]) self.mesh = bldMesh self.meshNodes = bldMesh.GetNodesId() elapsed_time = time.time() - init_time init_time += elapsed_time print('Mesh Groups Defined in %g sec' % (elapsed_time)) try: if NEW_SALOME: bldMesh.ExportMED(self.medFilename, auto_groups=0, minor=40, overwrite=1, meshPart=None, autoDimension=0) else: bldMesh.ExportMED(self.medFilename, 0, SMESH.MED_V2_2, 1, None, 0) except: print('ExportMED() failed. Invalid file name?') if salome.sg.hasDesktop(): if NEW_SALOME: salome.sg.updateObjBrowser() else: salome.sg.updateObjBrowser(1) elapsed_time = init_time - start_time print('ALL Operations Completed in %g sec' % (elapsed_time))
def create(self): # Read data from input file with open(self.dataFilename) as dataFile: data = json.load(dataFile) # print(len(data['elements'])) # elements = self.select(data['elements']) # print(len(elements)) elements = data["elements"] connections = data["connections"] # --> Delete this reference data and repopulate it with the objects # while going through elements for conn in connections: conn["relatedElements"] = [] # End <-- meshSize = self.meshSize zGround = self.zGround dec = 5 # 4 decimals for length in mm tol = 10**(-dec - 3 + 1) self.tolLoc = tol * 10 * 2 tolLoc = self.tolLoc NEW_SALOME = int(salome_version.getVersion()[0]) >= 9 salome.salome_init() theStudy = salome.myStudy notebook = salome_notebook.NoteBook(theStudy) ### ### GEOM component ### import GEOM from salome.geom import geomBuilder import math import SALOMEDS gg = salome.ImportComponentGUI("GEOM") if NEW_SALOME: geompy = geomBuilder.New() else: geompy = geomBuilder.New(theStudy) self.geompy = geompy O = geompy.MakeVertex(0, 0, 0) OX = geompy.MakeVectorDXDYDZ(1, 0, 0) OY = geompy.MakeVectorDXDYDZ(0, 1, 0) OZ = geompy.MakeVectorDXDYDZ(0, 0, 1) geompy.addToStudy(O, "O") geompy.addToStudy(OX, "OX") geompy.addToStudy(OY, "OY") geompy.addToStudy(OZ, "OZ") if len([e for e in elements if e["geometryType"] == "line"]) > 0: buildingShapeType = "EDGE" if len([e for e in elements if e["geometryType"] == "surface"]) > 0: buildingShapeType = "FACE" ### Define entities ### start_time = time.time() print("Defining Object Geometry") init_time = start_time # Loop 1 for el in elements: el["elemObj"] = self.makeObject(el["geometry"], el["geometryType"]) el["linkObjs"] = [None for _ in el["connections"]] for j, rel in enumerate(el["connections"]): conn = [ c for c in connections if c["referenceName"] == rel["relatedConnection"] ][0] if rel["eccentricity"]: rel["index"] = len(conn["relatedElements"]) + 1 geometry = self.getLinkGeometry(rel["eccentricity"], el["orientation"], conn["geometry"]) el["linkObjs"][j] = self.makeObject(geometry, "line") conn["relatedElements"].append(rel) # Make assemble of Building Object bldObjs = [] bldObjs.extend([el["elemObj"] for el in elements]) bldObjs.extend( flatten([[link for link in el["linkObjs"] if link] for el in elements])) # bldComp = geompy.MakeCompound(bldObjs) bldComp = geompy.MakePartition( bldObjs, [], [], [], self.geompy.ShapeType[buildingShapeType], 0, [], 1) geompy.addToStudy(bldComp, "bldComp") elapsed_time = time.time() - init_time init_time += elapsed_time print("Building Geometry Defined in %g sec" % (elapsed_time)) # Define and add groups for all curve, surface and rigid members if len([e for e in elements if e["geometryType"] == "line"]) > 0: # Make compound of requested group compoundTemp = geompy.MakeCompound([ e["elemObj"] for e in elements if e["geometryType"] == "line" ]) # Define group object and add to study curveCompound = geompy.GetInPlace(bldComp, compoundTemp, True) geompy.addToStudyInFather(bldComp, curveCompound, "CurveMembers") if len([e for e in elements if e["geometryType"] == "surface"]) > 0: # Make compound of requested group compoundTemp = geompy.MakeCompound([ e["elemObj"] for e in elements if e["geometryType"] == "surface" ]) # Define group object and add to study surfaceCompound = geompy.GetInPlace(bldComp, compoundTemp, True) geompy.addToStudyInFather(bldComp, surfaceCompound, "SurfaceMembers") linkObjs = list( flatten([[obj for obj in el["linkObjs"] if obj] for el in elements])) if len(linkObjs) > 0: # Make compound of requested group compoundTemp = geompy.MakeCompound(linkObjs) # Define group object and add to study rigidCompound = geompy.GetInPlace(bldComp, compoundTemp, True) geompy.addToStudyInFather(bldComp, rigidCompound, "RigidMembers") for el in elements: # el['partObj'] = geompy.RestoreGivenSubShapes(bldComp, [el['partObj']], GEOM.FSM_GetInPlace, False, False)[0] el["elemObj"] = geompy.GetInPlace(bldComp, el["elemObj"], True) geompy.addToStudyInFather(bldComp, el["elemObj"], self.getGroupName(el["referenceName"])) for j, rel in enumerate(el["connections"]): if rel["eccentricity"]: # point geometry el["linkObjs"][j] = geompy.GetInPlace( bldComp, el["linkObjs"][j], True) geompy.addToStudyInFather( bldComp, el["linkObjs"][j], self.getGroupName(el["referenceName"]) + "_1DR_" + self.getGroupName(rel["relatedConnection"]), ) elapsed_time = time.time() - init_time init_time += elapsed_time print("Building Geometry Groups Defined in %g sec" % (elapsed_time)) ### ### SMESH component ### import SMESH from salome.smesh import smeshBuilder print("Defining Mesh Components") if NEW_SALOME: smesh = smeshBuilder.New() else: smesh = smeshBuilder.New(theStudy) bldMesh = smesh.Mesh(bldComp) Regular_1D = bldMesh.Segment() Local_Length_1 = Regular_1D.LocalLength(meshSize, None, tolLoc) if buildingShapeType == "FACE": NETGEN2D_ONLY = bldMesh.Triangle(algo=smeshBuilder.NETGEN_2D) NETGEN2D_Pars = NETGEN2D_ONLY.Parameters() NETGEN2D_Pars.SetMaxSize(meshSize) NETGEN2D_Pars.SetOptimize(1) NETGEN2D_Pars.SetFineness(2) NETGEN2D_Pars.SetMinSize(meshSize / 5.0) NETGEN2D_Pars.SetUseSurfaceCurvature(1) NETGEN2D_Pars.SetQuadAllowed(1) NETGEN2D_Pars.SetSecondOrder(0) NETGEN2D_Pars.SetFuseEdges(254) isDone = bldMesh.Compute() coincident_nodes_on_part = bldMesh.FindCoincidentNodesOnPart([bldMesh], tolLoc, [], 0) if coincident_nodes_on_part: # bldMesh.MergeNodes(coincident_nodes_on_part, [], 0) # print(f'{len(coincident_nodes_on_part)} Sets of Coincident Nodes Found and Merged') print( f"{len(coincident_nodes_on_part)} Sets of Coincident Nodes Found" ) print(f"{coincident_nodes_on_part}") ## Set names of Mesh objects smesh.SetName(Regular_1D.GetAlgorithm(), "Regular_1D") smesh.SetName(Local_Length_1, "Local_Length_1") if buildingShapeType == "FACE": smesh.SetName(NETGEN2D_ONLY.GetAlgorithm(), "NETGEN2D_ONLY") smesh.SetName(NETGEN2D_Pars, "NETGEN2D_Pars") smesh.SetName(bldMesh.GetMesh(), "bldMesh") elapsed_time = time.time() - init_time init_time += elapsed_time print("Meshing Operations Completed in %g sec" % (elapsed_time)) # Define and add groups for all curve, surface and rigid members if len([e for e in elements if e["geometryType"] == "line"]) > 0: tempgroup = bldMesh.GroupOnGeom(curveCompound, "CurveMembers", SMESH.EDGE) smesh.SetName(tempgroup, "CurveMembers") if len([e for e in elements if e["geometryType"] == "surface"]) > 0: tempgroup = bldMesh.GroupOnGeom(surfaceCompound, "SurfaceMembers", SMESH.FACE) smesh.SetName(tempgroup, "SurfaceMembers") if len(linkObjs) > 0: tempgroup = bldMesh.GroupOnGeom(rigidCompound, "RigidMembers", SMESH.EDGE) smesh.SetName(tempgroup, "RigidMembers") # Define groups in Mesh for el in elements: if el["geometryType"] == "line": shapeType = SMESH.EDGE if el["geometryType"] == "surface": shapeType = SMESH.FACE tempgroup = bldMesh.GroupOnGeom( el["elemObj"], self.getGroupName(el["referenceName"]), shapeType) smesh.SetName(tempgroup, self.getGroupName(el["referenceName"])) for j, rel in enumerate(el["connections"]): if rel["eccentricity"]: tempgroup = bldMesh.GroupOnGeom( el["linkObjs"][j], self.getGroupName(el["referenceName"]) + "_1DR_" + self.getGroupName(rel["relatedConnection"]), SMESH.EDGE, ) smesh.SetName( tempgroup, self.getGroupName(el["referenceName"]) + "_1DR_" + self.getGroupName(rel["relatedConnection"]), ) self.mesh = bldMesh self.meshNodes = bldMesh.GetNodesId() # Find ground supports and extract node coordinates grdSupps = bldMesh.CreateEmptyGroup(SMESH.NODE, "grdSupps") for node in self.meshNodes: coords = bldMesh.GetNodeXYZ(node) if abs(coords[2] - self.zGround) < tolLoc: grdSupps.Add([node]) smesh.SetName(grdSupps, "grdSupps") elapsed_time = time.time() - init_time init_time += elapsed_time print("Mesh Groups Defined in %g sec" % (elapsed_time)) try: if NEW_SALOME: bldMesh.ExportMED( self.medFilename, auto_groups=0, minor=40, overwrite=1, meshPart=None, autoDimension=0, ) else: bldMesh.ExportMED(self.medFilename, 0, SMESH.MED_V2_2, 1, None, 0) except: print("ExportMED() failed. Invalid file name?") if salome.sg.hasDesktop(): if NEW_SALOME: salome.sg.updateObjBrowser() else: salome.sg.updateObjBrowser(1) elapsed_time = init_time - start_time print("ALL Operations Completed in %g sec" % (elapsed_time))
def start_convtk(self, Flag_json=0): SystemSlash = self.SystemSlash list_load_path = self._creat_dic() # 存储目录列表 # 利用 salome 打开 stp 文件,并进行拆分,另存为 vtk 文件 salome.salome_init() notebook = salome_notebook.NoteBook() sys.path.insert(0, list_load_path[7][0]) geompy = geomBuilder.New() O = geompy.MakeVertex(0, 0, 0) OX = geompy.MakeVectorDXDYDZ(1, 0, 0) OY = geompy.MakeVectorDXDYDZ(0, 1, 0) OZ = geompy.MakeVectorDXDYDZ(0, 0, 1) try: if ".stp" == list_load_path[7][3]: Input = geompy.ImportSTEP(self.inputfilePath, False, True) elif ".brep" == list_load_path[7][3]: Input = geompy.ImportBREP(self.inputfilePath) elif ".iges" == list_load_path[7][3]: Input = geompy.ImportIGES(self.inputfilePath) print("Identification file type successful") except Exception: print("IOError: file type must be .stp .brep .iges") return None faces = geompy.ExtractShapes(Input, geompy.ShapeType["FACE"], True) face_time = 0 for index, face in enumerate(faces): face_time = face_time + 1 LoadVTKFPath = list_load_path[ 2] + self.SystemSlash + "Face_%d" % face_time + ".vtk" geompy.ExportVTK(face, LoadVTKFPath, 0.00001) # 遍历文件夹,查询拆分个数 Face_file_NM = os.listdir(list_load_path[2]) NM_files = len(Face_file_NM) print(NM_files) # 创建stl文件 Face_stl_path = self.outputfilePath2 Face_File_stl = open(Face_stl_path, 'w') # 创建vtm文件,并写入开头 Face_VTM = self.outputfilePath1 file_vtm = open(Face_VTM, 'w') file_vtm.write( '<VTKFile type="vtkMultiBlockDataSet" version="1.0" byte_order="LittleEndian" header_type="UInt64">' + '\n') file_vtm.write(' <vtkMultiBlockDataSet>' + '\n') file_vtm.write(' <Block index="0" name="face">' + '\n') try: # 删除vtk文件中的lines信息,将删除后的文件写进RFace文件夹中 for i in range(NM_files): Flag_json = Flag_json + 1 Read_Face_Path = list_load_path[ 2] + SystemSlash + "Face_" + str(i + 1) + ".vtk" Read_RFace_Path = list_load_path[ 4] + SystemSlash + "Face_" + str(i + 1) + ".vtk" print("rewrite face:{}".format(Read_Face_Path)) Read_file = open(Read_Face_Path, "r") data_Face = Read_file.read() Read_file.close() with open(Read_RFace_Path, "w") as R_Face_file: data_Face = re.sub("LINES[ \d\n]+", "", data_Face) R_Face_file.write(data_Face) # 重写lines信息,并提出所有的cell的pointid构成lines RFace_write_path = open(Read_RFace_Path, 'a') Read_File_Path = Read_RFace_Path face_vtk = LegacyVTKReader(FileNames=Read_File_Path) Dict_keys = GetSources().keys() # 这里 solame 的GetSources不能直接取到key,需要转换一下key Dict_keys = str(Dict_keys) p1 = re.compile(r'[[](.*?)[]]', re.S) Dict_keys = re.findall(p1, Dict_keys) Dict_keys = Dict_keys[0] Dict_keys = eval(Dict_keys.replace(')(', '),(')) facefirest = GetSources()[Dict_keys] UpdatePipeline() obj = facefirest.SMProxy.GetClientSideObject() block = obj.GetOutputDataObject(0) NM_Cells = block.GetNumberOfCells() list_afterPoint = [] list_pointIdAll = [] # 所有单元构成的线 for L in range(NM_Cells): Cell_Point_NM = block.GetCellType(L) while Cell_Point_NM == 5: This_Cell = block.GetCell(L) list_PointId = [] for T in range(Cell_Point_NM - 2): pointID = This_Cell.GetPointId(T) list_PointId.append(pointID) list_PointId.sort() list_PointId = list( itertools.combinations(list_PointId, 2)) for R in range(3): list_pointIdAll.append(list_PointId[R]) break # 将没有重复的点加入到list_afterPoint中 list_afterPoint = [ item for item, count in collections.Counter( list_pointIdAll).items() if count == 1 ] RFace_write_path.write("LINES" + " " + str(len(list_afterPoint)) + " " + str(len(list_afterPoint) * 3) + "\n") for Q in range(len(list_afterPoint)): Write_line = str(list_afterPoint[Q]) Write_line = Write_line.replace("L", '').replace( "(", "").replace(")", "").replace(",", "") RFace_write_path.write("2 " + Write_line + "\n") Delete() RFace_write_path.close() Read_file = open(Read_RFace_Path, "r") data_Wire = Read_file.read() Read_file.close() with open( list_load_path[3] + SystemSlash + "Wire_" + str(i + 1) + ".vtk", "w") as R_Wire_file: data_Wire = re.sub("POLYGONS[ \d\n]+", "", data_Wire) R_Wire_file.write(data_Wire) face_vtk = LegacyVTKReader(FileNames=Read_RFace_Path) # 使其表面光滑 generateSurfaceNormals1 = GenerateSurfaceNormals( Input=face_vtk) # 同时转换.stl文件 Dict_keys = GetSources().keys() # 这里solame的GetSources不能直接取到key,需要转换一下key Dict_keys = str(Dict_keys) p1 = re.compile(r'[[](.*?)[]]', re.S) Dict_keys = re.findall(p1, Dict_keys) Dict_keys = Dict_keys[0] Dict_keys = eval(Dict_keys.replace(')(', '),(')) facefirest = GetSources()[Dict_keys[0]] UpdatePipeline() obj = facefirest.SMProxy.GetClientSideObject() block = obj.GetOutputDataObject(0) NM_Cells = block.GetNumberOfCells() Face_File_stl.write('solid ' + 'Face_' + str(i + 1) + '\n') # 遍历vtk中所有的cell,并取每个cell的3个点 for L in range(NM_Cells): Cell_Point_NM = block.GetCellType(L) while Cell_Point_NM == 5: Face_File_stl.write(' facet normal 0 0 0' + '\n') Face_File_stl.write(' outer loop' + '\n') This_Cell = block.GetCell(L) for T in range(Cell_Point_NM - 2): pointID = This_Cell.GetPointId(T) pointCon = block.GetPoint(pointID) W_Line = str(pointCon) W_Line = W_Line.replace("(", " ").replace( ")", " ").replace(",", " ") # 去除列表中的小括号和逗号 Face_File_stl.write(' vertex ' + W_Line + '\n') Face_File_stl.write(' endloop' + '\n') Face_File_stl.write(' endfacet' + '\n') break Face_File_stl.write('endsolid' + '\n') # 转换.vtm Load_File_Path = list_load_path[ 5] + SystemSlash + "Face_" + str(i + 1) + ".vtp" # 将相关信息写入.vtm中 Write_file = 'face' + SystemSlash + 'Face_' + str(i + 1) + '.vtp' file_vtm.write(' <DataSet index="' + str(i) + '"' + ' name="' + 'Face_' + str(i + 1) + '" file="' + Write_file + '">' + '\n') file_vtm.write(' </DataSet>' + '\n') SaveData(Load_File_Path, proxy=generateSurfaceNormals1) Delete() Delete(face_vtk) file_vtm.write(' </Block>' + '\n') file_vtm.write(' <Block index="1" name="Wires">' + '\n') for i in range(NM_files): Read_Wire_Path = list_load_path[ 3] + SystemSlash + "Wire_" + str(i + 1) + ".vtk" wire_vtk = LegacyVTKReader(FileNames=Read_Wire_Path) # 转换.vtm Load_File_Path = list_load_path[ 6] + SystemSlash + "Wire_" + str(i + 1) + ".vtp" Write_file = 'wire' + SystemSlash + 'Wire_' + str(i + 1) + '.vtp' file_vtm.write(' <DataSet index="' + str(i) + '"' + ' name="' + 'Wire_' + str(i + 1) + '" file="' + Write_file + '">' + '\n') file_vtm.write(' </DataSet>' + '\n') SaveData(Load_File_Path, proxy=wire_vtk) Delete() file_vtm.write(' </Block>' + '\n') file_vtm.write(' </vtkMultiBlockDataSet>' + '\n') file_vtm.write('</VTKFile>' + '\n') print("rewrite face successful") print("rewrite wire successful") res_json = {"faceNumber": NM_files} print("result json|{}".format(json.dumps(res_json))) except Exception: print("Error:conversion died") return None del SystemSlash, list_load_path file_vtm.close() Face_File_stl.close() return Flag_json
def start_creat(self): try: stl_path = self.stl_path notebook = salome_notebook.NoteBook() geompy = geomBuilder.New() O = geompy.MakeVertex(0, 0, 0) OX = geompy.MakeVectorDXDYDZ(1, 0, 0) OY = geompy.MakeVectorDXDYDZ(0, 1, 0) OZ = geompy.MakeVectorDXDYDZ(0, 0, 1) Vertex_1 = geompy.MakeVertex(*self.fpoint) Vertex_2 = geompy.MakeVertex(*self.spoint) Box_1 = geompy.MakeBoxTwoPnt(Vertex_1, Vertex_2) [Face_1, Face_2, Face_3, Face_4, Face_5, Face_6] = geompy.ExtractShapes(Box_1, geompy.ShapeType["FACE"], True) geompy.ExportSTL(Face_1, stl_path + "boxFace_1.stl", True, 0.00001, True) geompy.ExportSTL(Face_2, stl_path + "boxFace_2.stl", True, 0.00001, True) geompy.ExportSTL(Face_3, stl_path + "boxFace_3.stl", True, 0.00001, True) geompy.ExportSTL(Face_4, stl_path + "boxFace_4.stl", True, 0.00001, True) geompy.ExportSTL(Face_5, stl_path + "boxFace_5.stl", True, 0.00001, True) geompy.ExportSTL(Face_6, stl_path + "boxFace_6.stl", True, 0.00001, True) save_vtk_dic = self.vtm_path + "VTK/" os.mkdir(save_vtk_dic) geompy.ExportVTK(Face_1, save_vtk_dic + "boxface1.vtk", 0.00001) geompy.ExportVTK(Face_2, save_vtk_dic + "boxface2.vtk", 0.00001) geompy.ExportVTK(Face_3, save_vtk_dic + "boxface3.vtk", 0.00001) geompy.ExportVTK(Face_4, save_vtk_dic + "boxface4.vtk", 0.00001) geompy.ExportVTK(Face_5, save_vtk_dic + "boxface5.vtk", 0.00001) geompy.ExportVTK(Face_6, save_vtk_dic + "boxface6.vtk", 0.00001) # 删除vtk中的line信息 self.del_line(save_vtk_dic, 1) self.del_line(save_vtk_dic, 2) self.del_line(save_vtk_dic, 3) self.del_line(save_vtk_dic, 4) self.del_line(save_vtk_dic, 5) self.del_line(save_vtk_dic, 6) # 将六个面信息一起写入一个文件 temall_stl = stl_path + "/" + "tem_file.stl" filebox = open(temall_stl, "a") self.merge_boxface(1, filebox) self.merge_boxface(2, filebox) self.merge_boxface(3, filebox) self.merge_boxface(4, filebox) self.merge_boxface(5, filebox) self.merge_boxface(6, filebox) filebox.close() add_stl = open(stl_path + self.stl_name, "a") with open(temall_stl) as w: wi = w.readlines() for i in range(len(wi)): add_stl.write(wi[i]) add_stl.close() except Exception: print("stl,vtk生成失败") try: # 转换vtp,并生成vtm Face_VTM = self.vtm_path + "{}".format(self.vtm_name) file_vtm = open(Face_VTM, 'w') file_vtm.write( '<VTKFile type="vtkMultiBlockDataSet" version="1.0" byte_order="LittleEndian" header_type="UInt64">' + '\n') file_vtm.write(' <vtkMultiBlockDataSet>' + '\n') file_vtm.write(' <Block index="0" name="box_face">' + '\n') # 创建一个boxface用来存放vtp os.makedirs(self.vtm_path + "boxface") file_num = os.listdir(self.vtm_path + "VTK") NM_file = len(file_num) for i in range(NM_file): # 写入vtm相关信息 Write_file = 'boxface' + "/" + 'boxface' + str(i + 1) + '.vtp' file_vtm.write(' <DataSet index="' + str(i) + '"' + ' name="' + 'boxface' + str(i + 1) + '" file="' + Write_file + '">' + '\n') file_vtm.write(' </DataSet>' + '\n') file_vtm.write(' </Block>' + '\n') file_vtm.write(' </vtkMultiBlockDataSet>' + '\n') file_vtm.write('</VTKFile>' + '\n') file_vtm.close() os.remove(stl_path + "boxFace_1.stl") os.remove(stl_path + "boxFace_2.stl") os.remove(stl_path + "boxFace_3.stl") os.remove(stl_path + "boxFace_4.stl") os.remove(stl_path + "boxFace_5.stl") os.remove(stl_path + "boxFace_6.stl") os.remove(stl_path + "tem_file.stl") except: print("vtm生成失败")