ParseExcellon.py 66 KB

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