Exemplo n.º 1
0
    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!")
Exemplo n.º 2
0
    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!")
Exemplo n.º 3
0
def buildLapJoint(dict={}):
    # - Get the data from the dictionary
    HorizWidth = float(dict["HorizWidth"])
    HorizLength = float(dict["HorizLength"])
    HorizThick = float(dict["HorizThick"])
    VertHeight = float(dict["VertHeight"])
    VertLength = float(dict["VertLength"])
    VertThick = float(dict["VertThick"])

    ## Define max and min thickness
    if VertThick >= HorizThick:
        maxThick = VertThick
        minThick = HorizThick
    else:
        maxThick = HorizThick
        minThick = VertThick
    avgThick = (maxThick + minThick) / 2.0

    Sheet01 = apex.createPart()

    ParentAssy = model_1.createAssembly(name="LapJoint")

    # - Build the horizontal plate
    result = apex.geometry.createBoxByLocationOrientation(
        name='Sheet01',
        description='',
        length=HorizLength,  # Length
        height=HorizWidth,  # Width
        depth=HorizThick,  # 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='BottomSheet')

    # - Build the vertical plate
    Sheet02 = apex.createPart()
    result = apex.geometry.createBoxByLocationOrientation(
        name='Sheet02',
        description='',
        length=VertLength,  # Length
        height=VertHeight,  # Width
        depth=VertThick,  # Thickness
        origin=apex.Coordinate(0.0, 0.0, HorizThick),
        orientation=apex.construct.createOrientation(alpha=0.0,
                                                     beta=0.0,
                                                     gamma=0.0))
    res = Sheet02.setParent(ParentAssy)
    res = Sheet02.update(name='UpperSheet')

    # - Translate vertical plate to the middle of horizontal plate
    _translateSheet = apex.EntityCollection()
    _translateSheet.append(Sheet02.getSolids()[0])
    newEntities = apex.transformTranslate(target=_translateSheet,
                                          direction=[0.0, 1.0, 0.0],
                                          distance=(HorizWidth -
                                                    2.0 * HorizThick),
                                          makeCopy=False)

    # Save joint info for reference
    JointInfoAssy = model_1.createAssembly("Joint info")
    res = JointInfoAssy.createPart(name="Sheet 01 = {0}mm".format(HorizThick))
    res = JointInfoAssy.createPart(name="Sheet 02 = {0}mm".format(VertThick))
    res = JointInfoAssy.createPart(name="Width = {0}mm".format(HorizWidth))
    res = JointInfoAssy.createPart(name="Length = {0}mm".format(HorizLength))

    # Creating split regions
    ## Split sheet 01 (horizontal sheet)
    _target = apex.EntityCollection()
    _target.append(Sheet01.getSolids()[0])
    listOfDist = [-4.0, -5.0, -6.0]
    for cutDist in listOfDist:
        _plane = apex.construct.Plane(
            apex.construct.Point3D(0.0,
                                   (HorizWidth + cutDist * avgThick), 0.0),
            apex.construct.Vector3D(0.0, 1.0, 0.0))
        result = apex.geometry.splitWithPlane(
            target=_target,
            plane=_plane,
            splitBehavior=apex.geometry.GeometrySplitBehavior.Partition)

    ## Split sheet 02 (vertical sheet)
    _target = apex.EntityCollection()
    _target.append(Sheet02.getSolids()[0])
    listOfDist = [0.0, 2.0, 3.0]
    for cutDist in listOfDist:
        _plane = apex.construct.Plane(
            apex.construct.Point3D(0.0,
                                   (HorizWidth + cutDist * avgThick), 0.0),
            apex.construct.Vector3D(0.0, 1.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
        refPoint = apex.Coordinate(HorizLength / 2.0,
                                   HorizWidth - 2.0 * HorizThick, 0.0)
        proxSearch = apex.utility.ProximitySearch()
        ans = proxSearch.insertList(list(Sheet01.getSolids()[0].getCells()))
        resSearch = proxSearch.findNearestObjects(location=refPoint,
                                                  numObjects=2)

        cellsToMesh = apex.EntityCollection()
        for elem in resSearch.foundObjects():
            cellsToMesh.append(elem)

        _SweepFace = apex.EntityCollection()
        result = apex.mesh.createHexMesh(
            name="",
            target=cellsToMesh,
            meshSize=(minThick / 2),
            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=4)
        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 0.9 * HorizThick <= Edge.getLength(
                    ) <= 1.1 * HorizThick:
                        seedEdge.append(Edge)
                result = apex.mesh.createEdgeSeedUniformByNumber(
                    target=seedEdge, numberElementEdges=1)
        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,
                        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

        # - Meshing Sheet 02
        refPoint = apex.Coordinate(HorizLength / 2.0,
                                   HorizWidth - 2.0 * HorizThick, 0.0)
        proxSearch = apex.utility.ProximitySearch()
        ans = proxSearch.insertList(list(Sheet02.getSolids()[0].getCells()))
        resSearch = proxSearch.findNearestObjects(location=refPoint,
                                                  numObjects=2)

        cellsToMesh = apex.EntityCollection()
        for elem in resSearch.foundObjects():
            cellsToMesh.append(elem)

        _SweepFace = apex.EntityCollection()
        result = apex.mesh.createHexMesh(
            name="",
            target=cellsToMesh,
            meshSize=(minThick / 2),
            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=4)
        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 0.9 * VertThick <= Edge.getLength() <= 1.1 * VertThick:
                        seedEdge.append(Edge)
                        print(Edge.getLength())
                result = apex.mesh.createEdgeSeedUniformByNumber(
                    target=seedEdge, numberElementEdges=1)

        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,
                        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
Exemplo n.º 4
0
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


#############################################################################################################################
#############################################################################################################################
#############################################################################################################################
Exemplo n.º 5
0
def Slicer(solidBody="",
           cutPos=[],
           cutAngleDeg="",
           maxPointSpacing=0.0,
           pathToSaveFile=""):
    workingSolid = solidBody

    # -Collect all vertices before partitioning, so I know which ones were created after the cut
    allEdgesIDBefore = []
    for elem in workingSolid.getEdges():
        allEdgesIDBefore.append(elem.getId())

    # -Create cutting plane location and orientation for partitioning (currently cutting on XY-plane)
    _plane = apex.construct.Plane(
        apex.construct.Point3D(float(cutPos[0]), float(cutPos[1]),
                               float(cutPos[2])),
        apex.construct.Vector3D(cos(radians(cutAngleDeg)),
                                sin(radians(cutAngleDeg)), 0.000000))

    _target = apex.EntityCollection()
    _target.append(workingSolid)

    # -Create partition
    result = apex.geometry.splitWithPlane(
        target=_target,
        plane=_plane,
        splitBehavior=apex.geometry.GeometrySplitBehavior.Partition)

    # -Collect all vertices after partitioning, IDs of old vertices will not change
    allEdgesIDAfter = []
    for elem in workingSolid.getEdges():
        allEdgesIDAfter.append(elem.getId())

    # -Check which vertices were created by the partitioning operation
    newEdgesID = (list(set(allEdgesIDAfter) - set(allEdgesIDBefore)))
    newEdgesHeight = []
    for EdgeID in newEdgesID:
        newEdgesHeight.append(
            workingSolid.getEdge(id=int(EdgeID)).getMidPoint().z)

    sortedByHeight = [
        int(x) for _, x in sorted(zip(newEdgesHeight, newEdgesID))
    ]

    workingEdge = workingSolid.getEdge(id=sortedByHeight[-1])
    workingEdgeLength = workingEdge.getLength()

    # -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 DED slicing code"
    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 = "\n{0};true;{1};{2};{3};0.0;0.0;1.0".format(
            i + 1, trajInfo[i][0], trajInfo[i][1], trajInfo[i][2])
        trajBuild += lineBuild

    # -Write the trajectory file
    if pathToSaveFile:
        with open(pathToSaveFile, 'w') as newTrajFile:
            newTrajFile.write(trajBuild)
Exemplo n.º 6
0
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
        )
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
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)