ParseExcellon.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. from camlib import Geometry, grace
  9. import shapely.affinity as affinity
  10. from shapely.geometry import Point, LineString
  11. import numpy as np
  12. import re
  13. import logging
  14. import traceback
  15. from copy import deepcopy
  16. # import AppTranslation as fcTranslate
  17. import gettext
  18. import builtins
  19. if '_' not in builtins.__dict__:
  20. _ = gettext.gettext
  21. log = logging.getLogger('base')
  22. class Excellon(Geometry):
  23. """
  24. Here it is done all the Excellon parsing.
  25. *ATTRIBUTES*
  26. * ``tools`` (dict): The key is the tool name and the value is
  27. a dictionary specifying the tool:
  28. ================ ====================================
  29. Key Value
  30. ================ ====================================
  31. tooldia Diameter of the tool
  32. drills List that store the Shapely Points for drill points
  33. slots List that store the Shapely Points for slots. Each is a tuple: (start_point, stop_point
  34. data dictionary which holds the options for each tool
  35. solid_geometry Geometry list for each tool
  36. ================ ====================================
  37. """
  38. defaults = {
  39. "zeros": "L",
  40. "excellon_format_upper_mm": '3',
  41. "excellon_format_lower_mm": '3',
  42. "excellon_format_upper_in": '2',
  43. "excellon_format_lower_in": '4',
  44. "excellon_units": 'INCH',
  45. "geo_steps_per_circle": '64'
  46. }
  47. def __init__(self, zeros=None, excellon_format_upper_mm=None, excellon_format_lower_mm=None,
  48. excellon_format_upper_in=None, excellon_format_lower_in=None, excellon_units=None,
  49. geo_steps_per_circle=None):
  50. """
  51. The constructor takes no parameters.
  52. :return: Excellon object.
  53. :rtype: Excellon
  54. """
  55. self.decimals = self.app.decimals
  56. if geo_steps_per_circle is None:
  57. geo_steps_per_circle = int(Excellon.defaults['geo_steps_per_circle'])
  58. self.geo_steps_per_circle = int(geo_steps_per_circle)
  59. Geometry.__init__(self, geo_steps_per_circle=int(geo_steps_per_circle))
  60. # dictionary to store tools, see above for description
  61. self.tools = {}
  62. self.source_file = ''
  63. # it serve to flag if a start routing or a stop routing was encountered
  64. # if a stop is encounter and this flag is still 0 (so there is no stop for a previous start) issue error
  65. self.routing_flag = 1
  66. self.match_routing_start = None
  67. self.match_routing_stop = None
  68. # ## IN|MM -> Units are inherited from Geometry
  69. self.units = self.app.defaults['units']
  70. self.units_found = self.app.defaults['units']
  71. # Trailing "T" or leading "L" (default)
  72. # self.zeros = "T"
  73. self.zeros = zeros or self.defaults["zeros"]
  74. self.zeros_found = deepcopy(self.zeros)
  75. # this will serve as a default if the Excellon file has no info regarding of tool diameters (this info may be
  76. # in another file like for PCB WIzard ECAD software
  77. self.toolless_diam = 1.0
  78. # signal that the Excellon file has no tool diameter informations and the tools have bogus (random) diameter
  79. self.diameterless = False
  80. # Excellon format
  81. self.excellon_format_upper_in = excellon_format_upper_in or self.defaults["excellon_format_upper_in"]
  82. self.excellon_format_lower_in = excellon_format_lower_in or self.defaults["excellon_format_lower_in"]
  83. self.excellon_format_upper_mm = excellon_format_upper_mm or self.defaults["excellon_format_upper_mm"]
  84. self.excellon_format_lower_mm = excellon_format_lower_mm or self.defaults["excellon_format_lower_mm"]
  85. self.excellon_units = excellon_units or self.defaults["excellon_units"]
  86. self.excellon_units_found = None
  87. # detected Excellon format is stored here:
  88. self.excellon_format = None
  89. # Attributes to be included in serialization
  90. # Always append to it because it carries contents
  91. # from Geometry.
  92. self.ser_attrs += ['tools', 'zeros', 'excellon_format_upper_mm', 'excellon_format_lower_mm',
  93. 'excellon_format_upper_in', 'excellon_format_lower_in', 'excellon_units', 'source_file']
  94. # ### Patterns ####
  95. # Regex basics:
  96. # ^ - beginning
  97. # $ - end
  98. # *: 0 or more, +: 1 or more, ?: 0 or 1
  99. # M48 - Beginning of Part Program Header
  100. self.hbegin_re = re.compile(r'^M48$')
  101. # ;HEADER - Beginning of Allegro Program Header
  102. self.allegro_hbegin_re = re.compile(r'\;\s*(HEADER)')
  103. # M95 or % - End of Part Program Header
  104. # NOTE: % has different meaning in the body
  105. self.hend_re = re.compile(r'^(?:M95|%)$')
  106. # FMAT Excellon format
  107. # Ignored in the parser
  108. # self.fmat_re = re.compile(r'^FMAT,([12])$')
  109. # Uunits and possible Excellon zeros and possible Excellon format
  110. # INCH uses 6 digits
  111. # METRIC uses 5/6
  112. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?,?(\d*\.\d+)?.*$')
  113. # Tool definition/parameters (?= is look-ahead
  114. # NOTE: This might be an overkill!
  115. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  116. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  117. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  118. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  119. self.toolset_re = re.compile(r'^T(\d+)(?=.*C,?(\d*\.?\d*))?' +
  120. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  121. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  122. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  123. self.detect_gcode_re = re.compile(r'^G2([01])$')
  124. # Tool select
  125. # Can have additional data after tool number but
  126. # is ignored if present in the header.
  127. # Warning: This will match toolset_re too.
  128. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  129. self.toolsel_re = re.compile(r'^T(\d+)')
  130. # Headerless toolset
  131. # self.toolset_hl_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))')
  132. self.toolset_hl_re = re.compile(r'^T(\d+)(?:.?C(\d+\.?\d*))?')
  133. # Comment
  134. self.comm_re = re.compile(r'^;(.*)$')
  135. # Absolute/Incremental G90/G91
  136. self.absinc_re = re.compile(r'^G9([01])$')
  137. # Modes of operation
  138. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  139. self.modes_re = re.compile(r'^G0([012345])')
  140. # Measuring mode
  141. # 1-metric, 2-inch
  142. self.meas_re = re.compile(r'^M7([12])$')
  143. # Coordinates
  144. # self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  145. # self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  146. coordsperiod_re_string = r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]'
  147. self.coordsperiod_re = re.compile(coordsperiod_re_string)
  148. coordsnoperiod_re_string = r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]'
  149. self.coordsnoperiod_re = re.compile(coordsnoperiod_re_string)
  150. # Slots parsing
  151. slots_re_string = r'^([^G]+)G85(.*)$'
  152. self.slots_re = re.compile(slots_re_string)
  153. # R - Repeat hole (# times, X offset, Y offset)
  154. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  155. # Various stop/pause commands
  156. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  157. # Allegro Excellon format support
  158. self.tool_units_re = re.compile(r'(\;\s*Holesize \d+.\s*\=\s*(\d+.\d+).*(MILS|MM))')
  159. # Altium Excellon format support
  160. # it's a comment like this: ";FILE_FORMAT=2:5"
  161. self.altium_format = re.compile(r'^;\s*(?:FILE_FORMAT)?(?:Format)?[=|:]\s*(\d+)[:|.](\d+).*$')
  162. # Parse coordinates
  163. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  164. # Repeating command
  165. self.repeat_re = re.compile(r'R(\d+)')
  166. def parse_file(self, filename=None, file_obj=None):
  167. """
  168. Reads the specified file as array of lines as passes it to ``parse_lines()``.
  169. :param filename: The file to be read and parsed.
  170. :param file_obj:
  171. :type filename: str
  172. :return: None
  173. """
  174. if file_obj:
  175. estr = file_obj
  176. else:
  177. if filename is None:
  178. return "fail"
  179. efile = open(filename, 'r')
  180. estr = efile.readlines()
  181. efile.close()
  182. try:
  183. self.parse_lines(estr)
  184. except Exception:
  185. return "fail"
  186. def parse_lines(self, elines):
  187. """
  188. Main Excellon parser.
  189. :param elines: List of strings, each being a line of Excellon code.
  190. :type elines: list
  191. :return: None
  192. """
  193. # State variables
  194. current_tool = ""
  195. in_header = False
  196. headerless = False
  197. current_x = None
  198. current_y = None
  199. slot_current_x = None
  200. slot_current_y = None
  201. name_tool = 0
  202. allegro_warning = False
  203. line_units_found = False
  204. repeating_x = 0
  205. repeating_y = 0
  206. repeat = 0
  207. line_units = ''
  208. # ## Parsing starts here ## ##
  209. line_num = 0 # Line number
  210. eline = ""
  211. try:
  212. for eline in elines:
  213. if self.app.abort_flag:
  214. # graceful abort requested by the user
  215. raise grace
  216. line_num += 1
  217. # log.debug("%3d %s" % (line_num, str(eline)))
  218. self.source_file += eline
  219. # Cleanup lines
  220. eline = eline.strip(' \r\n')
  221. # Excellon files and Gcode share some extensions therefore if we detect G20 or G21 it's GCODe
  222. # and we need to exit from here
  223. if self.detect_gcode_re.search(eline):
  224. log.warning("This is GCODE mark: %s" % eline)
  225. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_('This is GCODE mark'), eline))
  226. return
  227. # Header Begin (M48) #
  228. if self.hbegin_re.search(eline):
  229. in_header = True
  230. headerless = False
  231. log.warning("Found start of the header: %s" % eline)
  232. continue
  233. # Allegro Header Begin (;HEADER) #
  234. if self.allegro_hbegin_re.search(eline):
  235. in_header = True
  236. allegro_warning = True
  237. log.warning("Found ALLEGRO start of the header: %s" % eline)
  238. continue
  239. # Search for Header End #
  240. # Since there might be comments in the header that include header end char (% or M95)
  241. # we ignore the lines starting with ';' that contains such header end chars because it is not a
  242. # real header end.
  243. if self.comm_re.search(eline):
  244. match = self.tool_units_re.search(eline)
  245. if match:
  246. if line_units_found is False:
  247. line_units_found = True
  248. line_units = match.group(3)
  249. self.convert_units({"MILS": "IN", "MM": "MM"}[line_units])
  250. log.warning("Type of Allegro UNITS found inline in comments: %s" % line_units)
  251. if match.group(2):
  252. name_tool += 1
  253. # ---------- add a TOOL ------------ #
  254. if name_tool not in self.tools:
  255. self.tools[name_tool] = {}
  256. if line_units == 'MILS':
  257. spec = {
  258. 'tooldia': (float(match.group(2)) / 1000)
  259. }
  260. self.tools[name_tool]['tooldia'] = (float(match.group(2)) / 1000)
  261. log.debug("Tool definition: %d %s" % (name_tool, spec))
  262. else:
  263. spec = {
  264. 'tooldia': float(match.group(2))
  265. }
  266. self.tools[name_tool]['tooldia'] = float(match.group(2))
  267. log.debug("Tool definition: %d %s" % (name_tool, spec))
  268. spec['solid_geometry'] = []
  269. continue
  270. # search for Altium Excellon Format / Sprint Layout who is included as a comment
  271. match = self.altium_format.search(eline)
  272. if match:
  273. self.excellon_format_upper_mm = match.group(1)
  274. self.excellon_format_lower_mm = match.group(2)
  275. self.excellon_format_upper_in = match.group(1)
  276. self.excellon_format_lower_in = match.group(2)
  277. log.warning("Excellon format preset found in comments: %s:%s" %
  278. (match.group(1), match.group(2)))
  279. continue
  280. else:
  281. log.warning("Line ignored, it's a comment: %s" % eline)
  282. else:
  283. if self.hend_re.search(eline):
  284. if in_header is False or bool(self.tools) is False:
  285. log.warning("Found end of the header but there is no header: %s" % eline)
  286. log.warning("The only useful data in header are tools, units and format.")
  287. log.warning("Therefore we will create units and format based on defaults.")
  288. headerless = True
  289. try:
  290. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.excellon_units])
  291. except Exception as e:
  292. log.warning("Units could not be converted: %s" % str(e))
  293. in_header = False
  294. # for Allegro type of Excellons we reset name_tool variable so we can reuse it for toolchange
  295. if allegro_warning is True:
  296. name_tool = 0
  297. log.warning("Found end of the header: %s" % eline)
  298. '''
  299. In case that the units were not found in the header, we have two choices:
  300. - one is to use the default value in the App Preferences
  301. - the other is to make an evaluation based on a threshold
  302. we process here the self.tools list and make a list with tools with diameter less or equal
  303. with 0.1 and a list with tools with value greater than 0.1, 0.1 being the threshold value.
  304. Most tools in Excellon are greater than 0.1mm therefore if most of the tools are under this
  305. value it is safe to assume that the units are in INCH
  306. '''
  307. greater_tools = set()
  308. lower_tools = set()
  309. if not self.excellon_units_found and self.tools:
  310. for tool in self.tools:
  311. tool_dia = float(self.tools[tool]['tooldia'])
  312. lower_tools.add(tool_dia) if tool_dia <= 0.1 else greater_tools.add(tool_dia)
  313. assumed_units = "IN" if len(lower_tools) > len(greater_tools) else "MM"
  314. self.units = assumed_units
  315. continue
  316. # ## Alternative units format M71/M72
  317. # Supposed to be just in the body (yes, the body)
  318. # but some put it in the header (PADS for example).
  319. # Will detect anywhere. Occurrence will change the
  320. # object's units.
  321. match = self.meas_re.match(eline)
  322. if match:
  323. self.units = {"1": "MM", "2": "IN"}[match.group(1)]
  324. # Modified for issue #80
  325. log.debug("ALternative M71/M72 units found, before conversion: %s" % self.units)
  326. self.convert_units(self.units)
  327. log.debug("ALternative M71/M72 units found, after conversion: %s" % self.units)
  328. if self.units == 'MM':
  329. log.warning("Excellon format preset is: %s:%s" %
  330. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  331. else:
  332. log.warning("Excellon format preset is: %s:%s" %
  333. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  334. continue
  335. # ### Body ####
  336. if not in_header:
  337. # ## Tool change ###
  338. match = self.toolsel_re.search(eline)
  339. if match:
  340. current_tool = int(match.group(1))
  341. log.debug("Tool change: %s" % current_tool)
  342. if bool(headerless):
  343. match = self.toolset_hl_re.search(eline)
  344. if match:
  345. name = int(match.group(1))
  346. try:
  347. diam = float(match.group(2))
  348. except Exception:
  349. # it's possible that tool definition has only tool number and no diameter info
  350. # (those could be in another file like PCB Wizard do)
  351. # then match.group(2) = None and float(None) will create the exception
  352. # the below construction is so each tool will have a slightly different diameter
  353. # starting with a default value, to allow Excellon editing after that
  354. self.diameterless = True
  355. self.app.inform.emit('[WARNING] %s%s %s' %
  356. (_("No tool diameter info's. See shell.\n"
  357. "A tool change event: T"),
  358. str(current_tool),
  359. _("was found but the Excellon file "
  360. "have no informations regarding the tool "
  361. "diameters therefore the application will try to load it "
  362. "by using some 'fake' diameters.\n"
  363. "The user needs to edit the resulting Excellon object and "
  364. "change the diameters to reflect the real diameters.")
  365. )
  366. )
  367. if self.excellon_units == 'MM':
  368. diam = self.toolless_diam + (int(current_tool) - 1) / 100
  369. else:
  370. diam = (self.toolless_diam + (int(current_tool) - 1) / 100) / 25.4
  371. # ---------- add a TOOL ------------ #
  372. spec = {"tooldia": diam, 'solid_geometry': []}
  373. if name not in self.tools:
  374. self.tools[name] = {}
  375. self.tools[name]['tooldia'] = diam
  376. self.tools[name]['solid_geometry'] = []
  377. log.debug("Tool definition out of header: %s %s" % (name, spec))
  378. continue
  379. # ## Allegro Type Tool change ###
  380. if allegro_warning is True:
  381. match = self.absinc_re.search(eline)
  382. match1 = self.stop_re.search(eline)
  383. if match or match1:
  384. name_tool += 1
  385. current_tool = name_tool
  386. log.debug("Tool change for Allegro type of Excellon: %d" % current_tool)
  387. continue
  388. # ## Slots parsing for drilled slots (contain G85)
  389. # a Excellon drilled slot line may look like this:
  390. # X01125Y0022244G85Y0027756
  391. match = self.slots_re.search(eline)
  392. if match:
  393. # signal that there are milling slots operations
  394. self.defaults['excellon_drills'] = False
  395. # the slot start coordinates group is to the left of G85 command (group(1) )
  396. # the slot stop coordinates group is to the right of G85 command (group(2) )
  397. start_coords_match = match.group(1)
  398. stop_coords_match = match.group(2)
  399. # Slot coordinates without period # ##
  400. # get the coordinates for slot start and for slot stop into variables
  401. start_coords_noperiod = self.coordsnoperiod_re.search(start_coords_match)
  402. stop_coords_noperiod = self.coordsnoperiod_re.search(stop_coords_match)
  403. if start_coords_noperiod:
  404. try:
  405. slot_start_x = self.parse_number(start_coords_noperiod.group(1))
  406. slot_current_x = slot_start_x
  407. except TypeError:
  408. slot_start_x = slot_current_x
  409. except Exception:
  410. return
  411. try:
  412. slot_start_y = self.parse_number(start_coords_noperiod.group(2))
  413. slot_current_y = slot_start_y
  414. except TypeError:
  415. slot_start_y = slot_current_y
  416. except Exception:
  417. return
  418. try:
  419. slot_stop_x = self.parse_number(stop_coords_noperiod.group(1))
  420. slot_current_x = slot_stop_x
  421. except TypeError:
  422. slot_stop_x = slot_current_x
  423. except Exception:
  424. return
  425. try:
  426. slot_stop_y = self.parse_number(stop_coords_noperiod.group(2))
  427. slot_current_y = slot_stop_y
  428. except TypeError:
  429. slot_stop_y = slot_current_y
  430. except Exception:
  431. return
  432. if (slot_start_x is None or slot_start_y is None or
  433. slot_stop_x is None or slot_stop_y is None):
  434. log.error("Slots are missing some or all coordinates.")
  435. continue
  436. # we have a slot
  437. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  438. slot_start_y, slot_stop_x,
  439. slot_stop_y]))
  440. # store current tool diameter as slot diameter
  441. slot_dia = 0.05
  442. try:
  443. slot_dia = float(self.tools[current_tool]['tooldia'])
  444. except Exception:
  445. pass
  446. log.debug(
  447. 'Milling/Drilling slot with tool %s, diam=%f' % (
  448. current_tool,
  449. slot_dia
  450. )
  451. )
  452. # ---------- add a slot ------------ #
  453. slot = (
  454. Point(slot_start_x, slot_start_y),
  455. Point(slot_stop_x, slot_stop_y)
  456. )
  457. if current_tool not in self.tools:
  458. self.tools[current_tool] = {}
  459. if 'slots' in self.tools[current_tool]:
  460. self.tools[current_tool]['slots'].apend(slot)
  461. else:
  462. self.tools[current_tool]['slots'] = [slot]
  463. continue
  464. # Slot coordinates with period: Use literally. ###
  465. # get the coordinates for slot start and for slot stop into variables
  466. start_coords_period = self.coordsperiod_re.search(start_coords_match)
  467. stop_coords_period = self.coordsperiod_re.search(stop_coords_match)
  468. if start_coords_period:
  469. try:
  470. slot_start_x = float(start_coords_period.group(1))
  471. slot_current_x = slot_start_x
  472. except TypeError:
  473. slot_start_x = slot_current_x
  474. except Exception:
  475. return
  476. try:
  477. slot_start_y = float(start_coords_period.group(2))
  478. slot_current_y = slot_start_y
  479. except TypeError:
  480. slot_start_y = slot_current_y
  481. except Exception:
  482. return
  483. try:
  484. slot_stop_x = float(stop_coords_period.group(1))
  485. slot_current_x = slot_stop_x
  486. except TypeError:
  487. slot_stop_x = slot_current_x
  488. except Exception:
  489. return
  490. try:
  491. slot_stop_y = float(stop_coords_period.group(2))
  492. slot_current_y = slot_stop_y
  493. except TypeError:
  494. slot_stop_y = slot_current_y
  495. except Exception:
  496. return
  497. if (slot_start_x is None or slot_start_y is None or
  498. slot_stop_x is None or slot_stop_y is None):
  499. log.error("Slots are missing some or all coordinates.")
  500. continue
  501. # we have a slot
  502. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  503. slot_start_y, slot_stop_x,
  504. slot_stop_y]))
  505. # store current tool diameter as slot diameter
  506. slot_dia = 0.05
  507. try:
  508. slot_dia = float(self.tools[current_tool]['tooldia'])
  509. except Exception:
  510. pass
  511. log.debug(
  512. 'Milling/Drilling slot with tool %s, diam=%f' % (
  513. current_tool,
  514. slot_dia
  515. )
  516. )
  517. # ---------- add a Slot ------------ #
  518. slot = (
  519. Point(slot_start_x, slot_start_y),
  520. Point(slot_stop_x, slot_stop_y)
  521. )
  522. if current_tool not in self.tools:
  523. self.tools[current_tool] = {}
  524. if 'slots' in self.tools[current_tool]:
  525. self.tools[current_tool]['slots'].apend(slot)
  526. else:
  527. self.tools[current_tool]['slots'] = [slot]
  528. continue
  529. # ## Coordinates without period # ##
  530. match = self.coordsnoperiod_re.search(eline)
  531. if match:
  532. matchr = self.repeat_re.search(eline)
  533. if matchr: # if we have a repeat command
  534. repeat = int(matchr.group(1))
  535. if match.group(1):
  536. repeating_x = self.parse_number(match.group(1))
  537. else:
  538. repeating_x = 0
  539. if match.group(2):
  540. repeating_y = self.parse_number(match.group(2))
  541. else:
  542. repeating_y = 0
  543. coordx = current_x
  544. coordy = current_y
  545. while repeat > 0:
  546. if repeating_x:
  547. coordx += repeating_x
  548. if repeating_y:
  549. coordy += repeating_y
  550. # ---------- add a Drill ------------ #
  551. if current_tool not in self.tools:
  552. self.tools[current_tool] = {}
  553. if 'drills' in self.tools[current_tool]:
  554. self.tools[current_tool]['drills'].append(Point((coordx, coordy)))
  555. else:
  556. self.tools[current_tool]['drills'] = [Point((coordx, coordy))]
  557. repeat -= 1
  558. current_x = coordx
  559. current_y = coordy
  560. continue
  561. else: # those are normal coordinates
  562. try:
  563. x = self.parse_number(match.group(1))
  564. current_x = x
  565. except TypeError:
  566. x = current_x
  567. except Exception:
  568. return
  569. try:
  570. y = self.parse_number(match.group(2))
  571. current_y = y
  572. except TypeError:
  573. y = current_y
  574. except Exception:
  575. return
  576. if x is None or y is None:
  577. log.error("Missing coordinates")
  578. continue
  579. # ## Excellon Routing parse
  580. if len(re.findall("G00", eline)) > 0:
  581. self.match_routing_start = 'G00'
  582. # signal that there are milling slots operations
  583. self.defaults['excellon_drills'] = False
  584. self.routing_flag = 0
  585. slot_start_x = x
  586. slot_start_y = y
  587. continue
  588. if self.routing_flag == 0:
  589. if len(re.findall("G01", eline)) > 0:
  590. self.match_routing_stop = 'G01'
  591. # signal that there are milling slots operations
  592. self.defaults['excellon_drills'] = False
  593. self.routing_flag = 1
  594. slot_stop_x = x
  595. slot_stop_y = y
  596. # ---------- add a Slot ------------ #
  597. slot = (
  598. Point(slot_start_x, slot_start_y),
  599. Point(slot_stop_x, slot_stop_y)
  600. )
  601. if current_tool not in self.tools:
  602. self.tools[current_tool] = {}
  603. if 'slots' in self.tools[current_tool]:
  604. self.tools[current_tool]['slots'].apend(slot)
  605. else:
  606. self.tools[current_tool]['slots'] = [slot]
  607. continue
  608. if self.match_routing_start is None and self.match_routing_stop is None:
  609. # signal that there are drill operations
  610. self.defaults['excellon_drills'] = True
  611. # ---------- add a Drill ------------ #
  612. if current_tool not in self.tools:
  613. self.tools[current_tool] = {}
  614. if 'drills' in self.tools[current_tool]:
  615. self.tools[current_tool]['drills'].append(Point((x, y)))
  616. else:
  617. self.tools[current_tool]['drills'] = [Point((x, y))]
  618. # log.debug("{:15} {:8} {:8}".format(eline, x, y))
  619. continue
  620. # ## Coordinates with period: Use literally. # ##
  621. match = self.coordsperiod_re.search(eline)
  622. if match:
  623. matchr = self.repeat_re.search(eline)
  624. if matchr:
  625. repeat = int(matchr.group(1))
  626. if match:
  627. # signal that there are drill operations
  628. self.defaults['excellon_drills'] = True
  629. try:
  630. x = float(match.group(1))
  631. repeating_x = current_x
  632. current_x = x
  633. except TypeError:
  634. x = current_x
  635. repeating_x = 0
  636. try:
  637. y = float(match.group(2))
  638. repeating_y = current_y
  639. current_y = y
  640. except TypeError:
  641. y = current_y
  642. repeating_y = 0
  643. if x is None or y is None:
  644. log.error("Missing coordinates")
  645. continue
  646. # ## Excellon Routing parse
  647. if len(re.findall("G00", eline)) > 0:
  648. self.match_routing_start = 'G00'
  649. # signal that there are milling slots operations
  650. self.defaults['excellon_drills'] = False
  651. self.routing_flag = 0
  652. slot_start_x = x
  653. slot_start_y = y
  654. continue
  655. if self.routing_flag == 0:
  656. if len(re.findall("G01", eline)) > 0:
  657. self.match_routing_stop = 'G01'
  658. # signal that there are milling slots operations
  659. self.defaults['excellon_drills'] = False
  660. self.routing_flag = 1
  661. slot_stop_x = x
  662. slot_stop_y = y
  663. # ---------- add a Slot ------------ #
  664. slot = (
  665. Point(slot_start_x, slot_start_y),
  666. Point(slot_stop_x, slot_stop_y)
  667. )
  668. if current_tool not in self.tools:
  669. self.tools[current_tool] = {}
  670. if 'slots' in self.tools[current_tool]:
  671. self.tools[current_tool]['slots'].apend(slot)
  672. else:
  673. self.tools[current_tool]['slots'] = [slot]
  674. continue
  675. if self.match_routing_start is None and self.match_routing_stop is None:
  676. # signal that there are drill operations
  677. if repeat == 0:
  678. # signal that there are drill operations
  679. self.defaults['excellon_drills'] = True
  680. # ---------- add a Drill ------------ #
  681. if current_tool not in self.tools:
  682. self.tools[current_tool] = {}
  683. if 'drills' in self.tools[current_tool]:
  684. self.tools[current_tool]['drills'].append(Point((x, y)))
  685. else:
  686. self.tools[current_tool]['drills'] = [Point((x, y))]
  687. else:
  688. coordx = x
  689. coordy = y
  690. while repeat > 0:
  691. if repeating_x:
  692. coordx = (repeat * x) + repeating_x
  693. if repeating_y:
  694. coordy = (repeat * y) + repeating_y
  695. # ---------- add a Drill ------------ #
  696. if current_tool not in self.tools:
  697. self.tools[current_tool] = {}
  698. if 'drills' in self.tools[current_tool]:
  699. self.tools[current_tool]['drills'].append(Point((coordx, coordy)))
  700. else:
  701. self.tools[current_tool]['drills'] = [Point((coordx, coordy))]
  702. repeat -= 1
  703. repeating_x = repeating_y = 0
  704. # log.debug("{:15} {:8} {:8}".format(eline, x, y))
  705. continue
  706. # ### Header ####
  707. if in_header:
  708. # ## Tool definitions # ##
  709. match = self.toolset_re.search(eline)
  710. if match:
  711. # ---------- add a TOOL ------------ #
  712. name = int(match.group(1))
  713. spec = {"C": float(match.group(2)), 'solid_geometry': []}
  714. if name not in self.tools:
  715. self.tools[name] = {}
  716. self.tools[name]['tooldia'] = float(match.group(2))
  717. self.tools[name]['solid_geometry'] = []
  718. log.debug("Tool definition: %s %s" % (name, spec))
  719. continue
  720. # ## Units and number format # ##
  721. match = self.units_re.match(eline)
  722. if match:
  723. self.units = {"METRIC": "MM", "INCH": "IN"}[match.group(1)]
  724. self.excellon_units_found = self.units
  725. self.zeros = match.group(2) # "T" or "L". Might be empty
  726. self.excellon_format = match.group(3)
  727. if self.excellon_format:
  728. upper = len(self.excellon_format.partition('.')[0])
  729. lower = len(self.excellon_format.partition('.')[2])
  730. if self.units == 'MM':
  731. self.excellon_format_upper_mm = upper
  732. self.excellon_format_lower_mm = lower
  733. else:
  734. self.excellon_format_upper_in = upper
  735. self.excellon_format_lower_in = lower
  736. # Modified for issue #80
  737. log.warning("UNITS found inline - Value before conversion: %s" % self.units)
  738. self.convert_units(self.units)
  739. log.warning("UNITS found inline - Value after conversion: %s" % self.units)
  740. if self.units == 'MM':
  741. log.warning("Excellon format preset is: %s:%s" %
  742. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  743. else:
  744. log.warning("Excellon format preset is: %s:%s" %
  745. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  746. log.warning("Type of ZEROS found inline, in header: %s" % self.zeros)
  747. continue
  748. # Search for units type again it might be alone on the line
  749. if "INCH" in eline:
  750. line_units = "IN"
  751. # Modified for issue #80
  752. log.warning("Type of UNITS found inline, in header, before conversion: %s" % line_units)
  753. self.convert_units(line_units)
  754. log.warning("Type of UNITS found inline, in header, after conversion: %s" % self.units)
  755. log.warning("Excellon format preset is: %s:%s" %
  756. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  757. self.excellon_units_found = "IN"
  758. continue
  759. elif "METRIC" in eline:
  760. line_units = "MM"
  761. # Modified for issue #80
  762. log.warning("Type of UNITS found inline, in header, before conversion: %s" % line_units)
  763. self.convert_units(line_units)
  764. log.warning("Type of UNITS found inline, in header, after conversion: %s" % self.units)
  765. log.warning("Excellon format preset is: %s:%s" %
  766. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  767. self.excellon_units_found = "MM"
  768. continue
  769. # Search for zeros type again because it might be alone on the line
  770. match = re.search(r'[LT]Z', eline)
  771. if match:
  772. self.zeros = match.group()
  773. log.warning("Type of ZEROS found: %s" % self.zeros)
  774. continue
  775. # ## Units and number format outside header# ##
  776. match = self.units_re.match(eline)
  777. if match:
  778. self.units = {"METRIC": "MM", "INCH": "IN"}[match.group(1)]
  779. self.excellon_units_found = self.units
  780. self.zeros = match.group(2) # "T" or "L". Might be empty
  781. self.excellon_format = match.group(3)
  782. if self.excellon_format:
  783. upper = len(self.excellon_format.partition('.')[0])
  784. lower = len(self.excellon_format.partition('.')[2])
  785. if self.units == 'MM':
  786. self.excellon_format_upper_mm = upper
  787. self.excellon_format_lower_mm = lower
  788. else:
  789. self.excellon_format_upper_in = upper
  790. self.excellon_format_lower_in = lower
  791. # Modified for issue #80
  792. log.warning("Type of UNITS found outside header, inline before conversion: %s" % self.units)
  793. self.convert_units(self.units)
  794. log.warning("Type of UNITS found outside header, inline after conversion: %s" % self.units)
  795. if self.units == 'MM':
  796. log.warning("Excellon format preset is: %s:%s" %
  797. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  798. else:
  799. log.warning("Excellon format preset is: %s:%s" %
  800. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  801. log.warning("Type of ZEROS found outside header, inline: %s" % self.zeros)
  802. continue
  803. log.warning("Line ignored: %s" % eline)
  804. # make sure that since we are in headerless mode, we convert the tools only after the file parsing
  805. # is finished since the tools definitions are spread in the Excellon body. We use as units the value
  806. # from self.defaults['excellon_units']
  807. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  808. except Exception:
  809. log.error("Excellon PARSING FAILED. Line %d: %s" % (line_num, eline))
  810. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  811. msg += '{e_code} {tx} {l_nr}: {line}\n'.format(
  812. e_code='[ERROR]',
  813. tx=_("Excellon Parser error.\nParsing Failed. Line"),
  814. l_nr=line_num,
  815. line=eline)
  816. msg += traceback.format_exc()
  817. self.app.inform.emit(msg)
  818. return "fail"
  819. def parse_number(self, number_str):
  820. """
  821. Parses coordinate numbers without period.
  822. :param number_str: String representing the numerical value.
  823. :type number_str: str
  824. :return: Floating point representation of the number
  825. :rtype: float
  826. """
  827. match = self.leadingzeros_re.search(number_str)
  828. nr_length = len(match.group(1)) + len(match.group(2))
  829. try:
  830. if self.zeros == "L" or self.zeros == "LZ": # Leading
  831. # With leading zeros, when you type in a coordinate,
  832. # the leading zeros must always be included. Trailing zeros
  833. # are unneeded and may be left off. The CNC-7 will automatically add them.
  834. # r'^[-\+]?(0*)(\d*)'
  835. # 6 digits are divided by 10^4
  836. # If less than size digits, they are automatically added,
  837. # 5 digits then are divided by 10^3 and so on.
  838. if self.units.lower() == "in":
  839. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_in)))
  840. else:
  841. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_mm)))
  842. return result
  843. else: # Trailing
  844. # You must show all zeros to the right of the number and can omit
  845. # all zeros to the left of the number. The CNC-7 will count the number
  846. # of digits you typed and automatically fill in the missing zeros.
  847. # ## flatCAM expects 6digits
  848. # flatCAM expects the number of digits entered into the defaults
  849. if self.units.lower() == "in": # Inches is 00.0000
  850. result = float(number_str) / (10 ** (float(self.excellon_format_lower_in)))
  851. else: # Metric is 000.000
  852. result = float(number_str) / (10 ** (float(self.excellon_format_lower_mm)))
  853. return result
  854. except Exception as e:
  855. log.error("Aborted. Operation could not be completed due of %s" % str(e))
  856. return
  857. def create_geometry(self):
  858. """
  859. Creates circles of the tool diameter at every point
  860. specified in self.tools[tool]['drills'].
  861. Also creates geometries (polygons)
  862. for the slots as specified in self.tools[tool]['slots']
  863. All the resulting geometry is stored into self.solid_geometry list.
  864. The list self.solid_geometry has 2 elements: first is a dict with the drills geometry,
  865. and second element is another similar dict that contain the slots geometry.
  866. Each dict has as keys the tool diameters and as values lists with Shapely objects, the geometries
  867. ================ ====================================
  868. Key Value
  869. ================ ====================================
  870. tool_diameter list of (Shapely.Point) Where to drill
  871. ================ ====================================
  872. :return: None
  873. """
  874. log.debug("appParsers.ParseExcellon.Excellon.create_geometry()")
  875. self.solid_geometry = []
  876. try:
  877. # clear the solid_geometry in self.tools
  878. for tool in self.tools:
  879. self.tools[tool]['solid_geometry'] = []
  880. self.tools[tool]['data'] = {}
  881. for tool in self.tools:
  882. tooldia = self.tools[tool]['tooldia']
  883. if 'drills' in self.tools[tool]:
  884. for drill in self.tools[tool]['drills']:
  885. poly = drill.buffer(tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  886. # add poly in the tools geometry
  887. self.tools[tool]['solid_geometry'].append(poly)
  888. self.tools[tool]['data'] = deepcopy(self.default_data)
  889. # add poly to the total solid geometry
  890. self.solid_geometry.append(poly)
  891. if 'slots' in self.tools[tool]:
  892. for slot in self.tools[tool]['slots']:
  893. start = slot[0]
  894. stop = slot[1]
  895. lines_string = LineString([start, stop])
  896. poly = lines_string.buffer(tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  897. # add poly in the tools geometry
  898. self.tools[tool]['solid_geometry'].append(poly)
  899. self.tools[tool]['data'] = deepcopy(self.default_data)
  900. # add poly to the total solid geometry
  901. self.solid_geometry.append(poly)
  902. except Exception as e:
  903. log.debug("appParsers.ParseExcellon.Excellon.create_geometry() -> "
  904. "Excellon geometry creation failed due of ERROR: %s" % str(e))
  905. return "fail"
  906. def bounds(self, flatten=None):
  907. """
  908. Returns coordinates of rectangular bounds
  909. of Excellon geometry: (xmin, ymin, xmax, ymax).
  910. :param flatten: No used
  911. """
  912. log.debug("appParsers.ParseExcellon.Excellon.bounds()")
  913. if self.solid_geometry is None or not self.tools:
  914. log.debug("appParsers.ParseExcellon.Excellon -> solid_geometry is None")
  915. return 0, 0, 0, 0
  916. def bounds_rec(obj):
  917. if type(obj) is list:
  918. minx = np.Inf
  919. miny = np.Inf
  920. maxx = -np.Inf
  921. maxy = -np.Inf
  922. for k in obj:
  923. if type(k) is dict:
  924. for key in k:
  925. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  926. minx = min(minx, minx_)
  927. miny = min(miny, miny_)
  928. maxx = max(maxx, maxx_)
  929. maxy = max(maxy, maxy_)
  930. else:
  931. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  932. minx = min(minx, minx_)
  933. miny = min(miny, miny_)
  934. maxx = max(maxx, maxx_)
  935. maxy = max(maxy, maxy_)
  936. return minx, miny, maxx, maxy
  937. else:
  938. # it's a Shapely object, return it's bounds
  939. return obj.bounds
  940. minx_list = []
  941. miny_list = []
  942. maxx_list = []
  943. maxy_list = []
  944. for tool in self.tools:
  945. eminx, eminy, emaxx, emaxy = bounds_rec(self.tools[tool]['solid_geometry'])
  946. minx_list.append(eminx)
  947. miny_list.append(eminy)
  948. maxx_list.append(emaxx)
  949. maxy_list.append(emaxy)
  950. return min(minx_list), min(miny_list), max(maxx_list), max(maxy_list)
  951. def convert_units(self, units):
  952. """
  953. This function first convert to the the units found in the Excellon file but it converts tools that
  954. are not there yet so it has no effect other than it signal that the units are the ones in the file.
  955. On object creation, in app_obj.new_object(), true conversion is done because this is done at the end of the
  956. Excellon file parsing, the tools are inside and self.tools is really converted from the units found
  957. inside the file to the FlatCAM units.
  958. Kind of convolute way to make the conversion and it is based on the assumption that the Excellon file
  959. will have detected the units before the tools are parsed and stored in self.tools
  960. :param units: 'IN' or 'MM'. String
  961. :return:
  962. """
  963. # factor = Geometry.convert_units(self, units)
  964. obj_units = units
  965. if obj_units.upper() == self.units.upper():
  966. factor = 1.0
  967. elif obj_units.upper() == "MM":
  968. factor = 25.4
  969. elif obj_units.upper() == "IN":
  970. factor = 1 / 25.4
  971. else:
  972. log.error("Unsupported units: %s" % str(obj_units))
  973. factor = 1.0
  974. log.debug("appParsers.ParseExcellon.Excellon.convert_units() --> Factor: %s" % str(factor))
  975. self.units = obj_units
  976. self.scale(factor, factor)
  977. self.file_units_factor = factor
  978. # Tools
  979. for tname in self.tools:
  980. self.tools[tname]["tooldia"] *= factor
  981. self.create_geometry()
  982. return factor
  983. def scale(self, xfactor, yfactor=None, point=None):
  984. """
  985. Scales geometry on the XY plane in the object by a given factor.
  986. Tool sizes, feedrates an Z-plane dimensions are untouched.
  987. :param xfactor: Number by which to scale the object.
  988. :type xfactor: float
  989. :param yfactor: Number by which to scale the object.
  990. :type yfactor: float
  991. :param point: Origin point for scale
  992. :return: None
  993. :rtype: None
  994. """
  995. log.debug("appParsers.ParseExcellon.Excellon.scale()")
  996. if yfactor is None:
  997. yfactor = xfactor
  998. if point is None:
  999. px = 0
  1000. py = 0
  1001. else:
  1002. px, py = point
  1003. if xfactor == 0 and yfactor == 0:
  1004. return
  1005. def scale_geom(obj):
  1006. if type(obj) is list:
  1007. new_obj = []
  1008. for g in obj:
  1009. new_obj.append(scale_geom(g))
  1010. return new_obj
  1011. else:
  1012. try:
  1013. return affinity.scale(obj, xfactor, yfactor, origin=(px, py))
  1014. except AttributeError:
  1015. return obj
  1016. # variables to display the percentage of work done
  1017. self.geo_len = 0
  1018. try:
  1019. self.geo_len = len(self.tools)
  1020. except TypeError:
  1021. self.geo_len = 1
  1022. self.old_disp_number = 0
  1023. self.el_count = 0
  1024. for tool in self.tools:
  1025. # Scale Drills
  1026. if 'drills' in self.tools[tool]:
  1027. new_drills = []
  1028. for drill in self.tools[tool]['drills']:
  1029. new_drills.append(affinity.scale(drill, xfactor, yfactor, origin=(px, py)))
  1030. self.tools[tool]['drills'] = new_drills
  1031. # Scale Slots
  1032. if 'slots' in self.tools[tool]:
  1033. new_slots = []
  1034. for slot in self.tools[tool]['slots']:
  1035. new_start = affinity.scale(slot[0], xfactor, yfactor, origin=(px, py))
  1036. new_stop = affinity.scale(slot[1], xfactor, yfactor, origin=(px, py))
  1037. new_slot = (new_start, new_stop)
  1038. new_slots.append(new_slot)
  1039. # Scale solid_geometry
  1040. self.tools[tool]['solid_geometry'] = scale_geom(self.tools[tool]['solid_geometry'])
  1041. # update status display
  1042. self.el_count += 1
  1043. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1044. if self.old_disp_number < disp_number <= 100:
  1045. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1046. self.old_disp_number = disp_number
  1047. self.create_geometry()
  1048. self.app.proc_container.new_text = ''
  1049. def offset(self, vect):
  1050. """
  1051. Offsets geometry on the XY plane in the object by a given vector.
  1052. :param vect: (x, y) offset vector.
  1053. :type vect: tuple
  1054. :return: None
  1055. """
  1056. log.debug("appParsers.ParseExcellon.Excellon.offset()")
  1057. dx, dy = vect
  1058. if dx == 0 and dy == 0:
  1059. return
  1060. def offset_geom(obj):
  1061. try:
  1062. new_obj = []
  1063. for geo in obj:
  1064. new_obj.append(offset_geom(geo))
  1065. return new_obj
  1066. except TypeError:
  1067. try:
  1068. return affinity.translate(obj, xoff=dx, yoff=dy)
  1069. except AttributeError:
  1070. return obj
  1071. # variables to display the percentage of work done
  1072. self.geo_len = 0
  1073. try:
  1074. self.geo_len = len(self.tools)
  1075. except TypeError:
  1076. self.geo_len = 1
  1077. self.old_disp_number = 0
  1078. self.el_count = 0
  1079. for tool in self.tools:
  1080. # Offset Drills
  1081. if 'drills' in self.tools[tool]:
  1082. new_drills = []
  1083. for drill in self.tools[tool]['drills']:
  1084. new_drills.append(affinity.translate(drill, xoff=dx, yoff=dy))
  1085. self.tools[tool]['drills'] = new_drills
  1086. # Offset Slots
  1087. if 'slots' in self.tools[tool]:
  1088. new_slots = []
  1089. for slot in self.tools[tool]['slots']:
  1090. new_start = affinity.translate(slot[0], xoff=dx, yoff=dy)
  1091. new_stop = affinity.translate(slot[1], xoff=dx, yoff=dy)
  1092. new_slot = (new_start, new_stop)
  1093. new_slots.append(new_slot)
  1094. # Offset solid_geometry
  1095. self.tools[tool]['solid_geometry'] = offset_geom(self.tools[tool]['solid_geometry'])
  1096. # update status display
  1097. self.el_count += 1
  1098. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1099. if self.old_disp_number < disp_number <= 100:
  1100. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1101. self.old_disp_number = disp_number
  1102. # Recreate geometry
  1103. self.create_geometry()
  1104. self.app.proc_container.new_text = ''
  1105. def mirror(self, axis, point):
  1106. """
  1107. :param axis: "X" or "Y" indicates around which axis to mirror.
  1108. :type axis: str
  1109. :param point: [x, y] point belonging to the mirror axis.
  1110. :type point: list
  1111. :return: None
  1112. """
  1113. log.debug("appParsers.ParseExcellon.Excellon.mirror()")
  1114. px, py = point
  1115. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1116. def mirror_geom(obj):
  1117. try:
  1118. new_obj = []
  1119. for geo in obj:
  1120. new_obj.append(mirror_geom(geo))
  1121. return new_obj
  1122. except TypeError:
  1123. try:
  1124. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1125. except AttributeError:
  1126. return obj
  1127. # Modify data
  1128. # variables to display the percentage of work done
  1129. self.geo_len = 0
  1130. try:
  1131. self.geo_len = len(self.tools)
  1132. except TypeError:
  1133. self.geo_len = 1
  1134. self.old_disp_number = 0
  1135. self.el_count = 0
  1136. for tool in self.tools:
  1137. # Offset Drills
  1138. if 'drills' in self.tools[tool]:
  1139. new_drills = []
  1140. for drill in self.tools[tool]['drills']:
  1141. new_drills.append(affinity.scale(drill, xscale, yscale, origin=(px, py)))
  1142. self.tools[tool]['drills'] = new_drills
  1143. # Offset Slots
  1144. if 'slots' in self.tools[tool]:
  1145. new_slots = []
  1146. for slot in self.tools[tool]['slots']:
  1147. new_start = affinity.scale(slot[0], xscale, yscale, origin=(px, py))
  1148. new_stop = affinity.scale(slot[1], xscale, yscale, origin=(px, py))
  1149. new_slot = (new_start, new_stop)
  1150. new_slots.append(new_slot)
  1151. # Offset solid_geometry
  1152. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1153. # update status display
  1154. self.el_count += 1
  1155. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1156. if self.old_disp_number < disp_number <= 100:
  1157. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1158. self.old_disp_number = disp_number
  1159. # Recreate geometry
  1160. self.create_geometry()
  1161. self.app.proc_container.new_text = ''
  1162. def skew(self, angle_x=None, angle_y=None, point=None):
  1163. """
  1164. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1165. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1166. :param angle_x:
  1167. :param angle_y:
  1168. The shear angle(s) for the x and y axes respectively. These can be
  1169. specified in either degrees (default) or radians by setting
  1170. use_radians=True.
  1171. :param point: Origin point for Skew
  1172. See shapely manual for more information:
  1173. http://toblerity.org/shapely/manual.html#affine-transformations
  1174. """
  1175. log.debug("appParsers.ParseExcellon.Excellon.skew()")
  1176. if angle_x is None:
  1177. angle_x = 0.0
  1178. if angle_y is None:
  1179. angle_y = 0.0
  1180. if angle_x == 0 and angle_y == 0:
  1181. return
  1182. def skew_geom(obj):
  1183. try:
  1184. new_obj = []
  1185. for g in obj:
  1186. new_obj.append(skew_geom(g))
  1187. return new_obj
  1188. except TypeError:
  1189. try:
  1190. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1191. except AttributeError:
  1192. return obj
  1193. # variables to display the percentage of work done
  1194. self.geo_len = 0
  1195. try:
  1196. self.geo_len = len(self.tools)
  1197. except TypeError:
  1198. self.geo_len = 1
  1199. self.old_disp_number = 0
  1200. self.el_count = 0
  1201. if point is None:
  1202. px, py = 0, 0
  1203. else:
  1204. px, py = point
  1205. for tool in self.tools:
  1206. # Offset Drills
  1207. if 'drills' in self.tools[tool]:
  1208. new_drills = []
  1209. for drill in self.tools[tool]['drills']:
  1210. new_drills.append(affinity.skew(drill, angle_x, angle_y, origin=(px, py)))
  1211. self.tools[tool]['drills'] = new_drills
  1212. # Offset Slots
  1213. if 'slots' in self.tools[tool]:
  1214. new_slots = []
  1215. for slot in self.tools[tool]['slots']:
  1216. new_start = affinity.skew(slot[0], angle_x, angle_y, origin=(px, py))
  1217. new_stop = affinity.skew(slot[1], angle_x, angle_y, origin=(px, py))
  1218. new_slot = (new_start, new_stop)
  1219. new_slots.append(new_slot)
  1220. # Offset solid_geometry
  1221. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1222. # update status display
  1223. self.el_count += 1
  1224. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1225. if self.old_disp_number < disp_number <= 100:
  1226. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1227. self.old_disp_number = disp_number
  1228. self.create_geometry()
  1229. self.app.proc_container.new_text = ''
  1230. def rotate(self, angle, point=None):
  1231. """
  1232. Rotate the geometry of an object by an angle around the 'point' coordinates
  1233. :param angle:
  1234. :param point: tuple of coordinates (x, y)
  1235. :return: None
  1236. """
  1237. log.debug("appParsers.ParseExcellon.Excellon.rotate()")
  1238. if angle == 0:
  1239. return
  1240. def rotate_geom(obj, origin=None):
  1241. if type(obj) is list:
  1242. new_obj = []
  1243. for g in obj:
  1244. new_obj.append(rotate_geom(g))
  1245. return new_obj
  1246. else:
  1247. if origin:
  1248. try:
  1249. return affinity.rotate(obj, angle, origin=origin)
  1250. except AttributeError:
  1251. return obj
  1252. else:
  1253. try:
  1254. return affinity.rotate(obj, angle, origin=orig)
  1255. except AttributeError:
  1256. return obj
  1257. # variables to display the percentage of work done
  1258. self.geo_len = 0
  1259. try:
  1260. self.geo_len = len(self.tools)
  1261. except TypeError:
  1262. self.geo_len = 1
  1263. self.old_disp_number = 0
  1264. self.el_count = 0
  1265. if point is None:
  1266. orig = 'center'
  1267. else:
  1268. orig = point
  1269. for tool in self.tools:
  1270. # Offset Drills
  1271. if 'drills' in self.tools[tool]:
  1272. new_drills = []
  1273. for drill in self.tools[tool]['drills']:
  1274. new_drills.append(affinity.rotate(drill, angle, origin=orig))
  1275. self.tools[tool]['drills'] = new_drills
  1276. # Offset Slots
  1277. if 'slots' in self.tools[tool]:
  1278. new_slots = []
  1279. for slot in self.tools[tool]['slots']:
  1280. new_start = affinity.rotate(slot[0], angle, origin=orig)
  1281. new_stop = affinity.rotate(slot[1], angle, origin=orig)
  1282. new_slot = (new_start, new_stop)
  1283. new_slots.append(new_slot)
  1284. # Offset solid_geometry
  1285. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'], origin=orig)
  1286. # update status display
  1287. self.el_count += 1
  1288. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1289. if self.old_disp_number < disp_number <= 100:
  1290. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1291. self.old_disp_number = disp_number
  1292. self.create_geometry()
  1293. self.app.proc_container.new_text = ''
  1294. def buffer(self, distance, join, factor):
  1295. """
  1296. :param distance: if 'factor' is True then distance is the factor
  1297. :param factor: True or False (None)
  1298. :param join: The type of line joint used by the shapely buffer method: round, square, bevel
  1299. :return: None
  1300. """
  1301. log.debug("appParsers.ParseExcellon.Excellon.buffer()")
  1302. if distance == 0:
  1303. return
  1304. def buffer_geom(obj):
  1305. try:
  1306. new_obj = []
  1307. for g in obj:
  1308. new_obj.append(buffer_geom(g))
  1309. return new_obj
  1310. except TypeError:
  1311. try:
  1312. if factor is None:
  1313. return obj.buffer(distance, resolution=self.geo_steps_per_circle)
  1314. else:
  1315. return affinity.scale(obj, xfact=distance, yfact=distance, origin='center')
  1316. except AttributeError:
  1317. return obj
  1318. # buffer solid_geometry
  1319. for tool, tool_dict in list(self.tools.items()):
  1320. res = buffer_geom(tool_dict['solid_geometry'])
  1321. try:
  1322. __ = iter(res)
  1323. self.tools[tool]['solid_geometry'] = res
  1324. except TypeError:
  1325. self.tools[tool]['solid_geometry'] = [res]
  1326. if factor is None:
  1327. self.tools[tool]['tooldia'] += distance
  1328. else:
  1329. self.tools[tool]['tooldia'] *= distance
  1330. self.create_geometry()