def trihedron_withdisplay(context): import GEOM from salome.geom import geomBuilder # Intialize the geompy factory with the active study activeStudy = context.study geompy = geomBuilder.New(activeStudy) # Create the objects Vx = geompy.MakeVectorDXDYDZ(10, 0, 0) Vy = geompy.MakeVectorDXDYDZ(0, 10, 0) Vz = geompy.MakeVectorDXDYDZ(0, 0, 10) origin = geompy.MakeVertex(0, 0, 0) # Register the objects in the active study entries=[] entries.append(geompy.addToStudy( Vx, "Vx" )) entries.append(geompy.addToStudy( Vy, "Vy" )) entries.append(geompy.addToStudy( Vz, "Vz" )) entries.append(geompy.addToStudy( origin, "origin" )) # This part is to automatically display the objects in the active viewer. gcomp = salome.ImportComponentGUI("GEOM") for entry in entries: gcomp.createAndDisplayFitAllGO(entry)
def setUp(self): # initializing salome also creates a study. # clearing the study in order to have a clean study for each test. # This is much faster than re-launching salome for each test self.study = salome.myStudy self.study.Clear() self.study.Init() self.geompy = geomBuilder.New() self.smesh = smeshBuilder.New()
def TEST_createObject(): """ WARNING: for this test, we need GEOM (used to create an object) """ import GEOM from salome.geom import geomBuilder geompy = geomBuilder.New(salome.myStudy) box = geompy.MakeBoxDXDYDZ(200, 200, 200) id = geompy.addToStudy( box, 'box' ) return id
def setUp(self): # initializing salome also creates a study. # clearing the study in order to have a clean study for each test. # This is much faster than re-launching salome for each test self.study = salome.myStudy ResetStudy() self.assertEqual(GetNumberOfObjectsInStudy(), 0, msg="Resetting the study failed!") self.geompy = geomBuilder.New() self.smesh = smeshBuilder.New()
def brep2shapedirs(Pi, debug=1000000): geompy = geomBuilder.New(salome.myStudy) #debug=last index 1:activate view occ #debug=digit 2:delete obj #debug=digit 4:restoreswitch salome geom module if int(str(debug)[len(str(debug)) - 4]) == 1: restoresalomeiparm(module='Geometry') if int(str(debug)[len(str(debug)) - 2]) == 1: delobjregex(complaint="Shape*", s="delete", module='GEOM') #instantiate salome kind occ object Shape1 = geompy.ImportBREP(Pi.brepfile) Pi.brepshapeobj = Shape1 #debug checksum [Xmin1, Xmax1, Ymin1, Ymax1, Zmin1, Zmax1] = geompy.BoundingBox(Shape1) d1 = (Xmax1 - Xmin1) * (Xmax1 - Xmin1) + (Ymax1 - Ymin1) * ( Ymax1 - Ymin1) + (Zmax1 - Zmin1) * (Zmax1 - Zmin1) if int(str(debug)[len(str(debug)) - 1]) == 1: print "dd32 some file's fingerprint = ", d1 studyID = salome.myStudy._get_StudyId() salome.sg.updateObjBrowser(salome.myStudy._get_StudyId()) # now it is visible in the obj browser # found where: site:docs.salome-platform.org latest geompy_doc Packages ExtractShapes #http://docs.salome-platform.org/7/gui/GEOM/geompy_doc/group__l4__decompose.html #def and example FACE = geompy.ExtractShapes(Shape1, geompy.ShapeType["FACE"], True) #SubFaceList = geompy.SubShapeAll(Shape1, geompy.ShapeType["FACE"]) #len(SubFaceList) #len(FACE) listSubShapeIDs = geompy.SubShapeAllIDs(Shape1, geompy.ShapeType["FACE"]) nf = len(listSubShapeIDs) print "number of faces " + str(nf) #[2, 12, 19] # create a group from the faces of the box #solution of the puzzle: linguistic evolution: a group is a face. GROUP = [ geompy.CreateGroup(Shape1, geompy.ShapeType["FACE"]) for Face in FACE ] print "number of Groups " + str(len(GROUP)) #create 1 dir for each of those faces aka groups for i in range(0, nf): print listSubShapeIDs[i] geompy.UnionIDs(GROUP[i], [listSubShapeIDs[i]]) #finally represent all in object browser geompy.addToStudy(Shape1, 'Shape1') for i in range(0, nf): geompy.addToStudyInFather( Shape1, GROUP[i], 'Group' + str(nf) + '_' + str(listSubShapeIDs[i])) if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(salome.myStudy._get_StudyId()) if int(str(debug)[len(str(debug)) - 1]) == 1: displaysalomeplease(i5=10110) Pi.brepgroupobj = GROUP
def __init__(self, name, sections, folder=False, closed=True, minBSplineDegree=2, maxBSplineDegree=5, approximation=True): self.name, self.sections = name, sections self.edges = [] self.shells = [] self.locations = [] self.study = salome.myStudyManager.GetStudyByName(salome.myStudyManager.GetOpenStudies()[0]) self.geompy = geomBuilder.New(self.study) if folder: self.folder = self.geompy.NewFolder('shell_' + name) else: self.folder = None theMinDeg = minBSplineDegree theMaxDeg = maxBSplineDegree theTol2D = 1.E-5 theTol3D = 1.E-5 theNbIter = 100 theMethod = GEOM.FOM_Default isApprox = approximation sewing_precision = 1.E-4 for section in self.sections: self.edges.append(section.bases['edge']) self.shells.append(section.bases['shell']) self.locations.append(section.location) self.compound = self.geompy.MakeCompound(self.edges) self.face = self.geompy.MakeFilling(self.compound, theMinDeg, theMaxDeg, theTol2D, theTol3D, theNbIter, theMethod, isApprox) if closed: sewing = self.geompy.MakeSewing([self.face, self.sections[0].bases['shell'], self.sections[-1].bases['shell']], sewing_precision) self.geom = self.geompy.MakeShell([sewing]) else: self.geom = self.geompy.MakeShell([self.face]) self.geompy.addToStudy(self.geom, self.name) self.geompy.addToStudy(self.compound, self.name + '_sections') if self.folder: self.geompy.PutToFolder(self.geom, self.folder) self.geompy.PutToFolder(self.compound, self.folder) salome.sg.updateObjBrowser(True)
def __init__(self, name, solid, folder=False): self.name = name self.geom = solid self.study = salome.myStudyManager.GetStudyByName(salome.myStudyManager.GetOpenStudies()[0]) self.geompy = geomBuilder.New(self.study) if folder: self.folder = self.geompy.NewFolder('solid_' + name) else: self.folder = None self.geompy.addToStudy(self.geom, self.name) if self.folder: self.geompy.PutToFolder(self.geom, self.folder) salome.sg.updateObjBrowser(True)
def __init__(self, **kwargs): self.sections = {} self.shells = {} self.solids = {} if salome.myStudyManager.GetOpenStudies(): study = salome.myStudyManager.GetStudyByName(salome.myStudyManager.GetOpenStudies()[0]) salome.myStudyManager.Close(study) self.study = salome.myStudyManager.NewStudy('study') self.geompy = geomBuilder.New(self.study) self.geompy.addToStudyAuto(0) O = self.geompy.MakeVertex(0, 0, 0) OX = self.geompy.MakeVectorDXDYDZ(1, 0, 0) OY = self.geompy.MakeVectorDXDYDZ(0, 1, 0) OZ = self.geompy.MakeVectorDXDYDZ(0, 0, 1)
def trihedron(context): import GEOM from salome.geom import geomBuilder # Intialize the geompy factory with the active study activeStudy = context.study geompy = geomBuilder.New(activeStudy) # Create the objects Vx = geompy.MakeVectorDXDYDZ(10, 0, 0) Vy = geompy.MakeVectorDXDYDZ(0, 10, 0) Vz = geompy.MakeVectorDXDYDZ(0, 0, 10) origin = geompy.MakeVertex(0, 0, 0) # Register the objects in the active study geompy.addToStudy( Vx, "Vx" ) geompy.addToStudy( Vy, "Vy" ) geompy.addToStudy( Vz, "Vz" ) geompy.addToStudy( origin, "origin" )
def __init__(self, name, origin, OX_LCS=None, OY_LCS=None, folder=True): self.name = name self.origin = list(origin) self.bases = {} self.study = salome.myStudyManager.GetStudyByName(salome.myStudyManager.GetOpenStudies()[0]) self.geompy = geomBuilder.New(self.study) if folder: self.folder = self.geompy.NewFolder('section_' + name) else: self.folder = None try: self.OX_LCS = list(OX_LCS) except: self.OX_LCS = [1., 0., 0.] try: self.OY_LCS = list(OY_LCS) except: self.OY_LCS = [0., 1., 0.] # Create a vertex in the origin of the LCS self.location = self.geompy.MakeVertex(*tuple(self.origin)) self.geompy.addToStudy(self.location, self.name + '_origin') if self.folder: self.geompy.PutToFolder(self.location, self.folder) # Create LCS for the section self.LCS = self.geompy.MakeMarker(*tuple(self.origin + self.OX_LCS + self.OY_LCS)) self._obtain_rotation_matrix_LCS() self.geompy.addToStudy(self.LCS, self.name + '_LCS') if self.folder: self.geompy.PutToFolder(self.LCS, self.folder) salome.sg.updateObjBrowser(True)
from salome.smesh import smeshBuilder from numpy import genfromtxt def resize_list(l, size): l += [0] * (max(0, size - len(l))) #preset for size of a mesh SIZE_X = 100. SIZE_Y = 50. for j in range(10000): salome.salome_init() geompy = geomBuilder.New() smesh = smeshBuilder.New() # base box pnt1 = geompy.MakeVertex(0.0, 0.0, 0.0) pnt2 = geompy.MakeVertex(SIZE_X, 0.0, 0.0) pnt3 = geompy.MakeVertex(SIZE_X, SIZE_Y, 0.0) pnt4 = geompy.MakeVertex(0.0, SIZE_Y, 0) pnt5 = geompy.MakeVertex(0.0, 0.0, 50.0) pnt6 = geompy.MakeVertex(0.0, 0.0, -50.0) v1 = geompy.MakeVector(pnt5, pnt6) geompy.addToStudy(pnt1, "pnt1") geompy.addToStudy(pnt2, "pnt2")
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 writeMesh(name,couche,position,the_center,tolerance,direction=0): geompy = geomBuilder.New(theStudy) O = geompy.MakeVertex(0, 0, 0) OX = geompy.MakeVectorDXDYDZ(1, 0, 0) OY = geompy.MakeVectorDXDYDZ(0, 1, 0) OZ = geompy.MakeVectorDXDYDZ(0, 0, 1) Lcordon = 3. LZat = 10. LSub = 30. ESub = 20. Passe = [1,2] if direction == 1: Passe=[2,3] poSects= [-10.,0.,position,position+10.,90.,100.] Sommets=[] for sect in poSects: Sommets.append(geompy.MakeVertex(0, sect, 0)) # Sommet_1 Sommets.append(geompy.MakeVertex(Lcordon, sect, 0)) # Sommet_2 Sommets.append(geompy.MakeVertex(LZat, sect, 0)) # Sommet_3 Sommets.append(geompy.MakeVertex(LSub, sect, 0)) # Sommet_4 Sommets.append(geompy.MakeVertex(0, sect, -Lcordon)) # Sommet_5 Sommets.append(geompy.MakeVertex(Lcordon, sect, -Lcordon)) # Sommet_6 Sommets.append(geompy.MakeVertex(0, sect, -LZat)) # Sommet_7 Sommets.append(geompy.MakeVertex(LZat, sect, -LZat)) # Sommet_8 Sommets.append(geompy.MakeVertex(0, sect, -ESub)) # Sommet_9 Sommets.append(geompy.MakeVertex(LSub, sect, -ESub)) # Sommet_10 Sommets.append(geompy.MakeVertex(0, sect,Lcordon)) # Sommet_11 Sommets.append(geompy.MakeVertex(Lcordon, sect,Lcordon)) # Sommet_12 nbParSect = 12 Lignes=[] print '----Construction des lignes des sections' for i,sect in enumerate(poSects): Lignes.append(geompy.MakeLineTwoPnt(Sommets[0+i*nbParSect], Sommets[1+i*nbParSect])) # Ligne_1 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[1+i*nbParSect], Sommets[2+i*nbParSect])) # Ligne_2 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[2+i*nbParSect], Sommets[3+i*nbParSect])) # Ligne_3 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[3+i*nbParSect], Sommets[9+i*nbParSect])) # Ligne_4 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[9+i*nbParSect], Sommets[8+i*nbParSect])) # Ligne_5 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[8+i*nbParSect], Sommets[6+i*nbParSect])) # Ligne_6 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[6+i*nbParSect], Sommets[4+i*nbParSect])) # Ligne_7 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[4+i*nbParSect], Sommets[0+i*nbParSect])) # Ligne_8 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[5+i*nbParSect], Sommets[4+i*nbParSect])) # Ligne_9 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[5+i*nbParSect], Sommets[1+i*nbParSect])) # Ligne_10 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[5+i*nbParSect], Sommets[7+i*nbParSect])) # Ligne_11 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[7+i*nbParSect], Sommets[9+i*nbParSect])) # Ligne_12 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[7+i*nbParSect], Sommets[6+i*nbParSect])) # Ligne_13 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[7+i*nbParSect], Sommets[2+i*nbParSect])) # Ligne_14 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[0+i*nbParSect], Sommets[10+i*nbParSect])) # Ligne_15 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[10+i*nbParSect], Sommets[11+i*nbParSect]))# Ligne_16 = Lignes.append(geompy.MakeLineTwoPnt(Sommets[1+i*nbParSect], Sommets[11+i*nbParSect])) # Ligne_17 = print '----Construction des faces des sections' Faces=[] numFacesSectDeb=[0] for i,sect in enumerate(poSects): Faces.append(geompy.MakeFaceWires([Lignes[0+i*17], Lignes[7+i*17], Lignes[8+i*17], Lignes[9+i*17]], 1)) # Face_1 = Faces.append(geompy.MakeFaceWires([Lignes[1+i*17], Lignes[9+i*17], Lignes[10+i*17], Lignes[13+i*17]], 1)) # Face_2 = Faces.append(geompy.MakeFaceWires([Lignes[6+i*17], Lignes[8+i*17], Lignes[10+i*17], Lignes[12+i*17]], 1)) # Face_3 = Faces.append(geompy.MakeFaceWires([Lignes[2+i*17], Lignes[3+i*17], Lignes[11+i*17], Lignes[13+i*17]], 1)) # Face_4 = Faces.append(geompy.MakeFaceWires([Lignes[4+i*17], Lignes[5+i*17], Lignes[11+i*17], Lignes[12+i*17]], 1)) # Face_5 = Faces.append(geompy.MakeFaceWires([Lignes[0+i*17], Lignes[16+i*17], Lignes[15+i*17], Lignes[14+i*17]], 1)) # Face_6 = numFacesSectDeb.append(len(Faces)) numLigneBase = len(Lignes) print '----------------Nombre de Lignes de base:',numLigneBase,' nombre de ligne par section:',numLigneBase/len(poSects) numFaceBase = len(Faces) print '----------------Nombre de Faces de base:',numFaceBase,' nombre de face par section:',numFaceBase/len(poSects) print '----Construction des lignes liant les sections' for i in range(len(poSects)-1): for j in range(nbParSect): Lignes.append(geompy.MakeLineTwoPnt(Sommets[j+i*nbParSect],Sommets[j+(i+1)*nbParSect])) #print 'Nombre de Lignes:',len(Lignes) numFacesJoint=[len(Faces)] print '----Construction des faces liant les sections' for i in range(len(poSects)-1): Faces.append(geompy.MakeFaceWires([Lignes[0+i*17], Lignes[17+i*17], Lignes[numLigneBase+i*nbParSect], Lignes[numLigneBase+1+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[1+i*17], Lignes[18+i*17], Lignes[numLigneBase+1+i*nbParSect], Lignes[numLigneBase+2+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[2+i*17], Lignes[19+i*17], Lignes[numLigneBase+2+i*nbParSect], Lignes[numLigneBase+3+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[3+i*17], Lignes[20+i*17], Lignes[numLigneBase+3+i*nbParSect], Lignes[numLigneBase+9+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[4+i*17], Lignes[21+i*17], Lignes[numLigneBase+8+i*nbParSect], Lignes[numLigneBase+9+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[5+i*17], Lignes[22+i*17], Lignes[numLigneBase+6+i*nbParSect], Lignes[numLigneBase+8+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[6+i*17], Lignes[23+i*17], Lignes[numLigneBase+4+i*nbParSect], Lignes[numLigneBase+6+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[7+i*17], Lignes[24+i*17], Lignes[numLigneBase+i*nbParSect], Lignes[numLigneBase+4+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[9+i*17], Lignes[26+i*17], Lignes[numLigneBase+1+i*nbParSect], Lignes[numLigneBase+5+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[10+i*17], Lignes[27+i*17], Lignes[numLigneBase+5+i*nbParSect], Lignes[numLigneBase+7+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[12+i*17], Lignes[29+i*17], Lignes[numLigneBase+6+i*nbParSect], Lignes[numLigneBase+7+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[11+i*17], Lignes[28+i*17], Lignes[numLigneBase+7+i*nbParSect], Lignes[numLigneBase+9+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[13+i*17], Lignes[30+i*17], Lignes[numLigneBase+2+i*nbParSect], Lignes[numLigneBase+7+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[8+i*17] , Lignes[25+i*17], Lignes[numLigneBase+4+i*nbParSect], Lignes[numLigneBase+5+i*nbParSect]], 1)) if (i in Passe): Faces.append(geompy.MakeFaceWires([Lignes[14+i*17] , Lignes[31+i*17], Lignes[numLigneBase+i*nbParSect], Lignes[numLigneBase+10+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[15+i*17] , Lignes[32+i*17], Lignes[numLigneBase+10+i*nbParSect], Lignes[numLigneBase+11+i*nbParSect]], 1)) Faces.append(geompy.MakeFaceWires([Lignes[16+i*17] , Lignes[33+i*17], Lignes[numLigneBase+1+i*nbParSect], Lignes[numLigneBase+11+i*nbParSect]], 1)) numFacesJoint.append(len(Faces)) numLigne = len(Lignes) print '----------------Nombre de Lignes:',numLigne,' nombre de ligne par section:',numLigneBase/len(poSects) numFace = len(Faces) print '----------------Nombre de Faces:',numFace,' nombre de face par section:',numFaceBase/len(poSects) print numFacesSectDeb,numFacesJoint Coques=[] print for i in range(len(poSects)-1): #print [0+numFacesSectDeb[i], 6+numFacesSectDeb[i], numFacesJoint[i], 7+numFacesJoint[i], 8+numFacesJoint[i],13+numFacesJoint[i]] Coques.append(geompy.MakeShell([Faces[0+numFacesSectDeb[i]], Faces[6+numFacesSectDeb[i]],Faces[numFacesJoint[i]], Faces[7+numFacesJoint[i]], Faces[8+numFacesJoint[i]],Faces[13+numFacesJoint[i]]])) Coques.append(geompy.MakeShell([Faces[1+numFacesSectDeb[i]], Faces[7+numFacesSectDeb[i]],Faces[1+numFacesJoint[i]], Faces[8+numFacesJoint[i]], Faces[9+numFacesJoint[i]],Faces[12+numFacesJoint[i]]])) Coques.append(geompy.MakeShell([Faces[2+numFacesSectDeb[i]], Faces[8+numFacesSectDeb[i]],Faces[6+numFacesJoint[i]], Faces[9+numFacesJoint[i]], Faces[10+numFacesJoint[i]],Faces[13+numFacesJoint[i]]])) Coques.append(geompy.MakeShell([Faces[3+numFacesSectDeb[i]], Faces[9+numFacesSectDeb[i]],Faces[2+numFacesJoint[i]], Faces[3+numFacesJoint[i]], Faces[11+numFacesJoint[i]],Faces[12+numFacesJoint[i]]])) Coques.append(geompy.MakeShell([Faces[4+numFacesSectDeb[i]], Faces[10+numFacesSectDeb[i]],Faces[11+numFacesJoint[i]], Faces[10+numFacesJoint[i]],Faces[4+numFacesJoint[i]], Faces[5+numFacesJoint[i]]])) if (i in Passe): Coques.append(geompy.MakeShell([Faces[5+numFacesSectDeb[i]], Faces[11+numFacesSectDeb[i]], Faces[0+numFacesJoint[i]], Faces[14+numFacesJoint[i]], Faces[15+numFacesJoint[i]], Faces[16+numFacesJoint[i]]])) Solides=[] for i,coque in enumerate(Coques): solide = geompy.MakeSolid([coque]) Solides.append(solide) Eprouv = geompy.MakeCompound(Solides) Solides = geompy.ExtractShapes(Eprouv, geompy.ShapeType["SOLID"], True) GLS=[] GSS=[] for i,sol in enumerate(Solides): localAretes = geompy.ExtractShapes(sol, geompy.ShapeType["EDGE"], True) longIDS=[] sectIDS=[] for arete in localAretes: angleY=geompy.GetAngle(arete,OY) iidd = geompy.GetSubShapeID(sol,arete) if angleY==0: longIDS.append(iidd) else: sectIDS.append(iidd) GroupeL = geompy.CreateGroup(sol, geompy.ShapeType["EDGE"]) GroupeS = geompy.CreateGroup(sol, geompy.ShapeType["EDGE"]) geompy.UnionIDs(GroupeL, longIDS) geompy.UnionIDs(GroupeS,sectIDS) GLS.append(GroupeL) GSS.append(GroupeS) ### ### SMESH component ### print '---Maillage' import SMESH, SALOMEDS from salome.smesh import smeshBuilder from salome.StdMeshers import StdMeshersBuilder smesh = smeshBuilder.New(theStudy) Maillage_1 = smesh.Mesh(Eprouv) Regular_1D = Maillage_1.Segment() Local_Length_1 = Regular_1D.LocalLength(0.5,None,1e-07) Quadrangle_2D = Maillage_1.Quadrangle(algo=smeshBuilder.QUADRANGLE) Quadrangle_Parameters_1 = Quadrangle_2D.QuadrangleParameters(StdMeshersBuilder.QUAD_QUADRANGLE_PREF,-1,[],[]) Hexa_3D = Maillage_1.Hexahedron(algo=smeshBuilder.Hexa) SSML=[] SSMS=[] # for gl in GLS: # Regular_1D_1 = Maillage_1.Segment(geom=gl) # Nb_Segments_1 = Regular_1D_1.NumberOfSegments(20) # SSML.append( Regular_1D_1.GetSubMesh()) for gs in GSS: Regular_1D_2 = Maillage_1.Segment(geom=gs) Nb_Segments_2 = Regular_1D_2.NumberOfSegments(8) SSMS.append(Regular_1D_2.GetSubMesh()) isDone = Maillage_1.Compute() coincident_nodes_on_part = Maillage_1.FindCoincidentNodesOnPart( Maillage_1, 1e-05, [], 0 ) Maillage_1.MergeNodes(coincident_nodes_on_part) tol2 = tolerance**2 node_inside_ids = [] for node_id in Maillage_1.GetNodesId(): x, y, z = Maillage_1.GetNodeXYZ(node_id) d=0. #d = (x - the_center[0])**2 d += (y - the_center[1])**2 d += (z - the_center[2])**2 if d < tol2: node_inside_ids.append(node_id) grp = Maillage_1.CreateEmptyGroup(SMESH.NODE, "inside") grp.Add(node_inside_ids) print '---Ecriture du fichier MED' Maillage_1.ExportMED(name, 0, SMESH.MED_V2_2, 1, None ,1)
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_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生成失败")
def mesh2bnd_n_unv(Pi, debug=1000140, maxmbsteps=1300): import SMESH, SALOMEDS #debug=last index 1:activate vtkviewr fitall #debug=digit 2:4 put off debug noise; level edges, next 5 #debug=digit 3:1 delete former objects geompy = geomBuilder.New(salome.myStudy) ##### #interfaces boundaries VP = (geompy.SubShapeAll(Pi.brepshapeobj, geompy.ShapeType["VERTEX"])) #shape objects #testfunction for visualisation of vertex sequence ## mode = "test_manual" #mode="production_manual" #mode="if_man_prod" if mode == "test_manual": Vp_mb1 = [8 - 1, 7 - 1, 8 - 1, 6 - 1] ## #Vp_mb1=[8,7,8,6] #is: line between Vertice 8,7 and between 8,6 Vp_mb2 = [1 - 1, 2 - 1] # cold? new_group2 = [None] * len(Vp_mb1 + Vp_mb2) print "test_manual" VpL = [Vp_mb1, Vp_mb2] else: VpL = [Pi.Vp_mb1, Pi.Vp_mb2] # bggroup1L = [] mesh = Pi.meshobj ## dim = SMESH.BND_1DFROM2D Pi.mbedges = [] glue_edges = [] glue_elements = [] glue_points = [] i6 = 0 for Vp_mb in VpL: #boundary by boundaryy i6 = i6 + 1 for i in range(0, len(Vp_mb), 2): #boundary line byboundary line groupName = 'Group_bd' + ''.join(str(Vp_mb[i]) + str(Vp_mb[i + 1])) nb2, new_mesh2, new_group2[i] = mesh.MakeBoundaryElements( dim, groupName) # new_group2[i]:all mesh edge boundary elements of mesh # but as well create new entry in obj browser #nb2, new_mesh2? salome.sg.updateObjBrowser(salome.myStudy._get_StudyId()) #print new_group2[i].GetListOfID() #print "i6:" +str(i6) debug1 = int(str(debug)[len(str(debug)) - 2]) #4 #if i6==2:debug1=5 mbresult = edge2mbnodes(Pi, Vp_mb[i], Vp_mb[i + 1], VP, mesh, new_group2[i], maxmbsteps, debug1, complaint='Yes or no, please!') #return mbresult=mesh boundary elements of line: mesh edge elements of it unv reqires #max Length 1300 ##debug off, >100 nodes long,list of vertices of shape, mesh, list of mesh's boundary nodes ##nbDel = new_group2[i].Remove( new_group2[i].GetListOfID() ) ##nbAdd = new_group2[i].Add( mbresult[1] ) ##delete groups with same name for group, name in zip(mesh.GetGroups(), mesh.GetGroupNames()): if name == groupName: mesh.RemoveGroup(group) #clean object brouwer of single line entry no needed for i1 in mbresult[1]: glue_edges.append(i1) for i1 in mbresult[0]: glue_points.append(i1) for i1 in mbresult[2]: glue_elements.append(i1) #hold lines of same boundary in second part of array #glue groups togehter groupName = 'Group_bd' + str(i6) #final boject browsers entries of mesh boundary "group" with found edge as required for export to unv for group, name in zip(mesh.GetGroups(), mesh.GetGroupNames()): if name == groupName: mesh.RemoveGroup(group) nb2, new_mesh2, bggroup1 = mesh.MakeBoundaryElements(dim, groupName) nbDel = bggroup1.Remove(bggroup1.GetListOfID()) nbAdd = bggroup1.Add(glue_edges) # salome.sg.updateObjBrowser(salome.myStudy._get_StudyId()) displaysalomeplease(11021, 4, groupName) bggroup1L.append(bggroup1) Pi.mbedges.append([glue_edges, glue_elements, glue_points]) glue_edges = [] glue_elements = [] glue_points = [] # Boundary part end ##Expor mesh.ExportUNV(Pi.unvfile) if int(str(debug)[len(str(debug)) - 1]) == 1: displaysalomeplease(11111)
def edge2mbnodes(Pi, VPi1, VPi2, VP, Mesh_1, new_group2, i5end=100, debug=4, complaint='Yes or no, please!'): geompy = geomBuilder.New(salome.myStudy) mb11point = list(geompy.PointCoordinates(VP[VPi1])) mb12point = list(geompy.PointCoordinates(VP[VPi2])) if debug != 4: print "mb11point mb12point " + str([mb11point, mb12point ]) # + mb12node mb11node # if debug != 4: print "he" + str( new_group2.GetNodeIDs() ) # #debug off, >100 nodes long,list of vertices of shape, mesh, list of mesh's boundary nodes mb11node = 0 mb12node = 0 for i in new_group2.GetNodeIDs(): a = Mesh_1.GetNodeXYZ(i) if a == mb12point: mb12node = i if a == mb11point: mb11node = i #boundary points as nodes if debug != 4: print "mb12node mb11node " + str([mb12node, mb11node ]) # + mb12node mb11node # #xy repres of Edges Vx = [list(geompy.PointCoordinates(i)) for i in VP] # #Vertexes indices as boundary node list Vnodes = [ i for i1 in Vx for i in new_group2.GetNodeIDs() if i1 == Mesh_1.GetNodeXYZ(i) ] #[4, 3, 2, 1, 6, 5, 8, 7] # # # on the neighbour suche # Element of mbpoint1 mesh = Mesh_1 if debug != 4: mesh.FindElementsByPoint(mb12point[0], mb12point[1], mb12point[2]) #[119, 134, 920] #[133, 134, 842, 860, 920, 945] neughbour does not show up even # lets focus on element 920 #Mesh_1.GetElemNodes(920) #[8, 119, 133] # # foundpoints0 = [mb12node] foundpoints = foundpoints0 if debug != 4: len(foundpoints) d = [] d0 = [] resultedge = [] * 2 resultedgeL = [] secondbetnode = -1 lastsecondbetnode = -1 i5 = 0 say = "ok" # vom ersten boundary eckpunkt, die anliegenden Elemente:b a = Mesh_1.GetNodeXYZ(mb12node) b = mesh.FindElementsByPoint(a[0], a[1], a[2]) if debug != 4: print "-ALL_adjacent_Elem_at_start" + str( b ) #+"-c1 bound " + str(c1)+"-c " + str(c) + "-d nicht schon " + str(d) while list(set(resultedge) & set(foundpoints)) == [] and i5 < i5end: i5 = i5 + 1 for i in b: #extract neighbor node on boundary line part 1 if len(Mesh_1.GetElemNodes(i)) > 2: for i1 in Mesh_1.GetElemNodes(i): if i1 == foundpoints[len(foundpoints) - 1]: d0 = list( set(set(Mesh_1.GetElemNodes(i))) & set(new_group2.GetNodeIDs()) - set(foundpoints) - set([secondbetnode]) - set([lastsecondbetnode]) - set(d)) if debug != 4: print "-d EleNodes /foundnotes " + str( d0 ) # + "-next points " + str(i1) +"-c1 bound " + str(c1)+"-c " + str(c) + "-d nicht schon " + str(d) if d0 != []: d.append(d0[0]) if len(d0) == 2: d.append(d0[1]) if len(d0) == 3: print "pointed stick??" if d0 != []: break if debug != 4: print ":for adjEle_b(i) " + str(i) + ": these nodes " + str( Mesh_1.GetElemNodes(i)) #d.append(d0[0]) # in the beginning we wait for two #if d!=[]: break #buggy? # if len( d ) > 1 and i5 == 1: #part 2, in the beginning we got two bet, chose one # Debug wait boundary could get loss in the interior at subshape contracts right: more then one boundary node per element:add vertex only e = list(set(Vnodes) & set(d)) if e != []: foundpoints.append(d[1]) else: foundpoints.append(d[1]) secondbetnode = d[0] if len(d) > 1 and i5 != 1: #if more then one node add the Vnode f = list(set(Vnodes) & set(d)) ##print "the two nodes:" + str(d) + "but:" + str(f) + "is vertex" if f != []: foundpoints.append(f[0]) # if len(d) == 1: foundpoints.append(d[0]) #put best neighbour bet to the collection # d = [] d0 = [] #and go for searching the next a = Mesh_1.GetNodeXYZ(foundpoints[len(foundpoints) - 1]) b = mesh.FindElementsByPoint(a[0], a[1], a[2]) if debug != 4: print "-new found points:" + str( foundpoints) + "new adjElem:" + str(b) + "2.betnode:" + str( secondbetnode) # #at endnode: out with result, at vertex: out with second bet, new collection list if list(set(Vnodes) & set([foundpoints[len(foundpoints) - 1]])) != []: if foundpoints[len(foundpoints) - 1] == mb11node: resultedge = foundpoints #resultedge.append(foundpoints) if debug != 4: print "result case" else: lastsecondbetnode = foundpoints[1] foundpoints = [mb12node, secondbetnode] secondbetnode = -1 if debug != 4: print "second bet case" + "-new found points:" + str( foundpoints) else: if debug != 4: print "added node no vertex" if debug != 4: print "Durchlauf" + str(i5) if debug != 4: print "Durchlauf" + str(i5) resultedgeL.append(foundpoints) #print resultedgeL resultedgeL.append([ mesh.FindElementByNodes([foundpoints[i], foundpoints[i + 1]]) for i in range(0, len(foundpoints) - 1) ]) #print resultedgeL #note: afterwards it came out that everything could have been done easier with better APIs, ppssibly everything needs to be rewritten due to performances probs # #find the elements atjacent to the boundary line and add it to return matrix, yet. foundmbelem = [] for i in range(0, len(foundpoints) - 1): #print "i ",i," foundpoints[i] ", foundpoints[i] pi2 = Pi.meshobj.GetNodeXYZ(foundpoints[i]) #print "pi2 ",pi2 ei3L = Pi.meshobj.FindElementsByPoint(pi2[0], pi2[1], pi2[2]) #print "GetElemNodes",ei3L #element index 3 is a list of adjacent element to boundary point for ei4 in ei3L: ei4L = Pi.meshobj.GetElemNodes(ei4) #print "FindElementsByPoint",ei4 #print "GetElemNodes",ei4L if len(ei4L) > 2 and set(ei4L) >= set( [foundpoints[i], foundpoints[i + 1]]): foundmbelem.append(ei4) #print foundmbelem resultedgeL.append(foundmbelem) return resultedgeL
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
import salome import GEOM import math import SMESH from salome.smesh import smeshBuilder import SALOMEDS import StdMeshers import NETGENPlugin salome.salome_init() study = salome.myStudy studyId = salome.myStudyId from salome.geom import geomBuilder geompy = geomBuilder.New(salome.myStudy) smesh = smeshBuilder.New(salome.myStudy) from salome.geom import geomtools geompy = geomtools.getGeompy(studyId) from salome.kernel.studyedit import getStudyEditor studyEditor = getStudyEditor(studyId) gst = geomtools.GeomStudyTools(studyEditor) gg = salome.ImportComponentGUI("GEOM")
Vert_array =[0]; number_vertex = len(Vert_array) Vert = [] VolumeObject1 = [] ContactObject1 = [] VolumeObject2 = [] ContactObject2 = [] print " DBS_lead's Geometry buid\n" ######################################### end of extra code 1 ######################################## ###################################################################################################### from salome.geom import geomBuilder import math import SALOMEDS geompy = geomBuilder.New(theStudy) O = geompy.MakeVertex(0, 0, 0) OX = geompy.MakeVectorDXDYDZ(1, 0, 0) OY = geompy.MakeVectorDXDYDZ(0, 1, 0) OZ = geompy.MakeVectorDXDYDZ(0, 0, 1) Circle_1 = geompy.MakeCircle(O, OZ, 0.635) Contact_1 = geompy.MakePrismVecH(Circle_1, OZ, 1.5) geompy.TranslateDXDYDZ(Contact_1, 0, 0, 0.865) Contact_2 = geompy.MakeTranslation(Contact_1, 0, 0, 2) Contact_3 = geompy.MakeTranslation(Contact_1, 0, 0, 4) Contact_4 = geompy.MakeTranslation(Contact_1, 0, 0, 6) Cylinder_1 = geompy.MakeCylinderRH(0.635, 149.365) Sphere_1 = geompy.MakeSphereR(0.635) Fuse_1 = geompy.MakeFuseList([Cylinder_1, Sphere_1], True, True) Cylinder_2 = geompy.MakeCylinderRH(encap_thickness+0.635, 149.365)
def extractFeatureEdges(body, minFeatureAngle=5): ''' Find all feature edges on the supplied body and return them as a list of edge ids. body - A Salome solid, compound, shell or face object to find all feature edges on. minFeatureAngle - the angle (in degrees) between adjacent surfaces above which the edge will be considered a feature angle. ''' import salome salome.salome_init() import GEOM from salome.geom import geomBuilder geompy = geomBuilder.New(salome.myStudy) # Check the body type if not (body.GetShapeType() in [GEOM.SHELL, GEOM.SOLID, GEOM.FACE, GEOM.COMPOUND]): raise RuntimeError('Supplied object is not a solid, shell or face.') print 'Extracting edges of %s with feature angle > %g.' % (body.GetName(), minFeatureAngle) # Extract basic info faces = geompy.SubShapeAll(body, geompy.ShapeType["FACE"]) curves = geompy.SubShapeAll(body, geompy.ShapeType["EDGE"]) points = geompy.SubShapeAll(body, geompy.ShapeType["VERTEX"]) faceIds = geompy.GetSubShapesIDs(body, faces) curveIds = geompy.GetSubShapesIDs(body, curves) nodeIds = geompy.GetSubShapesIDs(body, points) maxFaceId = max(faceIds) maxCurveId = max(curveIds) maxNodeId = max(nodeIds) # Reverse mapping from curve id to local curve arrays faceMap = [-1 for i in xrange(maxFaceId + 1)] for localId, id in enumerate(faceIds): faceMap[id] = localId curveMap = [-1 for i in xrange(maxCurveId + 1)] for localId, id in enumerate(curveIds): curveMap[id] = localId nodeMap = [-1 for i in xrange(maxNodeId + 1)] for localId, id in enumerate(nodeIds): nodeMap[id] = localId # Get curves on each face faceCurveIds = [[ curveMap[id] for id in geompy.GetSubShapesIDs( body, geompy.SubShapeAll(face, geompy.ShapeType["EDGE"])) ] for face in faces] # Get faces attached to each curve curveFaceIds = [[] for id in curveIds] for faceI, ids in enumerate(faceCurveIds): for id in ids: curveFaceIds[id].append(faceI) # Now that we have the connectivity for curves and faces find the # feature edges featureEdgeIds = [] for curveId, curve, adjFaceIds in zip(curveIds, curves, curveFaceIds): if len(adjFaceIds) == 2: # Curve with 2 adjacent faces - Test feature angle # Determine break angle at each curve # If greater than the feature edge angle, add the curve to group featureEdges face1 = faces[adjFaceIds[0]] face2 = faces[adjFaceIds[1]] point = geompy.GetFirstVertex(curve) # Test at the first vertex n1 = geompy.GetNormal(face1, point) n2 = geompy.GetNormal(face2, point) angle = geompy.GetAngle(n1, n2) if angle > minFeatureAngle: featureEdgeIds.append(curveId) elif len(adjFaceIds) == 1: # Curve on standalone face - Add by default featureEdgeIds.append(curveId) elif len(adjFaceIds) == 0: # Standalone curve - Ignore None else: raise RuntimeError( 'Curve found sharing %d faces. This is unexpected for fully enclosed bodies.' % len(adjFaceIds)) # Done print "%d feature edges found" % len(featureEdgeIds) return featureEdgeIds