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 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()
b(C.range_b, C.slow_step, -C.br_width), C.v, 0, ptList_p[19]) Curves(ap(C.range_a, C.slow_step, odstep_slupa), b_p(C.range_b, C.slow_step, odstep_slupa), C.v, -1.0, ptList_p[20]) size = len(ptList_p[10]) # Wyznacza ilość przepon new_ptList = [] for i in range(0, size): new_ptList.append( [] ) # Dodaje do nowej tablicy dokładnie tyle pustych tablic ile jest przepon for list in ptList_p: new_ptList[i].append( list[i] ) # Dodaje do tablicy z indeksem [i] znajdującej się w tablicy new_ptList, punkty o indeksie (i) kolejno z każdej tablicy zawartej w tablicy ptList_p for Curve in range(0, len(new_ptList)): Lista = new_ptList[Curve] n = len(Lista) deg = 1 m = n + deg + 1 controlPoints = Lista knotPoints = linspace(0, 1, m) createCurve3DNurb(controlPoints, knotPoints, deg).asCurve() for i in range(22, 39): _target = apex.EntityCollection() part_1 = apex.getPart(pathName="gen/Part 1") curve_1 = part_1.getCurve(name="Curve {}".format(i)) _target.extend(curve_1.getEdges()) result = apex.geometry.fillerSurface(target=_target)
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 createRefRegion(dict={}): model_1 = apex.currentModel() ### Math functions needed when numpy is not available def multip3D(v1, k): # Addition of two ponts in 3D return [x * k for x in v1] def add3D(v1, v2): # Addition of two ponts in 3D return [x + y for x, y in zip(v1, v2)] def subtract3D(v1, v2): # Subtraction of two ponts in 3D return [x - y for x, y in zip(v1, v2)] def distance3D(v1, v2): # Distance between two points in 3D return sqrt(abs(sum((a - b) for a, b in zip(v1, v2)))) def dotproduct(v1, v2): # Dot product of two vectors (list), cosine of the angle return sum((a * b) for a, b in zip(v1, v2)) def length(v): # Length of a vector (list) return sqrt(dotproduct(v, v)) def angle(v1, v2): # Angle between two vectors in degrees (lists) return degrees(acos(dotproduct(v1, v2) / (length(v1) * length(v2)))) # Return the angle in degrees def cross(a, b): # Cross-product (orthogonal vector) of two vectors (list) c = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] return c # List of three components (x,y,z) of the orthogonal vector 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='', plane=apex.construct.GlobalPlane.YZ, alignSketchViewWithViewport=True ) circle_1 = sketch_1.createCircleCenterPoint( name="", centerPoint=Point2D(0, 0), pointOnCircle=Point2D(0, diam / 2) ) return sketch_1.completeSketch(fillSketches=True) try: refDiameter = float(dict["refDiam"]) except: apex.enableShowOutput() print("\nInvalid diameter value!") raise try: TrajAssy = model_1.getAssembly(pathName="Refinement regions") except: TrajAssy = model_1.createAssembly(name="Refinement regions") try: if TrajAssy.getPart(name=f"RefDiam_{refDiameter}"): pass else: SpecifiedDiameter = TrajAssy.createPart(name=f"RefDiam_{refDiameter}") except: apex.enableShowOutput() print("Part creation with refinement diameter info failed!") allLongEdges = apex.EntityCollection() for selElement in apex.selection.getCurrentSelection(): # If selection is is a Part, go check what is inside if selElement.getVisibility(): if selElement.entityType == apex.EntityType.Part: for Solid in selElement.getSolids(): if Solid.getVisibility(): maxEdgeLength = 0.0 selectedEdge = apex.EntityType.Edge for Edge in Solid.getEdges(): if Edge.getLength() > maxEdgeLength: selectedEdge = Edge maxEdgeLength = Edge.getLength() allLongEdges.append(selectedEdge) for Surface in selElement.getSurfaces(): if Surface.getVisibility(): maxEdgeLength = 0.0 selectedEdge = apex.EntityType.Edge for Edge in Surface.getEdges(): if Edge.getLength() > maxEdgeLength: selectedEdge = Edge maxEdgeLength = Edge.getLength() allLongEdges.append(selectedEdge) # If selection is an Assembly, get the Parts and check what is inside if selElement.entityType == apex.EntityType.Assembly: if selElement.getVisibility(): for Part in selElement.getParts(True): if Part.getVisibility(): for Solid in Part.getSolids(): if Solid.getVisibility(): maxEdgeLength = 0.0 selectedEdge = apex.EntityType.Edge for Edge in Solid.getEdges(): if Edge.getLength() > maxEdgeLength: selectedEdge = Edge maxEdgeLength = Edge.getLength() allLongEdges.append(selectedEdge) for Surface in Part.getSurfaces(): if Surface.getVisibility(): maxEdgeLength = 0.0 selectedEdge = apex.EntityType.Edge for Edge in Surface.getEdges(): if Edge.getLength() > maxEdgeLength: selectedEdge = Edge maxEdgeLength = Edge.getLength() allLongEdges.append(selectedEdge) for selEdge in allLongEdges: CurrPart = TrajAssy.createPart(name="Edge_{0}_{1}mm".format(selEdge.getId(), refDiameter)) maxPointSpacing = 2 #mm if maxPointSpacing > 0: trajStep = int(selEdge.getLength() / maxPointSpacing) trajResolution = trajStep + 1 if trajStep > 2 else 3 else: trajResolution = 4 paramRange = selEdge.getParametricRange() delta = abs(paramRange['uEnd'] - paramRange['uStart']) / trajResolution sampling = [(x * delta) + paramRange['uStart'] for x in range(0, trajResolution + 1)] _PointCollection = apex.IPhysicalCollection() PathPoints = [] for i in range(len(sampling)): pointCoord = apex.Coordinate(selEdge.evaluateEdgeParametricCoordinate(sampling[i]).x , selEdge.evaluateEdgeParametricCoordinate(sampling[i]).y , selEdge.evaluateEdgeParametricCoordinate(sampling[i]).z) _PointCollection.append(pointCoord) PathPoints.append([selEdge.evaluateEdgeParametricCoordinate(sampling[i]).x , selEdge.evaluateEdgeParametricCoordinate(sampling[i]).y , selEdge.evaluateEdgeParametricCoordinate(sampling[i]).z]) newSpline = apex.geometry.createCurve( target=_PointCollection, behavior=apex.geometry.CurveBehavior.Spline ) CircleDone = doCircle(diam=refDiameter) ## Move circle to a new point location _target = apex.EntityCollection() _target.append(CurrPart.getSurfaces()[0]) PathLength = sqrt(pow(PathPoints[0][0], 2) + pow(PathPoints[0][1], 2) + pow(PathPoints[0][2], 2)) apex.transformTranslate(target=_target, direction=[PathPoints[0][0], PathPoints[0][1], PathPoints[0][2]], distance=PathLength, makeCopy=False) ## Rotate the circle TurnAngle = angle([1, 0, 0], [a - b for a, b in zip(PathPoints[1], PathPoints[0])]) if TurnAngle == 180: TurnAngle = 0 apex.transformRotate(target=_target, axisDirection=cross([1, 0, 0], [a - b for a, b in zip(PathPoints[1], PathPoints[0])]), axisPoint=Point3D(PathPoints[0][0], PathPoints[0][1], PathPoints[0][2]), angle=TurnAngle, makeCopy=False) ## Do the sweep _target = apex.EntityCollection() _target.append(CurrPart.getSurfaces()[0]) _path = apex.EntityCollection() _path.append(CurrPart.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 ) CurrPart.getSolids()[0].update(enableTransparency=True, transparencyLevel=50) DelEntities = apex.EntityCollection() for Surface in CurrPart.getSurfaces(): DelEntities.append(Surface) apex.deleteEntities(DelEntities) if dict["extendRegion"] == "True": for Face in CurrPart.getSolids()[0].getFaces(): XSectionArea = 3.14159 * (refDiameter / 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=refDiameter, direction=[1.0, 1.0, 1.0] ) except: print("\nSweep failed!") NewPartName = apex.getPart(selEdge.getBody().getPath()).getName() + "_(failed)" ans = apex.getPart(selEdge.getBody().getPath()).update(name = NewPartName)
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)) model_1 = apex.currentModel() for Assembly in apex.selection.getCurrentSelection(): for Part in Assembly.getParts(True): _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() if Solid.getVisibility(): _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}_(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 Solid.hide() except: Part.update(name="{0}_(failed)".format(Part.getName())) numOfFailed += 1 apex.enableShowOutput() else: numOfInvisible += 1 print( "Found {4} parts with solids in total.\nThere were {0} parts not visible, only visible parts are processed: created {1} midsurfaces.\nParts with multple thickness: {2} \nFailed parts: {3}" .format(numOfInvisible, numOfCreated, numOfMultiple, numOfFailed, numOfParts))