Hide menu
Loading...
Searching...
No Matches
machining/feature_recognizer/feature_recognizer.py

Refer to the CNC Machining Feature Recognizer Example

feature_group.py

1# $Id$
2#
3# Copyright (C) 2008-2014, Roman Lygin. All rights reserved.
4# Copyright (C) 2014-2025, CADEX. All rights reserved.
5#
6# This file is part of the Manufacturing Toolkit software.
7#
8# You may use this file under the terms of the BSD license as follows:
9#
10# Redistribution and use in source and binary forms, with or without
11# modification, are permitted provided that the following conditions are met:
12# * Redistributions of source code must retain the above copyright notice,
13# this list of conditions and the following disclaimer.
14# * Redistributions in binary form must reproduce the above copyright notice,
15# this list of conditions and the following disclaimer in the documentation
16# and/or other materials provided with the distribution.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28# POSSIBILITY OF SUCH DAMAGE.
29
30from functools import cmp_to_key
31
32import manufacturingtoolkit.CadExMTK as mtk
33
34class Pair:
35 def __init__(self, theFirst: float, theSecond: float):
36 self.First = theFirst
37 self.Second = theSecond
38
39 def __repr__(self):
40 return f"Pair({self.First}, {self.Second})"
41
42 def __str__(self):
43 return f"{self.First:.5f} x {self.Second:.5f}"
44
45class Dimension:
46 def __init__(self, theX: float, theY: float, theZ: float):
47 self.X = theX
48 self.Y = theY
49 self.Z = theZ
50
51 def __repr__(self):
52 return f"Dimension({self.X}, {self.Y}, {self.Z})"
53
54 def __str__(self):
55 return f"{self.X:.5f} x {self.Y:.5f} x {self.Z:.5f}"
56
57class Direction:
58 def __init__(self, theX: float, theY: float, theZ: float):
59 self.X = theX
60 self.Y = theY
61 self.Z = theZ
62
63 def __repr__(self):
64 return f"Direction({self.X}, {self.Y}, {self.Z})"
65
66 def __str__(self):
67 return f"({self.X:.2f}, {self.Y:.2f}, {self.Z:.2f})"
68
69def CompareFeatures(theA: mtk.MTKBase_Feature, theB: mtk.MTKBase_Feature):
70 aComparator = mtk.MTKBase_FeatureComparator()
71 anALessThanB = aComparator(theA, theB)
72 if anALessThanB:
73 return -1
74
75 aBLessThanA = aComparator(theB, theA)
76 if aBLessThanA:
77 return 1
78
79 return 0
80
81class FeatureGroupManager:
82 def __init__(self):
83 self.__myGroups = []
84
85 def AddFeature(self, theGroupName: str, theSubgroupName: str, theHasParameters: bool, theFeature: mtk.MTKBase_Feature):
86 #find or create
87 aRes = -1
88 for i in range(len(self.__myGroups)):
89 aGroup = self.__myGroups[i]
90 if aGroup.myName == theGroupName:
91 aRes = i
92 break
93
94 if aRes == -1:
95 self.__myGroups.append(self.FeatureGroup(theGroupName, theSubgroupName, theHasParameters))
96 aRes = len(self.__myGroups) - 1
97
98 #update
99 aGroup = self.__myGroups[aRes]
100 aSubgroups = aGroup.myFeatureSubgroups
101 aSubgroups.Append(theFeature)
102
103 def Print(self, theFeatureType: str, thePrintFeatureParameters):
104 self.__myGroups.sort(key=cmp_to_key(self.__compare))
105
106 aTotalCount = 0
107 for i in self.__myGroups:
108 aFeatureCount = i.FeatureCount()
109 aTotalCount += aFeatureCount
110
111 print(" ", i.myName, ": ", aFeatureCount, sep="")
112
113 if not i.myHasParameters:
114 continue
115
116 aSubgroupName = i.mySubgroupName
117 for j in range(i.myFeatureSubgroups.Size()):
118 print(" ", i.myFeatureSubgroups.GetFeatureCount(j), " ", aSubgroupName, " with", sep="")
119 thePrintFeatureParameters(i.myFeatureSubgroups.GetFeature(j))
120
121 print("\n Total ", theFeatureType, ": ", aTotalCount, "\n", sep="")
122
123 @staticmethod
124 def PrintFeatureParameter(theName: str, theValue, theUnits: str):
125 print(" ", theName, ": ", theValue, " ", theUnits, sep = "")
126
127 class OrderedFeatureList:
128 def __init__(self):
129 self.__myList = []
130
131 def Append(self, theFeature: mtk.MTKBase_Feature):
132 anInsertIndex = 0
133 for i in self.__myList:
134 aRes = CompareFeatures(theFeature, i.Feature)
135 if aRes == 0:
136 i.Count += 1
137 anInsertIndex = -1
138 break
139 elif aRes < 0:
140 break
141
142 anInsertIndex += 1
143
144 if anInsertIndex >= 0:
145 self.__myList.insert(anInsertIndex, self.FeatureAndCountPair(theFeature))
146
147 def Size(self):
148 return len(self.__myList)
149
150 def GetFeature(self, theIndex: int):
151 return self.__GetFeatureAndCountPair(theIndex).Feature
152
153 def GetFeatureCount(self, theIndex: int):
154 return self.__GetFeatureAndCountPair(theIndex).Count
155
156 def __GetFeatureAndCountPair(self, theIndex: int):
157 return self.__myList[theIndex]
158
159 class FeatureAndCountPair:
160 def __init__(self, theFeature: mtk.MTKBase_Feature):
161 self.Feature = theFeature
162 self.Count = 1
163
164 class FeatureGroup:
165 def __init__(self, theName: str, theSubgroupName: str, theHasParameters: bool):
166 self.myName = theName
167 self.mySubgroupName = theSubgroupName
168 self.myHasParameters = theHasParameters
169 self.myFeatureSubgroups = FeatureGroupManager.OrderedFeatureList()
170
171 def FeatureCount(self):
172 aCount = 0
173 for i in range(self.myFeatureSubgroups.Size()):
174 aCount += self.myFeatureSubgroups.GetFeatureCount(i)
175 return aCount
176
177 @staticmethod
178 def __compare(theA: FeatureGroup, theB: FeatureGroup):
179 anAName = theA.myName
180 aBName = theB.myName
181 if anAName == aBName:
182 return 0
183
184 anAFeatureSubgroups = theA.myFeatureSubgroups
185 aBFeatureSubgroups = theB.myFeatureSubgroups
186 if (not anAFeatureSubgroups) or (not aBFeatureSubgroups):
187 if anAName < aBName:
188 return -1
189 else:
190 return 1
191
192 anAFeature = anAFeatureSubgroups.GetFeature(0)
193 aBFeature = aBFeatureSubgroups.GetFeature(0)
194 return CompareFeatures(anAFeature, aBFeature)

