def prepare_data_grid(grid={}): # Display nodes and elements counts model = apex.currentModel() meshItem = [] grid['meshes'] = meshItem for Part in model.getParts(True): if Part.getVisibility(): for Mesh in Part.getMeshes(): print(Mesh) if Mesh.getVisibility(): meshInfo = {} meshItem.append(meshInfo) meshInfo['mesh_name'] = Mesh.getName() meshInfo['parent_name'] = Mesh.getParent().getName() meshInfo['elements_count'] = len(Mesh.getElements()) meshType = "" if type(Mesh) == apex.mesh.SolidMesh: meshType += "Tetra" elif type(Mesh) == apex.mesh.SurfaceMesh: meshType += "Surface" elif type(Mesh) == apex.mesh.HexMesh: meshType += "Hexa" else: meshType = "??" meshInfo['mesh_type'] = meshType return grid
def main(dict={}): #def main(): apex.disableShowOutput() myModel = apex.currentModel() matls = apex.catalog.getMaterials([{"path":myModel.getName()+"/Materials"}]) matlNames = [] for matl in matls: matlType = matl.getMaterialType() if matlType != 0: continue # 0 is isotropic matlNames.append(matl.getName()) if matl.getMaterialType() > 0: continue #print(matl.getElasticModulus()) #print(matl.getDensity()) #print(matl.getPoissonRatio()) if len(matlNames) == 0: matlNames.append("None") ret_dict = {} ret_dict["matlList"] = matlNames return ret_dict
def roundSelection(dict={}): model_1 = apex.currentModel() try: roundRadius = float(dict["roundRadius"]) except: apex.enableShowOutput() print("Invalid radius value!") _target = apex.EntityCollection() for selFace in apex.selection.getCurrentSelection(): for Edge in selFace.getEdges(): _target.append(Edge) try: result = apex.geometry.pushPull( target=_target, method=apex.geometry.PushPullMethod.Fillet, behavior=apex.geometry.PushPullBehavior.FollowShape, removeInnerLoops=False, createBooleanUnion=False, distance=roundRadius, direction=[7.071067811865475e-01, 7.071067811865475e-01, 0.0]) except: apex.enableShowOutput() print("Rounding failed for \n", selFace.getBody().getPathName())
def OrganizeSolids(dict={}): #=================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') try: numOfSolidsChanged = 0 for Part in apex.currentModel().getParts(recursive=True): if len(Part.getSolids()) > 1: for Solid in Part.getSolids()[1:]: if Solid.getVisibility(): if dict["useSolidName"] == 'True': newPart = apex.createPart(name=Solid.getName()) Solid.setParent(newPart) numOfSolidsChanged += 1 if Part.getParent(): newPart.setParent(Part.getParent()) else: newPart = apex.createPart(name=Part.getName()) Solid.setParent(newPart) numOfSolidsChanged += 1 if Part.getParent(): newPart.setParent(Part.getParent()) print("Reorganized {0} solids.".format(numOfSolidsChanged)) except: print("Operation failed or not performed.")
def CreateMeshPartitions(dict={}): # =================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() ## Collect faces to mesh _targetFine = apex.entityCollection() listOfLengths = [] listOfDiameters = [] MeshSize = float(dict["MeshSize"]) try: listOfTrajectories = model_1.getAssembly("Trajectories").getParts(True) listOfAllParts = [] for Part in model_1.getParts(True): if "Trajectories" not in Part.getPath(): listOfAllParts.append(Part) for Part in listOfTrajectories: if 'RefDiam' in Part.getName(): _, Diam = Part.getName().split('_') listOfDiameters.append(float(Diam)) else: if len(Part.getCurves()) > 0: listOfLengths.append(Part.getCurves()[0].getLength()) maxDiameter = max( listOfDiameters) #Getting the max diameter to use as search range ## Getting all faces from all parts that are not under 'Trajectories' facesToMesh = apex.EntityCollection() for Part in listOfAllParts: for Surface in Part.getSurfaces(): for Face in Surface.getFaces(): if Face.getArea() <= (1.1 * 3.14159 * maxDiameter * maxDiameter): facesToMesh.append(Face) apex.mesh.createSurfaceMesh( name="", target=facesToMesh, meshSize=MeshSize, meshType=apex.mesh.SurfaceMeshElementShape.Mixed, meshMethod=apex.mesh.SurfaceMeshMethod.Pave, mappedMeshDominanceLevel=2, elementOrder=apex.mesh.ElementOrder.Linear, meshUsingPrincipalAxes=False, refineMeshUsingCurvature=True, elementGeometryDeviationRatio=0.10, elementMinEdgeLengthRatio=0.50, createFeatureMeshOnFillets=False, createFeatureMeshOnChamfers=False, createFeatureMeshOnWashers=False, createFeatureMeshOnQuadFaces=False) except: print("Meshing failed or not performed.")
def Midsurface(dict={}): #=================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() # =================================================================== ## Extract midsurface for all parts numOfInvisible = 0 numOfFailed = 0 numOfMultiple = 0 numOfCreated = 0 numOfParts = len(model_1.getParts(recursive=True)) for Part in model_1.getParts(recursive=True): if 'Trajectories' not in Part.getPathName(): _target = apex.entityCollection() if Part.getVisibility(): try: listOfSolids = Part.getSolids( ) # Get a list of all solids for a given part for Solid in listOfSolids: # Append this list of solids to the _target variable _target = apex.entityCollection() _target.append(Solid) A_old = apex.catalog.getSectionDictionary() result = apex.geometry.assignConstantThicknessMidSurface( target=_target, autoAssignThickness=True, autoAssignTolerance=5.0e-02) A_new = apex.catalog.getSectionDictionary() new_thickness = { k: A_new[k] for k in set(A_new) - set(A_old) } for key, value in new_thickness.items(): nthickness = value.thickness if len(Part.getSurfaces()) > 1: Part.update(name="{0}_CHECK(multiple)".format( Part.getName())) numOfMultiple += 1 else: for entity in result: #'result' comes from the resulting collection of the midsurface extraction if entity.entityType is apex.EntityType.Surface: CurrPartPath = apex.getPart( entity.getPath()) CurrPartPath.update( name="{0}_{1}mm".format( CurrPartPath.getName(), str(round(float(nthickness), 2)).replace(".", ","))) numOfCreated += 1 except: Part.update( name="{0}_CHECK(failed)".format(Part.getName())) numOfFailed += 1 else: numOfInvisible += 1
def CreateSpotGroup(CSVPath="Path", RefineDiam=8.0): model_1 = apex.currentModel() if "/" in CSVPath: TrajectoryName = CSVPath[CSVPath.rfind("/") + 1:-4] else: TrajectoryName = CSVPath[CSVPath.rfind("\\") + 1:-4] try: TrajAssy = model_1.getAssembly(pathName="Trajectories") except: TrajAssy = model_1.createAssembly(name="Trajectories") WeldPositions = [] ScalingToMM = 1.0 with open(CSVPath, 'r') as CSVFile: for line in CSVFile: if "Length unit:" in line: unit = line.strip().split('[')[-1].replace("]", "") if unit == "mm": ScalingToMM = 1.0 elif unit == "m": ScalingToMM = 1000.0 elif uni == "in": ScalingToMM = 25.40 if ('true' in line) or ('false' in line): WeldPositions.append([ ScalingToMM * float(x) for x in line.strip().split(';')[2:5] ]) for spotPoint in WeldPositions: result = apex.geometry.createSphereByLocationOrientation( name='', description='', radius=RefineDiam / 2.0, origin=apex.Coordinate(spotPoint[0], spotPoint[1], spotPoint[2]), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0)) model_1.getCurrentPart().update(name=TrajectoryName) ans = model_1.getCurrentPart().setParent(parent=TrajAssy) try: if model_1.getAssembly("Trajectories").getPart( name="RefDiam_{0}".format(RefineDiam)): pass else: SpecifiedDiameter = apex.createPart( name="RefDiam_{0}".format(RefineDiam)) SpecifiedDiameter.setParent( model_1.getAssembly("Trajectories")) except: print("Part creation failed!")
def ExportBDF(dict={}): # =================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') # Export mesh to BDF model_1 = apex.currentModel() pathToSave = dict["DirPath"] for Part in model_1.getParts(True): if "=" not in Part.getName(): if Part.getVisibility(): try: Part.exportFEModel( filename=os.path.join( pathToSave, Part.getName().replace(",", ".") + ".bdf"), unitSystem="m-kg-s-N-K", exportWideFormat=False, exportHierarchicalFiles=False, resultOutputType=apex.attribute. NastranResultOutputType.Hdf5, renumberMethod=apex.attribute.ExportRenumberMethod. Internal, apexEngineeringAbstractions=False, ) except: pass for f in os.listdir(pathToSave): if '.bdf' in f: BDFPath = os.path.join(pathToSave, f) newContent = "" print(f) with open(BDFPath, 'r') as oldBDF: for line in oldBDF: line = line.strip() spaceVec = " " if 'CQUAD' in line: line = ' '.join(line.split()) vecStr = line.split() vecStr[2] = '1' finString = "" for elem in vecStr: finString += elem + spaceVec[0:8 - len(elem)] newContent += finString + '\n' elif 'CTRIA' in line: line = ' '.join(line.split()) vecStr = line.split() vecStr[2] = '1' finString = "" for elem in vecStr: finString += elem + spaceVec[0:8 - len(elem)] newContent += finString + '\n' #elif 'PSHELL' in line: # pass else: newContent += line + '\n' with open(BDFPath, 'w') as newBDF: newBDF.write(newContent)
def createAssy(dict={}): apex.disableShowOutput() model_1 = apex.currentModel() if dict["assyName"]: newAssy = model_1.createAssembly(name=dict["assyName"]) else: newAssy = model_1.createAssembly() for selElem in apex.selection.getCurrentSelection(): res = selElem.getParent().setParent(parent=newAssy)
def CountVisibleElements(dict={}): apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() numOfElements = 0 listOfParts = model_1.getParts(True) for Part in listOfParts: if Part.getVisibility(): for Mesh in Part.getMeshes(): numOfElements += len(Mesh.getElements()) print('Elements in all visible meshes: ', numOfElements)
def StiffnessOptimizer(dict={}): #apex.disableShowOutput() model_1 = apex.currentModel() try: maxNumPts = int(dict["MaxNumOfPoints"]) except: apex.enableShowOutput() print( "Need a number for the maximum number of points. Please have the correct input." ) raise dummyMaterial = apex.catalog.createMaterial(name="Steel", description="", color=[64, 254, 250]) dummyMaterial.update(elasticModulus=210.e+9, poissonRatio=0.3, density=7.8e-6) newAssyName = datetime.datetime.now().strftime("Test_%Y.%m.%d_%Hh%Mm%Ss") currAssy = model_1.createAssembly(name=newAssyName) for selPart in apex.selection.getCurrentSelection(): _target = apex.EntityCollection() _target.append(selPart) apex.attribute.assignMaterial(material=dummyMaterial, target=_target) selPart.setParent(currAssy) context_ = currAssy study = apex.getPrimaryStudy() study.createScenarioByModelRep( context=context_, simulationType=apex.studies.SimulationType.NormalModes) study = apex.getPrimaryStudy() currScenario = study.getScenario(name="Mode Scenario " + currAssy.getName()) """ simSetting1 = currScenario.simulationSettings simSetting1.partReduction = False simSetting1.freqRangeLower = 1000. simSetting1.freqRangeUpper = float('NaN') simSetting1.stopCalculation = True simSetting1.maxModes = 10 currScenario.simulationSettings = simSetting1 """ model_1.save() currScenario.execute() executedscenario_1 = scenario1.getLastExecutedScenario()
def ShowNoMeshed(dict={}): #=================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() # =================================================================== for Part in model_1.getParts(recursive=True): if 'Trajectories' not in Part.getPathName(): _target = apex.entityCollection() if Part.getMeshes(): Part.hide() else: Part.show()
def SuppressEdges(dict={}): #=================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() _target = apex.entityCollection() listOfVertices = [] for part in model_1.getParts(True): if part.getVisibility(): if 'Trajectories' not in part.getPath(): for Solid in part.getSolids(): if Solid.getVisibility(): for Vertex in Solid.getVertices(): listOfEdges = [] listOfLengths = [] for Edge in Vertex.getConnectedEdges(): listOfEdges.append(Edge.getId()) listOfLengths.append(Edge.getLength()) if len( listOfEdges ) > 2: # Suppress edges with more than 2 connections at the vertex sortedByNumber = [ int(x) for _, x in sorted( zip(listOfLengths, listOfEdges)) ] _target.append( Solid.getEdge(id=sortedByNumber[0])) """ for surface in part.getSurfaces(): if surface.getVisibility(): #_target.extend(surface.getEdges()) for Vertex in surface.getVertices(): listOfEdges = [] listOfLengths = [] for Edge in Vertex.getConnectedEdges(): listOfEdges.append(Edge.getId()) listOfLengths.append(Edge.getLength()) if len(listOfEdges) > 2: sortedByHeight = [int(x) for _, x in sorted(zip(listOfLengths, listOfEdges))] _target.append(surface.getEdge(id=sortedByHeight[0])) """ result = apex.geometry.suppressOnly(target=_target, maxEdgeAngle=1.745329251994330e-01, maxFaceAngle=8.726646259971650e-02, keepVerticesAtCurvatureChange=False, cleanupTol=1.000000000000000)
def ShowSurfMeshedOnly(dict={}): #=================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() # =================================================================== for Part in model_1.getParts(recursive=True): if 'Trajectories' not in Part.getPathName(): _target = apex.entityCollection() for Mesh in Part.getMeshes(): print(Mesh.entityType) if Mesh.entityType == apex.EntityType.SurfaceMesh: _target.extend(Part) _target.hide()
def CreateMeshNONPartitions(dict={}): #=================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName = r'''mm-kg-s-N''') model_1 = apex.currentModel() try: MeshSize = float(dict["CoarseMeshSize"]) except: MeshSize = float(dict["MeshSize"]) listOfAllParts = [] for Part in model_1.getParts(True): if "Trajectories" not in Part.getPath(): listOfAllParts.append(Part) ## Getting all faces from all parts that are not under 'Trajectories' listOfNonMeshedFaces = apex.EntityCollection() for Part in listOfAllParts: for Surface in Part.getSurfaces(): for Face in Surface.getFaces(): if not Face.getElements(): listOfNonMeshedFaces.append(Face) ## ----------------------------------------------------------------------------------------------------------- ## ----------------------------------------------------------------------------------------------------------- apex.mesh.createSurfaceMesh( name="", target=listOfNonMeshedFaces, meshSize= MeshSize, meshType=apex.mesh.SurfaceMeshElementShape.Mixed, meshMethod=apex.mesh.SurfaceMeshMethod.Pave, mappedMeshDominanceLevel=0, elementOrder=apex.mesh.ElementOrder.Linear, meshUsingPrincipalAxes=False, refineMeshUsingCurvature=True, elementGeometryDeviationRatio=0.10, elementMinEdgeLengthRatio=0.50, createFeatureMeshOnFillets=False, createFeatureMeshOnChamfers=False, createFeatureMeshOnWashers=False, createFeatureMeshOnQuadFaces=False )
def SuppressFeatures(dict={}): #=================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() _target = apex.entityCollection() try: for part in model_1.getParts(True): if 'Trajectories' not in part.getPath(): for surface in part.getSurfaces(): _target.extend(surface.getEdges()) _target.extend(surface.getVertices()) result = apex.geometry.suppressOnly( target=_target, maxEdgeAngle=1.745329251994330e-01, maxFaceAngle=8.726646259971650e-02, keepVerticesAtCurvatureChange=False, cleanupTol=1.000000000000000) except: print("Simplification not performed or failed.")
def SplitByTrajectories(dict={}): apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() try: listOfParts = model_1.getParts(True) _target = apex.entityCollection() _face = apex.entityCollection() for Part in listOfParts: if 'Trajectories' in Part.getPath(): for Solid in Part.getSolids(): _face += Solid.getFaces() else: _target += Part.getSurfaces() apex.geometry.splitOnSurface( target=_target, face=_face, splitBehavior=apex.geometry.GeometrySplitBehavior.Partition) entities_1 = apex.EntityCollection() assembly_1 = model_1.getAssembly(pathName="Trajectories") entities_1.append(assembly_1) entities_1.hide() except: print("Split failed or not performed.")
def buildCrossTension(dict={}): # - Get the data from the dictionary HorizWidth = float(dict["HorizWidth"]) HorizLength = float(dict["HorizLength"]) LowerThick = float(dict["HorizThick"]) VertHeight = float(dict["VertHeight"]) VertLength = float(dict["VertLength"]) UpperThick = float(dict["VertThick"]) spotSize = float(dict["SpotSize"]) ## Define max and min thickness if LowerThick >= UpperThick: maxThick = LowerThick minThick = UpperThick else: maxThick = UpperThick minThick = LowerThick avgThick = (maxThick + minThick) / 2.0 model_1 = apex.currentModel() ParentAssy = model_1.createAssembly(name="CrossTension") Sheet01 = apex.createPart() # - Build the bottom plate result = apex.geometry.createBoxByLocationOrientation( name='Sheet01', description='', length=HorizLength, # Length height=HorizWidth, # Width depth=LowerThick, # Thickness origin=apex.Coordinate(0.0, 0.0, 0.0), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0)) res = Sheet01.setParent(ParentAssy) res = Sheet01.update(name='LowerSheet') # - Build the upper plate Sheet02 = apex.createPart() result = apex.geometry.createBoxByLocationOrientation( name='Sheet02', description='', length=VertHeight, # Length height=VertLength, # Width depth=UpperThick, # Thickness origin=apex.Coordinate(0.0, 0.0, LowerThick), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0)) res = Sheet02.setParent(ParentAssy) res = Sheet02.update(name='UpperSheet') # - Translate sheet _translateSheet = apex.EntityCollection() _translateSheet.append(Sheet02.getSolids()[0]) newEntities = apex.transformTranslate(target=_translateSheet, direction=[1.0, 0.0, 0.0], distance=(HorizLength / 2.0 - VertHeight / 2.0), makeCopy=False) _translateSheet = apex.EntityCollection() _translateSheet.append(Sheet02.getSolids()[0]) newEntities = apex.transformTranslate(target=_translateSheet, direction=[0.0, -1.0, 0.0], distance=(HorizLength / 2.0 - HorizWidth / 2.0), makeCopy=False) # Save joint info for reference JointInfoAssy = model_1.createAssembly("Joint info") res = JointInfoAssy.createPart(name="Sheet 01 = {0}mm".format(LowerThick)) res = JointInfoAssy.createPart(name="Sheet 02 = {0}mm".format(UpperThick)) res = JointInfoAssy.createPart(name="Width = {0}mm".format(HorizWidth)) res = JointInfoAssy.createPart(name="Length = {0}mm".format(HorizLength)) # Creating split regions cylPart = model_1.createPart(name="Cylinder") result = apex.geometry.createCylinderByLocationOrientation( name='', description='', length=(maxThick + minThick), radius=spotSize, sweepangle=360.0, origin=apex.Coordinate(HorizLength / 2.0, HorizWidth / 2.0, 0.0), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0)) entities_1 = apex.EntityCollection() entities_1.append(result) entities_1.hide() result = apex.geometry.createCylinderByLocationOrientation( name='', description='', length=(maxThick + minThick), radius=1.5 * spotSize, sweepangle=360.0, origin=apex.Coordinate(HorizLength / 2.0, HorizWidth / 2.0, 0.0), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0)) entities_1 = apex.EntityCollection() entities_1.append(result) entities_1.hide() result = apex.geometry.createCylinderByLocationOrientation( name='', description='', length=(maxThick + minThick), radius=2.0 * spotSize, sweepangle=360.0, origin=apex.Coordinate(HorizLength / 2.0, HorizWidth / 2.0, 0.0), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0)) ## Split sheets _target = apex.EntityCollection() _target.append(Sheet01.getSolids()[0]) _target.append(Sheet02.getSolids()[0]) _splitter = apex.EntityCollection() for Solid in cylPart.getSolids(): _splitter.extend(Solid.getFaces()) result = apex.geometry.split( target=_target, splitter=_splitter, splitBehavior=apex.geometry.GeometrySplitBehavior.Partition) entities_1 = apex.EntityCollection() entities_1.append(cylPart) apex.deleteEntities(entities_1) _plane = apex.construct.Plane( apex.construct.Point3D(HorizLength / 2.0, HorizWidth / 2.0, 0.0), apex.construct.Vector3D(1.0, 0.0, 0.0)) result = apex.geometry.splitWithPlane( target=_target, plane=_plane, splitBehavior=apex.geometry.GeometrySplitBehavior.Partition) ## - Perform meshing if requested if dict["MeshForMe"] == 'True': # - Meshing Sheet 01 and Sheet 02 refPoint = apex.Coordinate(HorizLength / 2.0, HorizWidth / 2.0, 0.0) listOfSolids = [Sheet01.getSolids()[0], Sheet02.getSolids()[0]] for i in range(len(listOfSolids)): proxSearch = apex.utility.ProximitySearch() ans = proxSearch.insertList(list(listOfSolids[i].getCells())) resSearch = proxSearch.findNearestObjects(location=refPoint, numObjects=4) cellsToMesh = apex.EntityCollection() for elem in resSearch.foundObjects(): cellsToMesh.append(elem) _SweepFace = apex.EntityCollection() result = apex.mesh.createHexMesh( name="", target=cellsToMesh, meshSize=(minThick / 4.0), surfaceMeshMethod=apex.mesh.SurfaceMeshMethod.Pave, mappedMeshDominanceLevel=2, elementOrder=apex.mesh.ElementOrder.Linear, refineMeshUsingCurvature=False, elementGeometryDeviationRatio=0.10, elementMinEdgeLengthRatio=0.20, createFeatureMeshOnWashers=False, createFeatureMeshOnArbitraryHoles=False, preserveWasherThroughMesh=True, sweepFace=_SweepFace, hexMeshMethod=apex.mesh.HexMeshMethod.Auto) resSearch = proxSearch.findNearestObjects(location=refPoint, numObjects=8) cellsToMesh = apex.EntityCollection() for elem in resSearch.foundObjects(): if len(elem.getElements() ) > 0: # Check if it has a mesh already pass else: cellsToMesh.append(elem) seedEdge = apex.EntityCollection() for Edge in elem.getEdges(): if i == 0: if 0.9 * LowerThick <= Edge.getLength( ) <= 1.1 * LowerThick: seedEdge.append(Edge) else: if 0.9 * UpperThick <= Edge.getLength( ) <= 1.1 * UpperThick: seedEdge.append(Edge) result = apex.mesh.createEdgeSeedUniformByNumber( target=seedEdge, numberElementEdges=2) for Cell in cellsToMesh: vecFaces = Cell.getFaces() for Face in vecFaces: paramU = Face.evaluatePointOnFace(Face.getCentroid()).u paramV = Face.evaluatePointOnFace(Face.getCentroid()).v normalAtPoint = Face.evaluateNormal(paramU, paramV) if abs(normalAtPoint.z ) == 1: # -Extrusion direction for meshing _SweepFace = apex.EntityCollection() _SweepFace.append(Face) meshCell = apex.EntityCollection() meshCell.append(Cell) result = apex.mesh.createHexMesh( name="", target=meshCell, meshSize=maxThick / 1.5, surfaceMeshMethod=apex.mesh.SurfaceMeshMethod.Pave, mappedMeshDominanceLevel=2, elementOrder=apex.mesh.ElementOrder.Linear, refineMeshUsingCurvature=False, elementGeometryDeviationRatio=0.10, elementMinEdgeLengthRatio=0.20, createFeatureMeshOnWashers=False, createFeatureMeshOnArbitraryHoles=False, preserveWasherThroughMesh=True, sweepFace=_SweepFace, hexMeshMethod=apex.mesh.HexMeshMethod.Auto) break ############################################################################################################################# ############################################################################################################################# #############################################################################################################################
def extractTrajectory(dictionary={}): model_1 = apex.currentModel() dirToSave = dictionary["saveToDir"] for selEdge in apex.selection.getCurrentSelection(): maxPointSpacing = 2 # mm workingEdge = selEdge workingEdgeLength = workingEdge.getLength() if selEdge.entityType != apex.EntityType.Edge: dictionary["getNormalDirection"] = "False" trajName = f"Trajectory_{selEdge.getName()}.csv" else: trajName = f"Trajectory_{selEdge.getId()}.csv" pathToSaveFile = os.path.join(dirToSave, trajName) if dictionary["getNormalDirection"] == 'True': # -Getting faces that are connected to this edge (at least three will come up) proxSearch = apex.utility.ProximitySearch() listOfConnectedFaces = workingEdge.getConnectedFaces() ans = proxSearch.insertCollection(listOfConnectedFaces) # -Find the face on which the edge is lying on top (should be only one) edgeMidpoint = workingEdge.getMidPoint() resSearch = proxSearch.findNearestObjects(location=edgeMidpoint, numObjects=1) selectedFace = "" for elem in resSearch.foundObjects(): selectedFace = elem # -Define trajectory characteristics if maxPointSpacing > 0: trajStep = int(workingEdgeLength / maxPointSpacing) trajResolution = trajStep + 1 if trajStep > 2 else 3 else: trajResolution = 4 paramRange = workingEdge.getParametricRange() delta = abs(paramRange['uEnd'] - paramRange['uStart']) / trajResolution sampling = [(x * delta) + paramRange['uStart'] for x in range(0, trajResolution + 1)] # -Build trajectory information trajInfo = [] for i in range(len(sampling)): pointCoord = [ workingEdge.evaluateEdgeParametricCoordinate( sampling[i]).x / 1000, # Converting to meters workingEdge.evaluateEdgeParametricCoordinate(sampling[i] ).y / 1000, # Converting to meters workingEdge.evaluateEdgeParametricCoordinate(sampling[i]).z / 1000 ] # Converting to meters pointResolve = apex.Coordinate( pointCoord[0] * 1000, # Converting to mm pointCoord[1] * 1000, # Converting to mm pointCoord[2] * 1000) # Converting to mm paramU = selectedFace.evaluatePointOnFace(pointResolve).u paramV = selectedFace.evaluatePointOnFace(pointResolve).v normalAtPoint = selectedFace.evaluateNormal(paramU, paramV) pointDir = [normalAtPoint.x, normalAtPoint.y, normalAtPoint.z] trajInfo.append(pointCoord + pointDir) # -Get the correct file header from a Simufact trajectory trajHeader = "# CSV file produced by the Welding Toolkit on MSC Apex" trajHeader += "\n# Date of creation: xx xx xxxx xx:xx:xx" trajHeader += "\n# Length unit: Meter [m]" trajHeader += "\n#" trajHeader += "\n# Orientation: 0 - global vector ; 1 - local vector; 2 - local second point" trajHeader += "\n1" trajHeader += "\n#" trajHeader += "\n# order;activity;x-coordinate;y-coordinate;z-coordinate;x-second point;y-second point;z-second point" trajBuild = trajHeader for i in range(len(trajInfo)): lineBuild = f"\n{i + 1};true;{trajInfo[i][0]};{trajInfo[i][1]};{trajInfo[i][2]};{trajInfo[i][3]};{trajInfo[i][4]};{trajInfo[i][5]}" trajBuild += lineBuild # -Write the trajectory file if pathToSaveFile: with open(pathToSaveFile, 'w') as newTrajFile: newTrajFile.write(trajBuild) else: # -Define trajectory characteristics if maxPointSpacing > 0: trajStep = int(workingEdgeLength / maxPointSpacing) trajResolution = trajStep + 1 if trajStep > 2 else 3 else: trajResolution = 4 paramRange = workingEdge.getParametricRange() delta = abs(paramRange['uEnd'] - paramRange['uStart']) / trajResolution sampling = [(x * delta) + paramRange['uStart'] for x in range(0, trajResolution + 1)] # -Build trajectory information trajInfo = [] for i in range(len(sampling)): pointCoord = [ workingEdge.evaluateEdgeParametricCoordinate( sampling[i]).x / 1000, # Converting to meters workingEdge.evaluateEdgeParametricCoordinate(sampling[i] ).y / 1000, # Converting to meters workingEdge.evaluateEdgeParametricCoordinate(sampling[i]).z / 1000 ] # Converting to meters trajInfo.append(pointCoord) # -Get the correct file header from a Simufact trajectory trajHeader = "# CSV file produced by the Apex Welding toolkit" trajHeader += "\n# Date of creation: xx xx xxxx xx:xx:xx" trajHeader += "\n# Length unit: Meter [m]" trajHeader += "\n#" trajHeader += "\n# Orientation: 0 - global vector ; 1 - local vector; 2 - local second point" trajHeader += "\n1" trajHeader += "\n#" trajHeader += "\n# order;activity;x-coordinate;y-coordinate;z-coordinate;x-second point;y-second point;z-second point" trajBuild = trajHeader for i in range(len(trajInfo)): lineBuild = f"\n{i + 1};true;{trajInfo[i][0]};{trajInfo[i][1]};{trajInfo[i][2]};0.0;0.0;1.0" trajBuild += lineBuild # -Write the trajectory file if pathToSaveFile: with open(pathToSaveFile, 'w') as newTrajFile: newTrajFile.write(trajBuild)
def build_truss_model(): """Builds a ready-to-solve model of a truss structure and saves the model. """ # Get the current model model = apex.currentModel() # Create a sketch of the truss truss_sketch(model, TRUSS_ENDPOINTS) # Get the part object and part collection part = apex.getPart('{}/Part 1'.format(model.getName())) part_collection = apex.EntityCollection() part_collection.append(part) # Mesh the truss curves curve = part.getCurves()[0] collection = apex.EntityCollection() collection.append(curve) mesh = apex.mesh.createCurveMesh( name='', target=collection, meshSize=10.0, elementOrder=apex.mesh.ElementOrder.Linear).curveMeshes[0] # Apply Constraints constraint_nodes = find_constraint_nodes(mesh.getNodes()) _constraints = [ apex.environment.createDisplacementConstraint( name=f'Constraint {idx+1}', constraintType=apex.attribute.ConstraintType.Clamped, applicationMethod=apex.attribute.ApplicationMethod.Direct, target=node) for idx, node in enumerate(constraint_nodes) ] # Apply Loads load_nodes = find_load_nodes(mesh.getNodes()) _loads = [ apex.environment.createForceMoment( name=f'Load{idx+1}', forceMomentRep=apex.environment. createForceMomentStaticRepByComponent(name='load', description='', forceY=-100.0), applicationMethod=apex.attribute.ApplicationMethod.Direct, target=node, orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0)) for idx, node in enumerate(load_nodes) ] # Apply Gravity Load orientation = apex.construct.createOptionOrientation() orientation.GlobalNY = True _gravity_1 = apex.environment.createGravityByG(name='Gravity', gravConstant=386.08858268, orientation=orientation, gravConstantMultiplier=1.0) # Create and assign material material_1 = apex.catalog.createMaterial(name='steel', color=[64, 254, 250]) material_1.update(elasticModulus=30000000.0) material_1.update(poissonRatio=0.3) material_1.update(density=0.000725222171) apex.attribute.assignMaterial(material=material_1, target=part_collection) # Create and apply beam sections beamshape_1 = apex.attribute.createBeamShapeHollowRoundByThickness( name='Beam Shape', outerRadius=2.0, thickness=0.25) _beamspan_1 = apex.attribute.createBeamSpanFree( name='Span', beamTarget=curve.getEdges(), shapeEndA=beamshape_1, shapeEndB=beamshape_1, shapeEndA_orientation=0.0, shapeEndB_orientation=0.0, shapeEndA_offset1=0.0, shapeEndA_offset2=0.0, shapeEndB_offset1=0.0, shapeEndB_offset2=0.0) # Create analysis study = apex.getPrimaryStudy() scenario = study.createScenarioByModelRep( context=part, simulationType=apex.studies.SimulationType.Static) # TODO: Figure out why the following line throws an error # scenario.execute() model_save_name = get_unused_name(model.name, SAVE_DIRECTORY) model.saveAs(model_save_name, SAVE_DIRECTORY)
def GenerateStudies(dict={}): # =================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() # Check existing material and create generic steel if needed if "SteelGeneric" not in apex.catalog.getMaterialDictionary().keys(): apex.setScriptUnitSystem(unitSystemName=r'''m-kg-s-N''') SteelMaterial = apex.catalog.createMaterial(name="SteelGeneric", description="", color=[64, 254, 250]) SteelMaterial.update(elasticModulus=210.e+9, poissonRatio=0.3, density=7.8e-6) apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') #print("Material data for generic steel created") else: #print("Material already exists, skipping...") pass # Assign generic steel material to all Parts GenericMaterial = apex.catalog.getMaterial(name="SteelGeneric") _target = apex.EntityCollection() _target.extend(model_1.getParts(True)) apex.attribute.assignMaterial(material=GenericMaterial, target=_target) # Run body selection for selAssy in apex.selection.getCurrentSelection(): listOfRefSolid = [] listOfRefSolidPaths = [] for Part in selAssy.getParts(True): Part.update(color=[255, 0, 0]) Part.show() for Solid in Part.getSolids(): listOfRefSolidPaths.append(Solid.getPathName()) listOfRefSolid.append(Solid) listOfTargetSolids = apex.EntityCollection() for Part in model_1.getParts(True): for Solid in Part.getSolids(): if Solid.getPathName() not in listOfRefSolidPaths: listOfTargetSolids.append(Solid) Solid.update(color=[0, 0, 255]) Part.addUserAttribute(userAttributeName=Part.getPathName(), stringValue='Self') for refSolid in listOfRefSolid: textDisplay = apex.display.displayText( text=refSolid.getName(), textLocation=refSolid.getCentroid(), graphicsFont="Calibri", graphicsFontColor=apex.ColorRGB(255, 191, 0), graphicsFontSize=16, graphicsFontStyle=apex.display.GraphicsFontStyle.Normal, graphicsFontUnderlineStyle=apex.display. GraphicsFontUnderlineStyle.NoUnderline) distance_ = apex.measureDistance(source=refSolid, target=listOfTargetSolids) listOfTouchedBodies = apex.EntityCollection() try: _ans = refSolid.getParent().removeUserAttributes( userAttributeNames=[]) except: pass refSolid.getParent().addUserAttribute( userAttributeName=refSolid.getParent().getPathName(), stringValue='Self') for k in range(len(distance_)): if distance_[k] <= 0.0: listOfTouchedBodies.append(listOfTargetSolids[k]) refSolid.getParent().addUserAttribute( userAttributeName=listOfTargetSolids[k].getParent( ).getPathName(), stringValue='Touched') apex.display.clearAllGraphicsText() # Organizing Parts and getting ready for modal analysis for refSolid in listOfRefSolid: StudyAssy = model_1.createAssembly(name="StudyAssy") dictInfo = {"Self": "", "Touched": []} solidParent = refSolid.getParent() # Moving Parts to the StudyAssy for Attribute in solidParent.getUserAttributes(): if Attribute.getStringValue() == 'Self': dictInfo[Attribute.getStringValue( )] = Attribute.getAttributeName() else: dictInfo[Attribute.getStringValue()].append( Attribute.getAttributeName()) ans_ = apex.getPart( Attribute.getAttributeName()).setParent( parent=StudyAssy) refSolid.getParent().setParent(parent=StudyAssy) # Creating ties based on touching bodies listOfTies = apex.EntityCollection() BeadPath = StudyAssy.getPart( dictInfo["Self"][dictInfo["Self"].rfind("/") + 1:]).getPathName() for elem in dictInfo["Touched"]: compPath = StudyAssy.getPart(elem[elem.rfind("/") + 1:]).getPathName() _entities = apex.getEntities(pathNames=[BeadPath, compPath]) newTies = apex.attribute.createMeshIndependentTieAutomatic( target=_entities, tiePairTolerance=5., patchToleranceCalculationMethod=apex.AutoManual.Automatic) listOfTies.extend(newTies) # --- Running the modal thing scenaryName = "Scenario for " + solidParent.getName() context_ = StudyAssy study = apex.getPrimaryStudy() study.createScenario( name=scenaryName, description="Generated by the Optimization Toolbox - FO", scenarioConfiguration=apex.studies.ScenarioConfiguration. NormalModes) study = apex.getPrimaryStudy() scenario1 = study.getScenario(name=scenaryName) scenario1.associateModelRep(context_) # study = apex.getPrimaryStudy() # scenario1 = study.getScenario(name=scenaryName) # simSetting1 = scenario1.simulationSettings # simSetting1.partReduction = False # simSetting1.freqRangeLower = 1000. # simSetting1.freqRangeUpper = float('NaN') # simSetting1.stopCalculation = True # simSetting1.maxModes = 3 # scenario1.simulationSettings = simSetting1 #model_1.save() scenario1.execute() # Kick it # --- Done with execution # Deleting ties apex.deleteEntities(listOfTies) # Reset the model tree for Part in StudyAssy.getParts(True): for Attribute in Part.getUserAttributes(): if Attribute.getStringValue() == 'Self': index = Attribute.getAttributeName().rfind("/") ParentAssy = Attribute.getAttributeName()[0:index] Part.setParent(parent=apex.getAssembly(ParentAssy)) # Delete the Assembly used to build the study toDelete = apex.EntityCollection() toDelete.append(StudyAssy) apex.deleteEntities(toDelete) # --- Do postprocessing result = apex.session.displayMeshCracks(False) result = apex.session.display2DSpans(False) result = apex.session.display3DSpans(False) apex.display.hideRotationCenter() result = apex.session.displayMeshCracks(False) result = apex.session.displayInteractionMarkers(True) result = apex.session.displayConnectionMarkers(True) result = apex.session.display2DSpans(False) result = apex.session.display3DSpans(True) result = apex.session.displayLoadsAndBCMarkers(True) result = apex.session.displaySensorMarkers(True) study = apex.getPrimaryStudy() scenario1 = study.getScenario(name=scenaryName) executedscenario_1 = scenario1.getLastExecutedScenario() event1 = executedscenario_1.getEvent( pathName="/Study/{0}<< -1>>/Event 1".format(scenaryName)) stateplot_1 = apex.post.createStatePlot(event=event1, resultDataSetIndex=[7]) visualizationTarget1 = apex.entityCollection() study = apex.getPrimaryStudy() scenario1 = study.getScenario(name=scenaryName) executedscenario_1 = scenario1.getLastExecutedScenario() visualizationTarget1.append( executedscenario_1.getAssembly( pathName=apex.currentModel().name + "/ar:StudyAssy_Default Rep")) deformvisualization_1 = stateplot_1.createDeformVisualization( target=visualizationTarget1, deformScalingMethod=apex.post.DeformScalingMethod.Relative, relativeScalingFactor=2., displayUnit="mm") result = apex.session.displaySensorMarkers(False) colormap_1 = apex.post.createColorMap( name="FringeSpectrum", colorMapSegmentMethod=apex.post.ColorMapSegmentMethod.Linear, start=0.0, end=0.0, isLocked=False, useOutOfRangeColors=False, displayContinuousColors=False) visualizationTarget1 = apex.entityCollection() study = apex.getPrimaryStudy() scenario1 = study.getScenario(name=scenaryName) executedscenario_1 = scenario1.getLastExecutedScenario() visualizationTarget1.append( executedscenario_1.getAssembly( pathName=apex.currentModel().name + "/ar:StudyAssy_Default Rep")) contourvisualization_1 = stateplot_1.createContourVisualization( contourStyle=apex.post.ContourStyle.Fringe, target=visualizationTarget1, resultQuantity=apex.post.ResultQuantity. DisplacementTranslational, resultDerivation=apex.post.ResultDerivation.Magnitude, layerIdentificationMethod=apex.post.LayerIdentificationMethod. Position, layers=["NONE"], layerEnvelopingMethod=apex.post.LayerEnvelopingMethod.Unknown, elementNodalProcessing=apex.post.ElementNodalProcessing. Averaged, coordinateSystemMethod=apex.post.CoordinateSystemMethod.Global, colorMap=colormap_1, displayUnit="mm") contourvisualization_1.update() result = apex.session.display3DSpans(False) result = apex.session.displaySensorMarkers(True) result = apex.session.display2DSpans(False) result = apex.session.display3DSpans(False) result = apex.session.displaySensorMarkers(True) for i in range(4): stateplot_1.update(resultDataSetIndex=[7 + i]) time.sleep(3) capturedImage = apex.display.captureImage( path= r"D:\00-Projects\01-SequenceOptimization\ApexFiles\Images", imageNamePrefix=scenaryName, imageCaptureRegion=apex.display.CaptureRegionType.Viewport, imageFormat=apex.display.ImageType.jpg) apex.post.exitPostProcess()
def ExpandSplit(dict={}): try: distance = float(dict["distance"]) except ValueError: apex.enableShowOutput() print("Non-numeric input for distance, must be a number!") raise model_1 = apex.currentModel() SelectedAssyName = "" _splitter = apex.EntityCollection() for Assembly in apex.selection.getCurrentSelection(): SelectedAssyName = Assembly.getName() for Part in Assembly.getParts(True): for Solid in Part.getSolids(): for Face in Solid.getFaces(): _splitter.append(Face) if dict["splitSolids"] == 'True': includeSolid = True else: includeSolid = False if dict["splitSurfaces"] == 'True': includeSurface = True else: includeSurface = False _target = apex.EntityCollection() for Part in model_1.getParts(True): if SelectedAssyName not in Part.getPathName(): if Part.getVisibility(): if includeSolid: for Solid in Part.getSolids(): if Solid.getVisibility(): _target.append(Solid) if includeSurface: for Surface in Part.getSurfaces(): if Surface.getVisibility(): _target.append(Surface) try: result = apex.geometry.splitEntityWithOffsetFaces( target=_target, splitter=_splitter, offset=( -1.0 * distance ), # Negative value to make it expand outwards, it does inwards otherwise splitBehavior=apex.geometry.GeometrySplitBehavior.Partition) except: print( "Split failed, ty using the Apex builtin tool instead. It is under partitioning, using offset." ) apex.enableShowOutput() if dict["suppressVertices"] == 'True': _target = apex.EntityCollection() for Part in model_1.getParts(True): if SelectedAssyName not in Part.getPathName(): for Surface in Part.getSurfaces(): if Surface.getVisibility(): _target.append(Surface.getVertices()) try: result = apex.geometry.suppressOnly( target=_target, maxEdgeAngle=1.000000000000000e+01, maxFaceAngle=5.000000000000000, keepVerticesAtCurvatureChange=False, cleanupTol=1.000000000000000, forceSuppress=False) except: apex.enableShowOutput() raise
def buildLapShear(dict={}): # - Get the data from the dictionary try: Thick01 = float(dict["Thick01"]) Thick02 = float(dict["Thick02"]) GapSize = float(dict["GapSize"]) spotSize = float(dict["SpotSize"]) except: apex.enableShowOutput() print("Please use only numbers as input in the fields.") ## Define max and min thickness if Thick01 >= Thick02: maxThick = Thick01 minThick = Thick02 else: maxThick = Thick02 minThick = Thick01 avgThick = (maxThick + minThick) / 2.0 if maxThick < 1.30: CouponLength = 105 CouponWidth = 45 CouponOverlap = 35 SampleLength = 175 GrippedLength = 40 UnclampedLength = 95 else: CouponLength = 138 CouponWidth = 60 CouponOverlap = 45 SampleLength = 230 GrippedLength = 62.5 UnclampedLength = 105 model_1 = apex.currentModel() ParentAssy = model_1.createAssembly(name="AWS-RSW-LapShear") # -- Build Upper sheet Sheet01 = apex.createPart() result = apex.geometry.createBoxByLocationOrientation( name='Sheet01', description='', length=CouponLength, # Length height=CouponWidth, # Width depth=Thick02, # Thickness origin=apex.Coordinate(0.0, 0.0, Thick01), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0) ) res = Sheet01.setParent(ParentAssy) res = Sheet01.update(name=f'UpperSheet-{Thick02}mm') # -- Build lower sheet Sheet02 = apex.createPart() result = apex.geometry.createBoxByLocationOrientation( name='Sheet02', description='', length=CouponLength, # Length height=CouponWidth, # Width depth=Thick01, # Thickness origin=apex.Coordinate(0.0, 0.0, 0.0), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0) ) res = Sheet02.setParent(ParentAssy) res = Sheet02.update(name=f'LowerSheet-{Thick01}mm') # -- Translate sheet to the correct overlap length _translateSheet = apex.EntityCollection() _translateSheet.append(Sheet02.getSolids()[0]) newEntities = apex.transformTranslate( target=_translateSheet, direction=[-1.0, 0.0, 0.0], distance=(CouponLength - CouponOverlap), makeCopy=False ) # -- Creating split regions cylPart = model_1.createPart(name="Cylinder") result = apex.geometry.createCylinderByLocationOrientation( name='', description='', length=(maxThick + minThick), radius=spotSize, sweepangle=360.0, origin=apex.Coordinate(CouponOverlap / 2.0, CouponWidth / 2.0, 0.0), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0) ) entities_1 = apex.EntityCollection() entities_1.append(result) entities_1.hide() result = apex.geometry.createCylinderByLocationOrientation( name='', description='', length=(maxThick + minThick), radius=1.5 * spotSize, sweepangle=360.0, origin=apex.Coordinate(CouponOverlap / 2.0, CouponWidth / 2.0, 0.0), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0) ) entities_1 = apex.EntityCollection() entities_1.append(result) entities_1.hide() result = apex.geometry.createCylinderByLocationOrientation( name='', description='', length=(maxThick + minThick), radius=2.0 * spotSize, sweepangle=360.0, origin=apex.Coordinate(CouponOverlap / 2.0, CouponWidth / 2.0, 0.0), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0) ) # -- Split sheets _target = apex.EntityCollection() _target.append( Sheet01.getSolids()[0] ) _target.append( Sheet02.getSolids()[0] ) _splitter = apex.EntityCollection() for Solid in cylPart.getSolids(): _splitter.extend(Solid.getFaces()) result = apex.geometry.split( target = _target, splitter = _splitter, splitBehavior = apex.geometry.GeometrySplitBehavior.Partition ) entities_1 = apex.EntityCollection() entities_1.append(cylPart) #apex.deleteEntities(entities_1) _plane = apex.construct.Plane( apex.construct.Point3D(CouponOverlap / 2.0, CouponWidth / 2.0, 0.0), apex.construct.Vector3D(1.0, 0.0, 0.0) ) result = apex.geometry.splitWithPlane( target=_target, plane=_plane, splitBehavior=apex.geometry.GeometrySplitBehavior.Partition ) # -- Translate _translateSheet = apex.EntityCollection() _translateSheet.append(Sheet01.getSolids()[0]) newPosition = apex.transformTranslate( target=_translateSheet, direction=[0.0, 0.0, 1.0], distance=GapSize, makeCopy=False ) # -- Create grippers if dict["CreateGrippers"] == 'True': # -- Build Upper gripper UpperGripper = apex.createPart() result = apex.geometry.createBoxByLocationOrientation( name='UpperGripper', description='', length=1.2 * GrippedLength, # Length height=CouponWidth, # Width depth=3 * Thick02, # Thickness origin=apex.Coordinate(0.0, 0.0, Thick01), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0) ) res = UpperGripper.setParent(ParentAssy) res = UpperGripper.update(name=f'UpperGripper') # -- Translate _translateSheet = apex.EntityCollection() _translateSheet.append(UpperGripper.getSolids()[0]) newPosition = apex.transformTranslate( target=_translateSheet, direction=[1.0, 0.0, 0.0], distance=(CouponLength - GrippedLength), makeCopy=False ) newPosition = apex.transformTranslate( target=_translateSheet, direction=[0.0, 0.0, -1.0], distance=(Thick02 + GapSize), makeCopy=False ) _target = apex.EntityCollection() _target.append(UpperGripper.getSolids()[0]) _subtractingEntities = apex.EntityCollection() _subtractingEntities.append(Sheet01.getSolids()[0]) result = apex.geometry.subtractBoolean( target=_target, subtractingEntity=_subtractingEntities, retainOriginalBodies=True ) # -- Build Lower gripper LowerGripper = apex.createPart() result = apex.geometry.createBoxByLocationOrientation( name='LowerGripper', description='', length=1.2 * GrippedLength, # Length height=CouponWidth, # Width depth=3 * Thick01, # Thickness origin=apex.Coordinate(0.0, 0.0, Thick01), orientation=apex.construct.createOrientation(alpha=0.0, beta=0.0, gamma=0.0) ) res = LowerGripper.setParent(ParentAssy) res = LowerGripper.update(name=f'LowerGripper') # -- Translate _translateSheet = apex.EntityCollection() _translateSheet.append(LowerGripper.getSolids()[0]) newPosition = apex.transformTranslate( target=_translateSheet, direction=[-1.0, 0.0, 0.0], distance=(CouponLength - CouponOverlap + 0.2 * GrippedLength), makeCopy=False ) newPosition = apex.transformTranslate( target=_translateSheet, direction=[0.0, 0.0, -1.0], distance=(Thick01 + Thick02), makeCopy=False ) _target = apex.EntityCollection() _target.append(LowerGripper.getSolids()[0]) _subtractingEntities = apex.EntityCollection() _subtractingEntities.append(Sheet02.getSolids()[0]) result = apex.geometry.subtractBoolean( target=_target, subtractingEntity=_subtractingEntities, retainOriginalBodies=True ) _target = apex.EntityCollection() for Edge in UpperGripper.getSolids()[0].getEdges(): _target.append(Edge) for Edge in LowerGripper.getSolids()[0].getEdges(): _target.append(Edge) try: result = apex.geometry.pushPull( target=_target, method=apex.geometry.PushPullMethod.Fillet, behavior=apex.geometry.PushPullBehavior.FollowShape, removeInnerLoops=False, createBooleanUnion=False, distance=0.05, direction=[7.071067811865475e-01, 7.071067811865475e-01, 0.0] ) except: pass # -- Perform meshing if requested if dict["Meshing"] != 'No mesh': if dict["Meshing"] == "For weld": refLevel = 4.0 # Ref level for weld only else: refLevel = 8.0 # Ref level for pull test # - Meshing Sheet 01 and Sheet 02 refPoint = apex.Coordinate(CouponOverlap / 2.0, CouponWidth / 2.0, 0.0) listOfSolids = [Sheet01.getSolids()[0], Sheet02.getSolids()[0]] for i in range(len(listOfSolids)): proxSearch = apex.utility.ProximitySearch() ans = proxSearch.insertList(list(listOfSolids[i].getCells())) resSearch = proxSearch.findNearestObjects(location=refPoint, numObjects=4) cellsToMesh = apex.EntityCollection() for elem in resSearch.foundObjects(): cellsToMesh.append(elem) _SweepFace = apex.EntityCollection() result = apex.mesh.createHexMesh( name="", target=cellsToMesh, meshSize=(minThick / refLevel), surfaceMeshMethod=apex.mesh.SurfaceMeshMethod.Pave, mappedMeshDominanceLevel=2, elementOrder=apex.mesh.ElementOrder.Linear, refineMeshUsingCurvature=False, elementGeometryDeviationRatio=0.10, elementMinEdgeLengthRatio=0.20, createFeatureMeshOnWashers=False, createFeatureMeshOnArbitraryHoles=False, preserveWasherThroughMesh=True, sweepFace=_SweepFace, hexMeshMethod=apex.mesh.HexMeshMethod.Auto ) resSearch = proxSearch.findNearestObjects(location=refPoint, numObjects=8) cellsToMesh = apex.EntityCollection() for elem in resSearch.foundObjects(): if len(elem.getElements()) > 0: # Check if it has a mesh already pass else: cellsToMesh.append(elem) seedEdge = apex.EntityCollection() for Edge in elem.getEdges(): if i == 0: if 0.9 * Thick02 <= Edge.getLength() <= 1.1 * Thick02: seedEdge.append(Edge) else: if 0.9 * Thick01 <= Edge.getLength() <= 1.1 * Thick01: seedEdge.append(Edge) result = apex.mesh.createEdgeSeedUniformByNumber( target=seedEdge, numberElementEdges=2 ) for Cell in cellsToMesh: vecFaces = Cell.getFaces() for Face in vecFaces: paramU = Face.evaluatePointOnFace(Face.getCentroid()).u paramV = Face.evaluatePointOnFace(Face.getCentroid()).v normalAtPoint = Face.evaluateNormal(paramU, paramV) if abs(normalAtPoint.z) == 1: # -Extrusion direction for meshing _SweepFace = apex.EntityCollection() _SweepFace.append(Face) meshCell = apex.EntityCollection() meshCell.append(Cell) result = apex.mesh.createHexMesh( name="", target=meshCell, meshSize=maxThick/1.5, surfaceMeshMethod=apex.mesh.SurfaceMeshMethod.Pave, mappedMeshDominanceLevel=2, elementOrder=apex.mesh.ElementOrder.Linear, refineMeshUsingCurvature=False, elementGeometryDeviationRatio=0.10, elementMinEdgeLengthRatio=0.20, createFeatureMeshOnWashers=False, createFeatureMeshOnArbitraryHoles=False, preserveWasherThroughMesh=True, sweepFace=_SweepFace, hexMeshMethod=apex.mesh.HexMeshMethod.Auto ) break _target = apex.EntityCollection() _target.append(LowerGripper.getSolids()[0]) _target.append(UpperGripper.getSolids()[0]) featuremeshtypes_2 = apex.mesh.FeatureMeshTypeVector() result = apex.mesh.createSurfaceMesh( name="", target=_target, meshSize=minThick, meshType=apex.mesh.SurfaceMeshElementShape.Quadrilateral, meshMethod=apex.mesh.SurfaceMeshMethod.Auto, mappedMeshDominanceLevel=2, elementOrder=apex.mesh.ElementOrder.Linear, refineMeshUsingCurvature=False, elementGeometryDeviationRatio=0.10, elementMinEdgeLengthRatio=0.20, growFaceMeshSize=False, faceMeshGrowthRatio=1.2, createFeatureMeshes=False, featureMeshTypes=featuremeshtypes_2, projectMidsideNodesToGeometry=True, useMeshFlowOptimization=True, meshFlow=apex.mesh.MeshFlow.Grid )
def CreateMeshPartitions(dict={}): # =================================================================== ## Initializing Apex code apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() ## Collect faces to mesh _targetFine = apex.entityCollection() listOfLengths = [] listOfDiameters = [] try: MeshSize = float(dict["MeshSize"]) except: MeshSize = float(dict["FineMeshSize"]) #try: listOfTrajectories = model_1.getAssembly("Refinement regions").getParts( True) listOfAllParts = [] for Part in model_1.getParts(True): if "Refinement regions" not in Part.getPath(): listOfAllParts.append(Part) for Part in listOfTrajectories: if 'RefDiam' in Part.getName(): _, Diam = Part.getName().split('_') listOfDiameters.append(float(Diam)) else: if len(Part.getCurves()) > 0: listOfLengths.append(Part.getCurves()[0].getLength()) maxDiameter = max( listOfDiameters) #Getting the max diameter to use as search range ## Getting all faces from all parts that are not under 'Trajectories' proxSearch = apex.utility.ProximitySearch() listOfAllPartFaces = [] for Part in listOfAllParts: for Surface in Part.getSurfaces(): for Face in Surface.getFaces(): listOfAllPartFaces.append(Face) ## Inserting the list of faces into the proximity search ans = proxSearch.insertList(listOfAllPartFaces) facesToMesh = apex.EntityCollection() ## Perform the search for Part in model_1.getAssembly('Refinement regions').getParts( ): # Add spots and weld beads to perfom the search for Solid in Part.getSolids(): resSearch = proxSearch.findObjectsWithinDistance( location=Solid.getLocation(), distance=1.1 * maxDiameter) for elem in resSearch.foundObjects(): if elem.entityType == apex.EntityType.Face: facesToMesh.append(elem) if listOfLengths: minLength = min(listOfLengths) ## Select everything that is smaller than the minLength * maxDiameter for Assy in model_1.getAssemblies(): if "Refinement regions" not in Assy.getName(): for Part in Assy.getParts(recursive=True): for Surface in Part.getSurfaces(): for Face in Surface.getFaces(): if Face.getArea() <= (0.8 * max(listOfLengths) * maxDiameter): facesToMesh.append(Face) else: ## Select everything that is smaller than the minLength * maxDiameter for Part in listOfAllParts: for Surface in Part.getSurfaces(): for Face in Surface.getFaces(): if Face.getArea() <= (1.1 * 3.14159 * (maxDiameter / 2)**2): facesToMesh.append(Face) apex.mesh.createSurfaceMesh( name="", target=facesToMesh, meshSize=MeshSize, meshType=apex.mesh.SurfaceMeshElementShape.Mixed, meshMethod=apex.mesh.SurfaceMeshMethod.Pave, mappedMeshDominanceLevel=2, elementOrder=apex.mesh.ElementOrder.Linear, meshUsingPrincipalAxes=False, refineMeshUsingCurvature=True, elementGeometryDeviationRatio=0.10, elementMinEdgeLengthRatio=0.50, createFeatureMeshOnFillets=False, createFeatureMeshOnChamfers=False, createFeatureMeshOnWashers=False, createFeatureMeshOnQuadFaces=False) try: pass except: print("Meshing failed or not performed.")
def verticalSlicing(dict={}): layerHeight = float(dict['layerHeight']) if dict['layerHeight'] else -1 model_1 = apex.currentModel() for selectedFace in apex.selection.getCurrentSelection(): currCut = layerHeight fCentr = [ selectedFace.getCentroid().x, selectedFace.getCentroid().y, selectedFace.getCentroid().z ] print(fCentr) paramU = selectedFace.evaluatePointOnFace(selectedFace.getCentroid()).u paramV = selectedFace.evaluatePointOnFace(selectedFace.getCentroid()).v normalAtPoint = selectedFace.evaluateNormal(paramU, paramV) normInvDir = [ -1 * normalAtPoint.x, -1 * normalAtPoint.y, -1 * normalAtPoint.z ] print(paramU, paramV) _target = apex.EntityCollection() _target.append(selectedFace.getBody()) while (True): # Loop to split vertically try: vecDir = apex.construct.Vector3D(currCut * normInvDir[0], currCut * normInvDir[1], currCut * normInvDir[2]) point3D = apex.construct.Point3D( (currCut * normInvDir[0]) + fCentr[0], (currCut * normInvDir[1]) + fCentr[1], (currCut * normInvDir[2]) + fCentr[2]) _plane = apex.construct.Plane(point3D, vecDir) if dict["splitBody"] == 'True': result = apex.geometry.splitWithPlane( target=_target, plane=_plane, splitBehavior=apex.geometry.GeometrySplitBehavior. Partition) else: result = apex.geometry.splitWithPlane( target=_target, plane=_plane, splitBehavior=apex.geometry.GeometrySplitBehavior.Split ) currCut += layerHeight except: e = sys.exc_info()[0] print(e) break listOfNames = [] listOfCenterHeight = [] for solid in model_1.getCurrentPart().getSolids(): solid.update(enableTransparency=True, transparencyLevel=50) listOfNames.append(solid.getPathName()) listOfCenterHeight.append(solid.getCentroid().z) sortedByHeight = [ x for _, x in sorted(zip(listOfCenterHeight, listOfNames)) ] newPath = [] for layerNum in range(len(sortedByHeight)): newPath.append( apex.getSolid(pathName=sortedByHeight[layerNum]).getPath() + "/Layer_{0}".format(layerNum)) res = apex.getSolid(pathName=sortedByHeight[layerNum]).update( name="Layer_{0}".format(layerNum))
def hatchingLayers(dict={}): listOfNames = [] listOfCenterHeight = [] distLine = float(dict["distanceLine"]) angleType = dict["angleType"] angleValue = dict["angleValue"] pointSpace = float(dict["pointSpacing"]) meshIt = dict["meshIt"] saveToDir = dict["saveToDir"] if angleType == 'Cycle through': from itertools import cycle angleList = angleValue.strip().replace(' ', '').split(',') angleList = [float(x) for x in angleList] anglesCycle = cycle(angleList) def nextAngle(): return next(anglesCycle) #for selObj in apex.selection.getCurrentSelection(): model_1 = apex.currentModel() for Solid in apex.selection.getCurrentSelection(): listOfNames.append(Solid.getPathName()) listOfCenterHeight.append(Solid.getCentroid().z) entities_1 = apex.EntityCollection() entities_1.append(Solid) entities_1.hide() sortedByHeight = [ x for _, x in sorted(zip(listOfCenterHeight, listOfNames)) ] currLayer = 1 for solidPath in sortedByHeight: solidToSlice = apex.getSolid(pathName=solidPath) solidName = solidToSlice.getName() xCenter = solidToSlice.getCentroid().x yCenter = solidToSlice.getCentroid().y zCenter = solidToSlice.getCentroid().z startPos = [xCenter, yCenter, zCenter] entities_1 = apex.EntityCollection() entities_1.append(solidToSlice) entities_1.show() if angleType == 'Single angle': angle = float(angleValue) elif angleType == 'Incremental': angle = float(angleValue) * currLayer elif angleType == 'Cycle through': angle = nextAngle() FullSlicing(bodyToSlice=solidToSlice, cutStartPos=startPos, cutStepping=distLine, cutAngleDeg=angle, maxPointSpacing=pointSpace, dirToSaveFiles=saveToDir, trajName=solidName) currLayer += 1 if meshIt == 'True': for solidPath in sortedByHeight: solidToMesh = apex.getSolid(pathName=solidPath) _target = apex.EntityCollection() _target.append(solidToMesh) _SweepFace = apex.EntityCollection() result = apex.mesh.createHexMesh( name="", target=_target, meshSize=distLine / 3, surfaceMeshMethod=apex.mesh.SurfaceMeshMethod.Mapped, mappedMeshDominanceLevel=3, elementOrder=apex.mesh.ElementOrder.Linear, refineMeshUsingCurvature=False, elementGeometryDeviationRatio=0.10, elementMinEdgeLengthRatio=0.50, createFeatureMeshOnWashers=False, createFeatureMeshOnArbitraryHoles=False, preserveWasherThroughMesh=False, sweepFace=_SweepFace, hexMeshMethod=apex.mesh.HexMeshMethod.Auto)
def calcSelected(grid={}): model = apex.currentModel() meshItem = [] grid['meshes'] = meshItem for Elem in apex.selection.getCurrentSelection(): if Elem.getVisibility(): if type(Elem) == apex.Assembly: for Part in Elem.getParts(True): for Mesh in Part.getMeshes(): if Mesh.getVisibility(): meshInfo = {} meshItem.append(meshInfo) meshInfo['mesh_name'] = Mesh.getName() meshInfo['parent_name'] = Mesh.getParent().getName() meshInfo['elements_count'] = len(Mesh.getElements()) meshType = "" if Mesh.getEntityType() == 42: meshType += "Tetra " elif Mesh.getEntityType() == 43: meshType += "Surface " elif Mesh.getEntityType() == 45: meshType += "Hexa " else: meshType = "??" meshInfo['mesh_type'] = meshType elif type(Elem) == apex.Part: for Mesh in Elem.getMeshes(): if Mesh.getVisibility(): meshInfo = {} meshItem.append(meshInfo) meshInfo['mesh_name'] = Mesh.getName() meshInfo['parent_name'] = Mesh.getParent().getName() meshInfo['elements_count'] = len(Mesh.getElements()) meshType = "" if Mesh.getEntityType() == 42: meshType += "Tetra " elif Mesh.getEntityType() == 43: meshType += "Surface " elif Mesh.getEntityType() == 45: meshType += "Hexa " else: meshType = "??" meshInfo['mesh_type'] = meshType elif type(Elem) == apex.mesh.SurfaceMesh: Mesh = Elem if Elem.getVisibility(): meshInfo = {} meshItem.append(meshInfo) meshInfo['mesh_name'] = Mesh.getName() meshInfo['parent_name'] = Mesh.getParent().getName() meshInfo['elements_count'] = len(Mesh.getElements()) meshType = "" if Mesh.getEntityType() == 42: meshType += "Tetra " elif Mesh.getEntityType() == 43: meshType += "Surface " elif Mesh.getEntityType() == 45: meshType += "Hexa " else: meshType = "??" meshInfo['mesh_type'] = meshType elif type(Elem) == apex.mesh.SolidMesh: Mesh = Elem if Elem.getVisibility(): meshInfo = {} meshItem.append(meshInfo) meshInfo['mesh_name'] = Mesh.getName() meshInfo['parent_name'] = Mesh.getParent().getName() meshInfo['elements_count'] = len(Mesh.getElements()) meshType = "" if Mesh.getEntityType() == 42: meshType += "Tetra " elif Mesh.getEntityType() == 43: meshType += "Surface " elif Mesh.getEntityType() == 45: meshType += "Hexa " else: meshType = "??" meshInfo['mesh_type'] = meshType elif type(Elem) == apex.mesh.HexMesh: Mesh = Elem if Elem.getVisibility(): meshInfo = {} meshItem.append(meshInfo) meshInfo['mesh_name'] = Mesh.getName() meshInfo['parent_name'] = Mesh.getParent().getName() meshInfo['elements_count'] = len(Mesh.getElements()) meshType = "" if Mesh.getEntityType() == 42: meshType += "Tetra " elif Mesh.getEntityType() == 43: meshType += "Surface " elif Mesh.getEntityType() == 45: meshType += "Hexa " else: meshType = "??" meshInfo['mesh_type'] = meshType return grid
def CreateWeldBead(CSVPath="NoPath", RefineDiam=4.0, UnitType="None"): model_1 = apex.currentModel() if "/" in CSVPath: TrajectoryName = CSVPath[CSVPath.rfind("/") + 1:-4] else: TrajectoryName = CSVPath[CSVPath.rfind("\\") + 1:-4] try: TrajAssy = model_1.getAssembly(pathName="Refinement regions") except: TrajAssy = model_1.createAssembly(name="Refinement regions") CurrPart = apex.createPart(name=TrajectoryName) CurrPart.setParent(model_1.getAssembly("Refinement regions")) vecLine = [] with open(CSVPath, 'r') as CSVContent: if UnitType == 'Millimeters': convRatio = 1.0 elif UnitType == 'Meters': convRatio = 1000.0 elif UnitType == 'Inches': convRatio = 2.54 for line in CSVContent: if ('true' in line) or ('false' in line): vecLine.append([ convRatio * float(X) for X in line.strip().split(';')[2:5] ]) ## Creating points at the location in the CSV file, these will guide the spline creation _iphysicalCollection = apex.IPhysicalCollection() for i in range(len(vecLine)): _iphysicalCollection.append( apex.Coordinate(vecLine[i][0], vecLine[i][1], vecLine[i][2])) ## Create spline based on the list of points given by the CSV file result = apex.geometry.createCurve( target=_iphysicalCollection, behavior=apex.geometry.CurveBehavior.Spline) def doCircle(diam=8.0): part_1 = model_1.getCurrentPart() if part_1 is None: part_1 = model_1.createPart() sketch_1 = part_1.createSketchOnGlobalPlane( name='Sketch 1', plane=apex.construct.GlobalPlane.YZ, alignSketchViewWithViewport=True) circle_1 = sketch_1.createCircleCenterPoint( name="Circle 1", centerPoint=Point2D(0, 0), pointOnCircle=Point2D(0, diam / 2)) return sketch_1.completeSketch(fillSketches=True) CircleDone = doCircle(diam=RefineDiam) ## Move circle to a new point location part_2 = model_1.getCurrentPart() for Surf in part_2.getSurfaces(): CurrPath = Surf.getPathName() CurrPath = CurrPath[CurrPath.find('/') + 1:] _entities = model_1.getEntities(pathNames=[CurrPath]) PathLength = sqrt( pow(vecLine[0][0], 2) + pow(vecLine[0][1], 2) + pow(vecLine[0][2], 2)) apex.transformTranslate(target=_entities, direction=vecLine[0], distance=PathLength, makeCopy=False) ## Rotate the circle _entities = model_1.getEntities(pathNames=[CurrPath]) TurnAngle = angle([1, 0, 0], [a - b for a, b in zip(vecLine[1], vecLine[0])]) if TurnAngle == 180: TurnAngle = 0 apex.transformRotate( target=_entities, axisDirection=cross( [1, 0, 0], [a - b for a, b in zip(vecLine[1], vecLine[0])]), axisPoint=Point3D(vecLine[0][0], vecLine[0][1], vecLine[0][2]), angle=TurnAngle, makeCopy=False) _target = apex.EntityCollection() _target.append(model_1.getCurrentPart().getSurfaces()[0]) _path = apex.EntityCollection() _path.append(model_1.getCurrentPart().getCurves()[0]) _lockDirection = apex.construct.Vector3D(0.0, 0.0, 0.0) try: result = apex.geometry.createGeometrySweepPath( target=_target, path=_path, scale=0.0, twist=0.0, profileSweepAlignmentMethod=apex.geometry. SweepProfileAlignmentMethod.Normal, islocked=False, lockDirection=_lockDirection, profileClamp=apex.geometry.SweepProfileClampingMethod.Smooth) GotBead = True except: print("Sweep failed...") GotBead = False ## Clean up the supporting geometries (points, curves, surfaces, etc.) DelEntities = apex.EntityCollection() ## Do NOT delete curves, they are used to get weld bead length """ DelCurves = model_1.getCurrentPart().getCurves() for Curve in DelCurves: DelEntities.append(Curve) DelPoints = model_1.getCurrentPart().getPoints() for Point in DelPoints: DelEntities.append(Point) """ if GotBead: DelSurfaces = model_1.getCurrentPart().getSurfaces() for Surface in DelSurfaces: DelEntities.append(Surface) apex.deleteEntities(DelEntities) ## Rename part and solid if GotBead: updateSolidName = model_1.getCurrentPart().getSolids()[0].update( name=TrajectoryName) if dict["ExtendBead"] == "True": #Push-pull the extremities by the diameter amount try: for Face in model_1.getCurrentPart().getSolids( )[0].getFaces(): XSectionArea = 3.14159 * (RefineDiam / 2)**2 if (0.9 * XSectionArea) < Face.getArea() < ( 1.1 * XSectionArea): _target = apex.EntityCollection() _target.append(Face) result = apex.geometry.pushPull( target=_target, method=apex.geometry.PushPullMethod.Normal, behavior=apex.geometry.PushPullBehavior. FollowShape, removeInnerLoops=False, createBooleanUnion=False, distance=RefineDiam, direction=[1.0, 1.0, 1.0]) except: updatePartName = model_1.getCurrentPart().update( name=TrajectoryName + "_ExtendFailed") else: updatePartName = model_1.getCurrentPart().update( name=TrajectoryName + "_SweepFailed") try: if model_1.getAssembly("Refinement regions").getPart( name="RefDiam_{0}".format(RefineDiam)): pass else: SpecifiedDiameter = apex.createPart( name="RefDiam_{0}".format(RefineDiam)) SpecifiedDiameter.setParent( model_1.getAssembly("Refinement regions")) except: print("Part creation failed!")
import apex from apex.construct import Point3D, Point2D apex.disableShowOutput() apex.setScriptUnitSystem(unitSystemName=r'''mm-kg-s-N''') model_1 = apex.currentModel() def RemoveEmpty(dict={}): entitiesToRemove = apex.EntityCollection() for Part in model_1.getParts(True): if not Part.getSolids(): entitiesToRemove.append(Part) try: apex.deleteEntities(entitiesToRemove) except: pass entitiesToRemove = apex.EntityCollection() for Assy in model_1.getAssemblies(True): if not Assy.getParts(True): entitiesToRemove.append(Assy) try: apex.deleteEntities(entitiesToRemove) except: pass
def ShowType(dict={}): model_1 = apex.currentModel() _splitter = apex.EntityCollection() for Elem in apex.selection.getCurrentSelection(): print(type(Elem)) print(Elem.getBody().getPathName())