shape_processor.py

1# $Id$
2#
3# Copyright (C) 2008-2014, Roman Lygin. All rights reserved.
4# Copyright (C) 2014-2025, CADEX. All rights reserved.
5#
6# This file is part of the Manufacturing Toolkit software.
7#
8# You may use this file under the terms of the BSD license as follows:
9#
10# Redistribution and use in source and binary forms, with or without
11# modification, are permitted provided that the following conditions are met:
12# * Redistributions of source code must retain the above copyright notice,
13# this list of conditions and the following disclaimer.
14# * Redistributions in binary form must reproduce the above copyright notice,
15# this list of conditions and the following disclaimer in the documentation
16# and/or other materials provided with the distribution.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28# POSSIBILITY OF SUCH DAMAGE.
29
30from abc import abstractmethod
31
32import manufacturingtoolkit.CadExMTK as mtk
33
34class ShapeProcessor(mtk.ModelData_ModelElementVoidVisitor):
35 def __init__(self):
36 super().__init__()
37 self.myPartIndex = 0
38
39 def VisitPart(self, thePart: mtk.ModelData_Part):
40 aPartName = "noname" if thePart.Name().IsEmpty() else thePart.Name()
41
42 aBodyList = thePart.Bodies()
43 i = 0
44 for aBody in aBodyList:
45 aShapeIt = mtk.ModelData_ShapeIterator(aBody)
46 for aShape in aShapeIt:
47 if aShape.Type() == mtk.ShapeType_Solid:
48 print("Part #", self.myPartIndex, " [\"", aPartName, "\"] - solid #", i, " has:", sep="")
49 i += 1
50 self.ProcessSolid(mtk.ModelData_Solid.Cast(aShape))
51 elif aShape.Type() == mtk.ShapeType_Shell:
52 print("Part #", self.myPartIndex, " [\"", aPartName, "\"] - shell #", i, " has:", sep="")
53 i += 1
54 self.ProcessShell(mtk.ModelData_Shell.Cast (aShape))
55 self.myPartIndex += 1
56
57 @abstractmethod
58 def ProcessSolid(self, theSolid: mtk.ModelData_Solid):
59 pass
60
61 @abstractmethod
62 def ProcessShell(self, theShell: mtk.ModelData_Shell):
63 pass
64
65class SolidProcessor(mtk.ModelData_ModelElementVoidVisitor):
66 def __init__(self):
67 super().__init__()
68 self.myPartIndex = 0
69
70 def VisitPart(self, thePart: mtk.ModelData_Part):
71 aPartName = "noname" if thePart.Name().IsEmpty() else thePart.Name()
72
73 aBodyList = thePart.Bodies()
74 i = 0
75 for aBody in aBodyList:
76 aShapeIt = mtk.ModelData_ShapeIterator(aBody)
77 for aShape in aShapeIt:
78 if aShape.Type() == mtk.ShapeType_Solid:
79 print("Part #", self.myPartIndex, " [\"", aPartName, "\"] - solid #", i, " has:", sep="")
80 i += 1
81 self.ProcessSolid (mtk.ModelData_Solid.Cast (aShape))
82 self.myPartIndex += 1
83
84 @abstractmethod
85 def ProcessSolid(self, theSolid: mtk.ModelData_Solid):
86 pass

feature_recognizer.py

1# $Id$
2#
3# Copyright (C) 2008-2014, Roman Lygin. All rights reserved.
4# Copyright (C) 2014-2025, CADEX. All rights reserved.
5#
6# This file is part of the Manufacturing Toolkit software.
7#
8# You may use this file under the terms of the BSD license as follows:
9#
10# Redistribution and use in source and binary forms, with or without
11# modification, are permitted provided that the following conditions are met:
12# * Redistributions of source code must retain the above copyright notice,
13# this list of conditions and the following disclaimer.
14# * Redistributions in binary form must reproduce the above copyright notice,
15# this list of conditions and the following disclaimer in the documentation
16# and/or other materials provided with the distribution.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28# POSSIBILITY OF SUCH DAMAGE.
29
30import os
31import sys
32
33from pathlib import Path
34
35import manufacturingtoolkit.CadExMTK as mtk
36
37sys.path.append(os.path.abspath(os.path.dirname(Path(__file__).resolve()) + "/../../"))
38sys.path.append(os.path.abspath(os.path.dirname(Path(__file__).resolve()) + "/../../helpers/"))
39
40import mtk_license as license
41
42import shape_processor
43import feature_group
44
45def FaceTypeToString(theType):
46 aFaceTypeMap = {
47 mtk.Machining_FT_FlatFaceMilled: "Flat Face Milled Face(s)",
48 mtk.Machining_FT_FlatSideMilled: "Flat Side Milled Face(s)",
49 mtk.Machining_FT_CurvedMilled: "Curved Milled Face(s)",
50 mtk.Machining_FT_CircularMilled: "Circular Milled Face(s)",
51 mtk.Machining_FT_Deburr: "Deburr Face(s)",
52 mtk.Machining_FT_ConvexProfileEdgeMilling: "Convex Profile Edge Milling Face(s)",
53 mtk.Machining_FT_ConcaveFilletEdgeMilling: "Concave Fillet Edge Milling Face(s)",
54 mtk.Machining_FT_FlatMilled: "Flat Milled Face(s)",
55 mtk.Machining_FT_TurnDiameter: "Turn Diameter Face(s)",
56 mtk.Machining_FT_TurnForm: "Turn Form Face(s)",
57 mtk.Machining_FT_TurnFace: "Turn Face Face(s)",
58 mtk.Machining_FT_Bore: "Bore Face(s)"
59 }
60
61 if theType in aFaceTypeMap:
62 return aFaceTypeMap[theType]
63 else:
64 return "Face(s)"
65
66def PocketTypeToString(theType):
67 aPocketTypeMap = {
68 mtk.Machining_PT_Closed: "Closed Pocket(s)",
69 mtk.Machining_PT_Open: "Open Pocket(s)",
70 mtk.Machining_PT_Through: "Through Pocket(s)"
71 }
72
73 if theType in aPocketTypeMap:
74 return aPocketTypeMap[theType]
75 else:
76 return "Pocket(s)"
77
78def HoleTypeToString(theType):
79 aHoleTypeMap = {
80 mtk.Machining_HT_Through: "Through Hole(s)",
81 mtk.Machining_HT_FlatBottom: "Flat Bottom Hole(s)",
82 mtk.Machining_HT_Blind: "Blind Hole(s)",
83 mtk.Machining_HT_Partial: "Partial Hole(s)"
84 }
85
86 if theType in aHoleTypeMap:
87 return aHoleTypeMap[theType]
88 else:
89 return "Hole(s)"
90
91def GroupByParameters(theFeatures: mtk.MTKBase_FeatureList, theManager: feature_group.FeatureGroupManager):
92 for aFeature in theFeatures:
93 if mtk.Machining_TurningFace.CompareType(aFeature):
94 aTurningFace = mtk.Machining_TurningFace.Cast(aFeature)
95 theManager.AddFeature(FaceTypeToString (aTurningFace.Type()), "Turning Face(s)", True, aFeature)
96 elif mtk.Machining_Face.CompareType(aFeature):
97 aFace = mtk.Machining_Face.Cast(aFeature)
98 theManager.AddFeature(FaceTypeToString (aFace.Type()), "", False, aFeature)
99 elif mtk.Machining_Countersink.CompareType(aFeature):
100 theManager.AddFeature("Countersink(s)", "Countersink(s)", True, aFeature)
101 elif mtk.Machining_Hole.CompareType(aFeature):
102 aHole = mtk.Machining_Hole.Cast(aFeature)
103 theManager.AddFeature(HoleTypeToString (aHole.Type()), "Hole(s)", True, aFeature)
104 elif mtk.Machining_SteppedHole.CompareType(aFeature):
105 aSteppedHole = mtk.Machining_SteppedHole.Cast(aFeature)
106 GroupByParameters(aSteppedHole.FeatureList(), theManager)
107 elif mtk.Machining_Pocket.CompareType(aFeature):
108 aPocket = mtk.Machining_Pocket.Cast(aFeature)
109 theManager.AddFeature(PocketTypeToString (aPocket.Type()), "", True, aFeature)
110 elif mtk.MTKBase_Boss.CompareType(aFeature):
111 theManager.AddFeature("Boss(es)", "Boss(es)", True, aFeature)
112
113def PrintFeatureParameters(theFeature: mtk.MTKBase_Feature):
114 if mtk.Machining_TurningFace.CompareType(theFeature):
115 aTurningFace = mtk.Machining_TurningFace.Cast(theFeature)
116 feature_group.FeatureGroupManager.PrintFeatureParameter("radius", aTurningFace.Radius(), "mm")
117 elif mtk.Machining_Face.CompareType(theFeature):
118 pass #no parameters
119 elif mtk.Machining_Countersink.CompareType(theFeature):
120 aCountersink = mtk.Machining_Countersink.Cast(theFeature)
121 anAxis = aCountersink.Axis().Axis()
122 aDirection = feature_group.Direction(anAxis.X(), anAxis.Y(), anAxis.Z())
123 feature_group.FeatureGroupManager.PrintFeatureParameter("radius", aCountersink.Radius(), "mm")
124 feature_group.FeatureGroupManager.PrintFeatureParameter("depth", aCountersink.Depth(), "mm")
125 feature_group.FeatureGroupManager.PrintFeatureParameter("axis", aDirection, "")
126 elif mtk.Machining_Hole.CompareType(theFeature):
127 aHole = mtk.Machining_Hole.Cast(theFeature)
128 anAxis = aHole.Axis().Axis()
129 aDirection = feature_group.Direction(anAxis.X(), anAxis.Y(), anAxis.Z())
130 feature_group.FeatureGroupManager.PrintFeatureParameter("radius", aHole.Radius(), "mm")
131 feature_group.FeatureGroupManager.PrintFeatureParameter("depth", aHole.Depth(), "mm")
132 feature_group.FeatureGroupManager.PrintFeatureParameter("axis", aDirection, "")
133 elif mtk.Machining_Pocket.CompareType(theFeature):
134 aPocket = mtk.Machining_Pocket.Cast(theFeature)
135 anAxis = aPocket.Axis().Direction()
136 aDirection = feature_group.Direction(anAxis.X(), anAxis.Y(), anAxis.Z())
137 feature_group.FeatureGroupManager.PrintFeatureParameter("length", aPocket.Length(), "mm")
138 feature_group.FeatureGroupManager.PrintFeatureParameter("width", aPocket.Width(), "mm")
139 feature_group.FeatureGroupManager.PrintFeatureParameter("depth", aPocket.Depth(), "mm")
140 feature_group.FeatureGroupManager.PrintFeatureParameter("axis", aDirection, "")
141 elif mtk.MTKBase_Boss.CompareType(theFeature):
142 aBoss = mtk.MTKBase_Boss.Cast(theFeature)
143 feature_group.FeatureGroupManager.PrintFeatureParameter("length", aBoss.Length(), "mm")
144 feature_group.FeatureGroupManager.PrintFeatureParameter("width", aBoss.Width(), "mm")
145 feature_group.FeatureGroupManager.PrintFeatureParameter("height", aBoss.Height(), "mm")
146
147def PrintFeatures(theFeatureList: mtk.MTKBase_FeatureList):
148 aManager = feature_group.FeatureGroupManager()
149 GroupByParameters (theFeatureList, aManager)
150 aManager.Print ("features", PrintFeatureParameters)
151
152class PartProcessor(shape_processor.SolidProcessor):
153 def __init__(self, theOperation): # Not imported swig: mtk.Machining_OperationType?
154 super().__init__()
155 self.myOperation = theOperation
156
157 def ProcessSolid(self, theSolid: mtk.ModelData_Solid):
158 aRecognizer = mtk.Machining_FeatureRecognizer()
159 aRecognizer.Parameters().SetOperation (self.myOperation)
160 aFeatureList = aRecognizer.Perform (theSolid)
161 PrintFeatures(aFeatureList)
162
163def PrintSupportedOperations():
164 print("Supported operations:")
165 print(" milling:\t CNC Machining Milling feature recognition")
166 print(" turning:\t CNC Machining Lathe+Milling feature recognition")
167
168def OperationType(theOperationStr: str):
169 aProcessMap = {
170 "milling": mtk.Machining_OT_Milling,
171 "turning": mtk.Machining_OT_LatheMilling
172 }
173
174 if theOperationStr in aProcessMap:
175 return aProcessMap[theOperationStr]
176 else:
177 return mtk.Machining_OT_Undefined
178
179def main(theSource: str, theOperationStr: str):
180 aKey = license.Value()
181
182 if not mtk.LicenseManager.Activate(aKey):
183 print("Failed to activate Manufacturing Toolkit license.")
184 return 1
185
186 aModel = mtk.ModelData_Model()
187 aReader = mtk.ModelData_ModelReader()
188
189 # Reading the file
190 if not aReader.Read(mtk.UTF16String(theSource), aModel):
191 print("Failed to open and convert the file " + theSource)
192 return 1
193
194 print("Model: ", aModel.Name(), "\n", sep="")
195
196 anOperation = OperationType(theOperationStr)
197 if anOperation == mtk.Machining_OT_Undefined:
198 print("Unsupported operation - ", theOperationStr, sep="")
199 print("Please use one of the following.")
200 PrintSupportedOperations()
201 return 1
202
203 # Processing
204 aPartProcessor = PartProcessor(anOperation)
205 aVisitor = mtk.ModelData_ModelElementUniqueVisitor(aPartProcessor)
206 aModel.Accept(aVisitor)
207
208 return 0
209
210if __name__ == "__main__":
211 if len(sys.argv) != 3:
212 print("Usage: : <input_file> <operation>, where:")
213 print(" <input_file> is a name of the file to be read")
214 print(" <operation> is a name of desired machining operation")
215 PrintSupportedOperations()
216 sys.exit()
217
218 aSource = os.path.abspath(sys.argv[1])
219 anOperation = sys.argv[2]
220
221 sys.exit(main(aSource, anOperation))