camlib.py 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112
  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 __future__ import division
  9. import traceback
  10. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  11. from matplotlib.figure import Figure
  12. import re
  13. import collections
  14. import numpy as np
  15. import matplotlib
  16. import matplotlib.pyplot as plt
  17. from scipy.spatial import Delaunay, KDTree
  18. from rtree import index as rtindex
  19. # See: http://toblerity.org/shapely/manual.html
  20. from shapely.geometry import Polygon, LineString, Point, LinearRing
  21. from shapely.geometry import MultiPoint, MultiPolygon
  22. from shapely.geometry import box as shply_box
  23. from shapely.ops import cascaded_union
  24. import shapely.affinity as affinity
  25. from shapely.wkt import loads as sloads
  26. from shapely.wkt import dumps as sdumps
  27. from shapely.geometry.base import BaseGeometry
  28. # Used for solid polygons in Matplotlib
  29. from descartes.patch import PolygonPatch
  30. import simplejson as json
  31. # TODO: Commented for FlatCAM packaging with cx_freeze
  32. #from matplotlib.pyplot import plot
  33. import logging
  34. log = logging.getLogger('base2')
  35. log.setLevel(logging.DEBUG)
  36. #log.setLevel(logging.WARNING)
  37. #log.setLevel(logging.INFO)
  38. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  39. handler = logging.StreamHandler()
  40. handler.setFormatter(formatter)
  41. log.addHandler(handler)
  42. class Geometry(object):
  43. """
  44. Base geometry class.
  45. """
  46. defaults = {
  47. "init_units": 'in'
  48. }
  49. def __init__(self):
  50. # Units (in or mm)
  51. self.units = Geometry.defaults["init_units"]
  52. # Final geometry: MultiPolygon or list (of geometry constructs)
  53. self.solid_geometry = None
  54. # Attributes to be included in serialization
  55. self.ser_attrs = ['units', 'solid_geometry']
  56. # Flattened geometry (list of paths only)
  57. self.flat_geometry = []
  58. # Flat geometry rtree index
  59. self.flat_geometry_rtree = rtindex.Index()
  60. def add_circle(self, origin, radius):
  61. """
  62. Adds a circle to the object.
  63. :param origin: Center of the circle.
  64. :param radius: Radius of the circle.
  65. :return: None
  66. """
  67. # TODO: Decide what solid_geometry is supposed to be and how we append to it.
  68. if self.solid_geometry is None:
  69. self.solid_geometry = []
  70. if type(self.solid_geometry) is list:
  71. self.solid_geometry.append(Point(origin).buffer(radius))
  72. return
  73. try:
  74. self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(radius))
  75. except:
  76. print "Failed to run union on polygons."
  77. raise
  78. def add_polygon(self, points):
  79. """
  80. Adds a polygon to the object (by union)
  81. :param points: The vertices of the polygon.
  82. :return: None
  83. """
  84. if self.solid_geometry is None:
  85. self.solid_geometry = []
  86. if type(self.solid_geometry) is list:
  87. self.solid_geometry.append(Polygon(points))
  88. return
  89. try:
  90. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  91. except:
  92. print "Failed to run union on polygons."
  93. raise
  94. def bounds(self):
  95. """
  96. Returns coordinates of rectangular bounds
  97. of geometry: (xmin, ymin, xmax, ymax).
  98. """
  99. log.debug("Geometry->bounds()")
  100. if self.solid_geometry is None:
  101. log.debug("solid_geometry is None")
  102. log.warning("solid_geometry not computed yet.")
  103. return 0, 0, 0, 0
  104. if type(self.solid_geometry) is list:
  105. log.debug("type(solid_geometry) is list")
  106. # TODO: This can be done faster. See comment from Shapely mailing lists.
  107. if len(self.solid_geometry) == 0:
  108. log.debug('solid_geometry is empty []')
  109. return 0, 0, 0, 0
  110. log.debug('solid_geometry is not empty, returning cascaded union of items')
  111. return cascaded_union(self.solid_geometry).bounds
  112. else:
  113. log.debug("type(solid_geometry) is not list, returning .bounds property")
  114. return self.solid_geometry.bounds
  115. def flatten_to_paths(self, geometry=None, reset=True):
  116. """
  117. Creates a list of non-iterable linear geometry elements and
  118. indexes them in rtree.
  119. :param geometry: Iterable geometry
  120. :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  121. :return: self.flat_geometry, self.flat_geometry_rtree
  122. """
  123. if geometry is None:
  124. geometry = self.solid_geometry
  125. if reset:
  126. self.flat_geometry = []
  127. try:
  128. for geo in geometry:
  129. self.flatten_to_paths(geometry=geo, reset=False)
  130. except TypeError:
  131. if type(geometry) == Polygon:
  132. g = geometry.exterior
  133. self.flat_geometry.append(g)
  134. self.flat_geometry_rtree.insert(len(self.flat_geometry)-1, g.coords[0])
  135. self.flat_geometry_rtree.insert(len(self.flat_geometry)-1, g.coords[-1])
  136. for interior in geometry.interiors:
  137. g = interior
  138. self.flat_geometry.append(g)
  139. self.flat_geometry_rtree.insert(len(self.flat_geometry)-1, g.coords[0])
  140. self.flat_geometry_rtree.insert(len(self.flat_geometry)-1, g.coords[-1])
  141. else:
  142. g = geometry
  143. self.flat_geometry.append(g)
  144. self.flat_geometry_rtree.insert(len(self.flat_geometry)-1, g.coords[0])
  145. self.flat_geometry_rtree.insert(len(self.flat_geometry)-1, g.coords[-1])
  146. return self.flat_geometry, self.flat_geometry_rtree
  147. def isolation_geometry(self, offset):
  148. """
  149. Creates contours around geometry at a given
  150. offset distance.
  151. :param offset: Offset distance.
  152. :type offset: float
  153. :return: The buffered geometry.
  154. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  155. """
  156. return self.solid_geometry.buffer(offset)
  157. def is_empty(self):
  158. if self.solid_geometry is None:
  159. return True
  160. if type(self.solid_geometry) is list and len(self.solid_geometry) == 0:
  161. return True
  162. return False
  163. def size(self):
  164. """
  165. Returns (width, height) of rectangular
  166. bounds of geometry.
  167. """
  168. if self.solid_geometry is None:
  169. log.warning("Solid_geometry not computed yet.")
  170. return 0
  171. bounds = self.bounds()
  172. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  173. def get_empty_area(self, boundary=None):
  174. """
  175. Returns the complement of self.solid_geometry within
  176. the given boundary polygon. If not specified, it defaults to
  177. the rectangular bounding box of self.solid_geometry.
  178. """
  179. if boundary is None:
  180. boundary = self.solid_geometry.envelope
  181. return boundary.difference(self.solid_geometry)
  182. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  183. """
  184. Creates geometry inside a polygon for a tool to cover
  185. the whole area.
  186. This algorithm shrinks the edges of the polygon and takes
  187. the resulting edges as toolpaths.
  188. :param polygon: Polygon to clear.
  189. :param tooldia: Diameter of the tool.
  190. :param overlap: Overlap of toolpasses.
  191. :return:
  192. """
  193. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  194. while True:
  195. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  196. if polygon.area > 0:
  197. poly_cuts.append(polygon)
  198. else:
  199. break
  200. return poly_cuts
  201. def clear_polygon2(self, polygon, tooldia, seedpoint=None, overlap=0.15):
  202. """
  203. Creates geometry inside a polygon for a tool to cover
  204. the whole area.
  205. This algorithm starts with a seed point inside the polygon
  206. and draws circles around it. Arcs inside the polygons are
  207. valid cuts. Finalizes by cutting around the inside edge of
  208. the polygon.
  209. :param polygon:
  210. :param tooldia:
  211. :param seedpoint:
  212. :param overlap:
  213. :return:
  214. """
  215. if seedpoint is None:
  216. seedpoint = polygon.representative_point()
  217. # Current buffer radius
  218. radius = tooldia/2*(1-overlap)
  219. # The toolpaths
  220. geoms = [Point(seedpoint).buffer(radius).exterior]
  221. # Path margin
  222. path_margin = polygon.buffer(-tooldia/2)
  223. # Grow from seed until outside the box.
  224. while 1:
  225. path = Point(seedpoint).buffer(radius).exterior
  226. path = path.intersection(path_margin)
  227. # Touches polygon?
  228. if path.is_empty:
  229. break
  230. else:
  231. geoms.append(path)
  232. radius += tooldia*(1-overlap)
  233. # Clean edges
  234. outer_edges = [x.exterior for x in autolist(polygon.buffer(-tooldia/2))]
  235. inner_edges = []
  236. for x in autolist(polygon.buffer(-tooldia/2)): # Over resulting polygons
  237. for y in x.interiors: # Over interiors of each polygon
  238. inner_edges.append(y)
  239. geoms += outer_edges + inner_edges
  240. return geoms
  241. def scale(self, factor):
  242. """
  243. Scales all of the object's geometry by a given factor. Override
  244. this method.
  245. :param factor: Number by which to scale.
  246. :type factor: float
  247. :return: None
  248. :rtype: None
  249. """
  250. return
  251. def offset(self, vect):
  252. """
  253. Offset the geometry by the given vector. Override this method.
  254. :param vect: (x, y) vector by which to offset the object.
  255. :type vect: tuple
  256. :return: None
  257. """
  258. return
  259. def convert_units(self, units):
  260. """
  261. Converts the units of the object to ``units`` by scaling all
  262. the geometry appropriately. This call ``scale()``. Don't call
  263. it again in descendents.
  264. :param units: "IN" or "MM"
  265. :type units: str
  266. :return: Scaling factor resulting from unit change.
  267. :rtype: float
  268. """
  269. log.debug("Geometry.convert_units()")
  270. if units.upper() == self.units.upper():
  271. return 1.0
  272. if units.upper() == "MM":
  273. factor = 25.4
  274. elif units.upper() == "IN":
  275. factor = 1/25.4
  276. else:
  277. log.error("Unsupported units: %s" % str(units))
  278. return 1.0
  279. self.units = units
  280. self.scale(factor)
  281. return factor
  282. def to_dict(self):
  283. """
  284. Returns a respresentation of the object as a dictionary.
  285. Attributes to include are listed in ``self.ser_attrs``.
  286. :return: A dictionary-encoded copy of the object.
  287. :rtype: dict
  288. """
  289. d = {}
  290. for attr in self.ser_attrs:
  291. d[attr] = getattr(self, attr)
  292. return d
  293. def from_dict(self, d):
  294. """
  295. Sets object's attributes from a dictionary.
  296. Attributes to include are listed in ``self.ser_attrs``.
  297. This method will look only for only and all the
  298. attributes in ``self.ser_attrs``. They must all
  299. be present. Use only for deserializing saved
  300. objects.
  301. :param d: Dictionary of attributes to set in the object.
  302. :type d: dict
  303. :return: None
  304. """
  305. for attr in self.ser_attrs:
  306. setattr(self, attr, d[attr])
  307. def union(self):
  308. """
  309. Runs a cascaded union on the list of objects in
  310. solid_geometry.
  311. :return: None
  312. """
  313. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  314. class ApertureMacro:
  315. """
  316. Syntax of aperture macros.
  317. <AM command>: AM<Aperture macro name>*<Macro content>
  318. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  319. <Variable definition>: $K=<Arithmetic expression>
  320. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  321. <Modifier>: $M|< Arithmetic expression>
  322. <Comment>: 0 <Text>
  323. """
  324. ## Regular expressions
  325. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  326. am2_re = re.compile(r'(.*)%$')
  327. amcomm_re = re.compile(r'^0(.*)')
  328. amprim_re = re.compile(r'^[1-9].*')
  329. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  330. def __init__(self, name=None):
  331. self.name = name
  332. self.raw = ""
  333. ## These below are recomputed for every aperture
  334. ## definition, in other words, are temporary variables.
  335. self.primitives = []
  336. self.locvars = {}
  337. self.geometry = None
  338. def to_dict(self):
  339. """
  340. Returns the object in a serializable form. Only the name and
  341. raw are required.
  342. :return: Dictionary representing the object. JSON ready.
  343. :rtype: dict
  344. """
  345. return {
  346. 'name': self.name,
  347. 'raw': self.raw
  348. }
  349. def from_dict(self, d):
  350. """
  351. Populates the object from a serial representation created
  352. with ``self.to_dict()``.
  353. :param d: Serial representation of an ApertureMacro object.
  354. :return: None
  355. """
  356. for attr in ['name', 'raw']:
  357. setattr(self, attr, d[attr])
  358. def parse_content(self):
  359. """
  360. Creates numerical lists for all primitives in the aperture
  361. macro (in ``self.raw``) by replacing all variables by their
  362. values iteratively and evaluating expressions. Results
  363. are stored in ``self.primitives``.
  364. :return: None
  365. """
  366. # Cleanup
  367. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  368. self.primitives = []
  369. # Separate parts
  370. parts = self.raw.split('*')
  371. #### Every part in the macro ####
  372. for part in parts:
  373. ### Comments. Ignored.
  374. match = ApertureMacro.amcomm_re.search(part)
  375. if match:
  376. continue
  377. ### Variables
  378. # These are variables defined locally inside the macro. They can be
  379. # numerical constant or defind in terms of previously define
  380. # variables, which can be defined locally or in an aperture
  381. # definition. All replacements ocurr here.
  382. match = ApertureMacro.amvar_re.search(part)
  383. if match:
  384. var = match.group(1)
  385. val = match.group(2)
  386. # Replace variables in value
  387. for v in self.locvars:
  388. val = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), val)
  389. # Make all others 0
  390. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  391. # Change x with *
  392. val = re.sub(r'[xX]', "*", val)
  393. # Eval() and store.
  394. self.locvars[var] = eval(val)
  395. continue
  396. ### Primitives
  397. # Each is an array. The first identifies the primitive, while the
  398. # rest depend on the primitive. All are strings representing a
  399. # number and may contain variable definition. The values of these
  400. # variables are defined in an aperture definition.
  401. match = ApertureMacro.amprim_re.search(part)
  402. if match:
  403. ## Replace all variables
  404. for v in self.locvars:
  405. part = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  406. # Make all others 0
  407. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  408. # Change x with *
  409. part = re.sub(r'[xX]', "*", part)
  410. ## Store
  411. elements = part.split(",")
  412. self.primitives.append([eval(x) for x in elements])
  413. continue
  414. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  415. def append(self, data):
  416. """
  417. Appends a string to the raw macro.
  418. :param data: Part of the macro.
  419. :type data: str
  420. :return: None
  421. """
  422. self.raw += data
  423. @staticmethod
  424. def default2zero(n, mods):
  425. """
  426. Pads the ``mods`` list with zeros resulting in an
  427. list of length n.
  428. :param n: Length of the resulting list.
  429. :type n: int
  430. :param mods: List to be padded.
  431. :type mods: list
  432. :return: Zero-padded list.
  433. :rtype: list
  434. """
  435. x = [0.0]*n
  436. na = len(mods)
  437. x[0:na] = mods
  438. return x
  439. @staticmethod
  440. def make_circle(mods):
  441. """
  442. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  443. :return:
  444. """
  445. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  446. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  447. @staticmethod
  448. def make_vectorline(mods):
  449. """
  450. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  451. rotation angle around origin in degrees)
  452. :return:
  453. """
  454. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  455. line = LineString([(xs, ys), (xe, ye)])
  456. box = line.buffer(width/2, cap_style=2)
  457. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  458. return {"pol": int(pol), "geometry": box_rotated}
  459. @staticmethod
  460. def make_centerline(mods):
  461. """
  462. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  463. rotation angle around origin in degrees)
  464. :return:
  465. """
  466. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  467. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  468. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  469. return {"pol": int(pol), "geometry": box_rotated}
  470. @staticmethod
  471. def make_lowerleftline(mods):
  472. """
  473. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  474. rotation angle around origin in degrees)
  475. :return:
  476. """
  477. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  478. box = shply_box(x, y, x+width, y+height)
  479. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  480. return {"pol": int(pol), "geometry": box_rotated}
  481. @staticmethod
  482. def make_outline(mods):
  483. """
  484. :param mods:
  485. :return:
  486. """
  487. pol = mods[0]
  488. n = mods[1]
  489. points = [(0, 0)]*(n+1)
  490. for i in range(n+1):
  491. points[i] = mods[2*i + 2:2*i + 4]
  492. angle = mods[2*n + 4]
  493. poly = Polygon(points)
  494. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  495. return {"pol": int(pol), "geometry": poly_rotated}
  496. @staticmethod
  497. def make_polygon(mods):
  498. """
  499. Note: Specs indicate that rotation is only allowed if the center
  500. (x, y) == (0, 0). I will tolerate breaking this rule.
  501. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  502. diameter of circumscribed circle >=0, rotation angle around origin)
  503. :return:
  504. """
  505. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  506. points = [(0, 0)]*nverts
  507. for i in range(nverts):
  508. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  509. y + 0.5 * dia * sin(2*pi * i/nverts))
  510. poly = Polygon(points)
  511. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  512. return {"pol": int(pol), "geometry": poly_rotated}
  513. @staticmethod
  514. def make_moire(mods):
  515. """
  516. Note: Specs indicate that rotation is only allowed if the center
  517. (x, y) == (0, 0). I will tolerate breaking this rule.
  518. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  519. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  520. angle around origin in degrees)
  521. :return:
  522. """
  523. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  524. r = dia/2 - thickness/2
  525. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  526. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  527. i = 1 # Number of rings created so far
  528. ## If the ring does not have an interior it means that it is
  529. ## a disk. Then stop.
  530. while len(ring.interiors) > 0 and i < nrings:
  531. r -= thickness + gap
  532. if r <= 0:
  533. break
  534. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  535. result = cascaded_union([result, ring])
  536. i += 1
  537. ## Crosshair
  538. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  539. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  540. result = cascaded_union([result, hor, ver])
  541. return {"pol": 1, "geometry": result}
  542. @staticmethod
  543. def make_thermal(mods):
  544. """
  545. Note: Specs indicate that rotation is only allowed if the center
  546. (x, y) == (0, 0). I will tolerate breaking this rule.
  547. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  548. gap-thickness, rotation angle around origin]
  549. :return:
  550. """
  551. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  552. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  553. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  554. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  555. thermal = ring.difference(hline.union(vline))
  556. return {"pol": 1, "geometry": thermal}
  557. def make_geometry(self, modifiers):
  558. """
  559. Runs the macro for the given modifiers and generates
  560. the corresponding geometry.
  561. :param modifiers: Modifiers (parameters) for this macro
  562. :type modifiers: list
  563. """
  564. ## Primitive makers
  565. makers = {
  566. "1": ApertureMacro.make_circle,
  567. "2": ApertureMacro.make_vectorline,
  568. "20": ApertureMacro.make_vectorline,
  569. "21": ApertureMacro.make_centerline,
  570. "22": ApertureMacro.make_lowerleftline,
  571. "4": ApertureMacro.make_outline,
  572. "5": ApertureMacro.make_polygon,
  573. "6": ApertureMacro.make_moire,
  574. "7": ApertureMacro.make_thermal
  575. }
  576. ## Store modifiers as local variables
  577. modifiers = modifiers or []
  578. modifiers = [float(m) for m in modifiers]
  579. self.locvars = {}
  580. for i in range(0, len(modifiers)):
  581. self.locvars[str(i+1)] = modifiers[i]
  582. ## Parse
  583. self.primitives = [] # Cleanup
  584. self.geometry = None
  585. self.parse_content()
  586. ## Make the geometry
  587. for primitive in self.primitives:
  588. # Make the primitive
  589. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  590. # Add it (according to polarity)
  591. if self.geometry is None and prim_geo['pol'] == 1:
  592. self.geometry = prim_geo['geometry']
  593. continue
  594. if prim_geo['pol'] == 1:
  595. self.geometry = self.geometry.union(prim_geo['geometry'])
  596. continue
  597. if prim_geo['pol'] == 0:
  598. self.geometry = self.geometry.difference(prim_geo['geometry'])
  599. continue
  600. return self.geometry
  601. class Gerber (Geometry):
  602. """
  603. **ATTRIBUTES**
  604. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  605. The values are dictionaries key/value pairs which describe the aperture. The
  606. type key is always present and the rest depend on the key:
  607. +-----------+-----------------------------------+
  608. | Key | Value |
  609. +===========+===================================+
  610. | type | (str) "C", "R", "O", "P", or "AP" |
  611. +-----------+-----------------------------------+
  612. | others | Depend on ``type`` |
  613. +-----------+-----------------------------------+
  614. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  615. that can be instanciated with different parameters in an aperture
  616. definition. See ``apertures`` above. The key is the name of the macro,
  617. and the macro itself, the value, is a ``Aperture_Macro`` object.
  618. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  619. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  620. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  621. *buffering* (or thickening) the ``paths`` with the aperture. These are
  622. generated from ``paths`` in ``buffer_paths()``.
  623. **USAGE**::
  624. g = Gerber()
  625. g.parse_file(filename)
  626. g.create_geometry()
  627. do_something(s.solid_geometry)
  628. """
  629. defaults = {
  630. "steps_per_circle": 40
  631. }
  632. def __init__(self, steps_per_circle=None):
  633. """
  634. The constructor takes no parameters. Use ``gerber.parse_files()``
  635. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  636. :return: Gerber object
  637. :rtype: Gerber
  638. """
  639. # Initialize parent
  640. Geometry.__init__(self)
  641. self.solid_geometry = Polygon()
  642. # Number format
  643. self.int_digits = 3
  644. """Number of integer digits in Gerber numbers. Used during parsing."""
  645. self.frac_digits = 4
  646. """Number of fraction digits in Gerber numbers. Used during parsing."""
  647. ## Gerber elements ##
  648. # Apertures {'id':{'type':chr,
  649. # ['size':float], ['width':float],
  650. # ['height':float]}, ...}
  651. self.apertures = {}
  652. # Aperture Macros
  653. self.aperture_macros = {}
  654. # Attributes to be included in serialization
  655. # Always append to it because it carries contents
  656. # from Geometry.
  657. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  658. 'aperture_macros', 'solid_geometry']
  659. #### Parser patterns ####
  660. # FS - Format Specification
  661. # The format of X and Y must be the same!
  662. # L-omit leading zeros, T-omit trailing zeros
  663. # A-absolute notation, I-incremental notation
  664. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  665. # Mode (IN/MM)
  666. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  667. # Comment G04|G4
  668. self.comm_re = re.compile(r'^G0?4(.*)$')
  669. # AD - Aperture definition
  670. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z_$\.][a-zA-Z0-9_$\.]*)(?:,(.*))?\*%$')
  671. # AM - Aperture Macro
  672. # Beginning of macro (Ends with *%):
  673. #self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  674. # Tool change
  675. # May begin with G54 but that is deprecated
  676. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  677. # G01... - Linear interpolation plus flashes with coordinates
  678. # Operation code (D0x) missing is deprecated... oh well I will support it.
  679. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  680. # Operation code alone, usually just D03 (Flash)
  681. self.opcode_re = re.compile(r'^D0?([123])\*$')
  682. # G02/3... - Circular interpolation with coordinates
  683. # 2-clockwise, 3-counterclockwise
  684. # Operation code (D0x) missing is deprecated... oh well I will support it.
  685. # Optional start with G02 or G03, optional end with D01 or D02 with
  686. # optional coordinates but at least one in any order.
  687. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))' +
  688. '?(?=.*I(-?\d+))?(?=.*J(-?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  689. # G01/2/3 Occurring without coordinates
  690. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  691. # Single D74 or multi D75 quadrant for circular interpolation
  692. self.quad_re = re.compile(r'^G7([45])\*$')
  693. # Region mode on
  694. # In region mode, D01 starts a region
  695. # and D02 ends it. A new region can be started again
  696. # with D01. All contours must be closed before
  697. # D02 or G37.
  698. self.regionon_re = re.compile(r'^G36\*$')
  699. # Region mode off
  700. # Will end a region and come off region mode.
  701. # All contours must be closed before D02 or G37.
  702. self.regionoff_re = re.compile(r'^G37\*$')
  703. # End of file
  704. self.eof_re = re.compile(r'^M02\*')
  705. # IP - Image polarity
  706. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  707. # LP - Level polarity
  708. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  709. # Units (OBSOLETE)
  710. self.units_re = re.compile(r'^G7([01])\*$')
  711. # Absolute/Relative G90/1 (OBSOLETE)
  712. self.absrel_re = re.compile(r'^G9([01])\*$')
  713. # Aperture macros
  714. self.am1_re = re.compile(r'^%AM([^\*]+)\*([^%]+)?(%)?$')
  715. self.am2_re = re.compile(r'(.*)%$')
  716. # How to discretize a circle.
  717. self.steps_per_circ = steps_per_circle or Gerber.defaults['steps_per_circle']
  718. def scale(self, factor):
  719. """
  720. Scales the objects' geometry on the XY plane by a given factor.
  721. These are:
  722. * ``buffered_paths``
  723. * ``flash_geometry``
  724. * ``solid_geometry``
  725. * ``regions``
  726. NOTE:
  727. Does not modify the data used to create these elements. If these
  728. are recreated, the scaling will be lost. This behavior was modified
  729. because of the complexity reached in this class.
  730. :param factor: Number by which to scale.
  731. :type factor: float
  732. :rtype : None
  733. """
  734. ## solid_geometry ???
  735. # It's a cascaded union of objects.
  736. self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  737. factor, origin=(0, 0))
  738. # # Now buffered_paths, flash_geometry and solid_geometry
  739. # self.create_geometry()
  740. def offset(self, vect):
  741. """
  742. Offsets the objects' geometry on the XY plane by a given vector.
  743. These are:
  744. * ``buffered_paths``
  745. * ``flash_geometry``
  746. * ``solid_geometry``
  747. * ``regions``
  748. NOTE:
  749. Does not modify the data used to create these elements. If these
  750. are recreated, the scaling will be lost. This behavior was modified
  751. because of the complexity reached in this class.
  752. :param vect: (x, y) offset vector.
  753. :type vect: tuple
  754. :return: None
  755. """
  756. dx, dy = vect
  757. ## Solid geometry
  758. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  759. def mirror(self, axis, point):
  760. """
  761. Mirrors the object around a specified axis passign through
  762. the given point. What is affected:
  763. * ``buffered_paths``
  764. * ``flash_geometry``
  765. * ``solid_geometry``
  766. * ``regions``
  767. NOTE:
  768. Does not modify the data used to create these elements. If these
  769. are recreated, the scaling will be lost. This behavior was modified
  770. because of the complexity reached in this class.
  771. :param axis: "X" or "Y" indicates around which axis to mirror.
  772. :type axis: str
  773. :param point: [x, y] point belonging to the mirror axis.
  774. :type point: list
  775. :return: None
  776. """
  777. px, py = point
  778. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  779. ## solid_geometry ???
  780. # It's a cascaded union of objects.
  781. self.solid_geometry = affinity.scale(self.solid_geometry,
  782. xscale, yscale, origin=(px, py))
  783. def aperture_parse(self, apertureId, apertureType, apParameters):
  784. """
  785. Parse gerber aperture definition into dictionary of apertures.
  786. The following kinds and their attributes are supported:
  787. * *Circular (C)*: size (float)
  788. * *Rectangle (R)*: width (float), height (float)
  789. * *Obround (O)*: width (float), height (float).
  790. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  791. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  792. :param apertureId: Id of the aperture being defined.
  793. :param apertureType: Type of the aperture.
  794. :param apParameters: Parameters of the aperture.
  795. :type apertureId: str
  796. :type apertureType: str
  797. :type apParameters: str
  798. :return: Identifier of the aperture.
  799. :rtype: str
  800. """
  801. # Found some Gerber with a leading zero in the aperture id and the
  802. # referenced it without the zero, so this is a hack to handle that.
  803. apid = str(int(apertureId))
  804. try: # Could be empty for aperture macros
  805. paramList = apParameters.split('X')
  806. except:
  807. paramList = None
  808. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  809. self.apertures[apid] = {"type": "C",
  810. "size": float(paramList[0])}
  811. return apid
  812. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  813. self.apertures[apid] = {"type": "R",
  814. "width": float(paramList[0]),
  815. "height": float(paramList[1]),
  816. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  817. return apid
  818. if apertureType == "O": # Obround
  819. self.apertures[apid] = {"type": "O",
  820. "width": float(paramList[0]),
  821. "height": float(paramList[1]),
  822. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  823. return apid
  824. if apertureType == "P": # Polygon (regular)
  825. self.apertures[apid] = {"type": "P",
  826. "diam": float(paramList[0]),
  827. "nVertices": int(paramList[1]),
  828. "size": float(paramList[0])} # Hack
  829. if len(paramList) >= 3:
  830. self.apertures[apid]["rotation"] = float(paramList[2])
  831. return apid
  832. if apertureType in self.aperture_macros:
  833. self.apertures[apid] = {"type": "AM",
  834. "macro": self.aperture_macros[apertureType],
  835. "modifiers": paramList}
  836. return apid
  837. log.warning("Aperture not implemented: %s" % str(apertureType))
  838. return None
  839. def parse_file(self, filename, follow=False):
  840. """
  841. Calls Gerber.parse_lines() with array of lines
  842. read from the given file.
  843. :param filename: Gerber file to parse.
  844. :type filename: str
  845. :param follow: If true, will not create polygons, just lines
  846. following the gerber path.
  847. :type follow: bool
  848. :return: None
  849. """
  850. gfile = open(filename, 'r')
  851. gstr = gfile.readlines()
  852. gfile.close()
  853. self.parse_lines(gstr, follow=follow)
  854. def parse_lines(self, glines, follow=False):
  855. """
  856. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  857. ``self.flashes``, ``self.regions`` and ``self.units``.
  858. :param glines: Gerber code as list of strings, each element being
  859. one line of the source file.
  860. :type glines: list
  861. :param follow: If true, will not create polygons, just lines
  862. following the gerber path.
  863. :type follow: bool
  864. :return: None
  865. :rtype: None
  866. """
  867. # Coordinates of the current path, each is [x, y]
  868. path = []
  869. # Polygons are stored here until there is a change in polarity.
  870. # Only then they are combined via cascaded_union and added or
  871. # subtracted from solid_geometry. This is ~100 times faster than
  872. # applyng a union for every new polygon.
  873. poly_buffer = []
  874. last_path_aperture = None
  875. current_aperture = None
  876. # 1,2 or 3 from "G01", "G02" or "G03"
  877. current_interpolation_mode = None
  878. # 1 or 2 from "D01" or "D02"
  879. # Note this is to support deprecated Gerber not putting
  880. # an operation code at the end of every coordinate line.
  881. current_operation_code = None
  882. # Current coordinates
  883. current_x = None
  884. current_y = None
  885. # Absolute or Relative/Incremental coordinates
  886. # Not implemented
  887. absolute = True
  888. # How to interpret circular interpolation: SINGLE or MULTI
  889. quadrant_mode = None
  890. # Indicates we are parsing an aperture macro
  891. current_macro = None
  892. # Indicates the current polarity: D-Dark, C-Clear
  893. current_polarity = 'D'
  894. # If a region is being defined
  895. making_region = False
  896. #### Parsing starts here ####
  897. line_num = 0
  898. gline = ""
  899. try:
  900. for gline in glines:
  901. line_num += 1
  902. ### Cleanup
  903. gline = gline.strip(' \r\n')
  904. ### Aperture Macros
  905. # Having this at the beggining will slow things down
  906. # but macros can have complicated statements than could
  907. # be caught by other patterns.
  908. if current_macro is None: # No macro started yet
  909. match = self.am1_re.search(gline)
  910. # Start macro if match, else not an AM, carry on.
  911. if match:
  912. log.info("Starting macro. Line %d: %s" % (line_num, gline))
  913. current_macro = match.group(1)
  914. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  915. if match.group(2): # Append
  916. self.aperture_macros[current_macro].append(match.group(2))
  917. if match.group(3): # Finish macro
  918. #self.aperture_macros[current_macro].parse_content()
  919. current_macro = None
  920. log.info("Macro complete in 1 line.")
  921. continue
  922. else: # Continue macro
  923. log.info("Continuing macro. Line %d." % line_num)
  924. match = self.am2_re.search(gline)
  925. if match: # Finish macro
  926. log.info("End of macro. Line %d." % line_num)
  927. self.aperture_macros[current_macro].append(match.group(1))
  928. #self.aperture_macros[current_macro].parse_content()
  929. current_macro = None
  930. else: # Append
  931. self.aperture_macros[current_macro].append(gline)
  932. continue
  933. ### G01 - Linear interpolation plus flashes
  934. # Operation code (D0x) missing is deprecated... oh well I will support it.
  935. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  936. match = self.lin_re.search(gline)
  937. if match:
  938. # Dxx alone?
  939. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  940. # try:
  941. # current_operation_code = int(match.group(4))
  942. # except:
  943. # pass # A line with just * will match too.
  944. # continue
  945. # NOTE: Letting it continue allows it to react to the
  946. # operation code.
  947. # Parse coordinates
  948. if match.group(2) is not None:
  949. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  950. if match.group(3) is not None:
  951. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  952. # Parse operation code
  953. if match.group(4) is not None:
  954. current_operation_code = int(match.group(4))
  955. # Pen down: add segment
  956. if current_operation_code == 1:
  957. path.append([current_x, current_y])
  958. last_path_aperture = current_aperture
  959. elif current_operation_code == 2:
  960. if len(path) > 1:
  961. ## --- BUFFERED ---
  962. if making_region:
  963. geo = Polygon(path)
  964. else:
  965. if last_path_aperture is None:
  966. log.warning("No aperture defined for curent path. (%d)" % line_num)
  967. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  968. #log.debug("Line %d: Setting aperture to %s before buffering." % (line_num, last_path_aperture))
  969. if follow:
  970. geo = LineString(path)
  971. else:
  972. geo = LineString(path).buffer(width/2)
  973. poly_buffer.append(geo)
  974. path = [[current_x, current_y]] # Start new path
  975. # Flash
  976. elif current_operation_code == 3:
  977. # --- BUFFERED ---
  978. flash = Gerber.create_flash_geometry(Point([current_x, current_y]),
  979. self.apertures[current_aperture])
  980. poly_buffer.append(flash)
  981. continue
  982. ### G02/3 - Circular interpolation
  983. # 2-clockwise, 3-counterclockwise
  984. match = self.circ_re.search(gline)
  985. if match:
  986. arcdir = [None, None, "cw", "ccw"]
  987. mode, x, y, i, j, d = match.groups()
  988. try:
  989. x = parse_gerber_number(x, self.frac_digits)
  990. except:
  991. x = current_x
  992. try:
  993. y = parse_gerber_number(y, self.frac_digits)
  994. except:
  995. y = current_y
  996. try:
  997. i = parse_gerber_number(i, self.frac_digits)
  998. except:
  999. i = 0
  1000. try:
  1001. j = parse_gerber_number(j, self.frac_digits)
  1002. except:
  1003. j = 0
  1004. if quadrant_mode is None:
  1005. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  1006. log.error(gline)
  1007. continue
  1008. if mode is None and current_interpolation_mode not in [2, 3]:
  1009. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  1010. log.error(gline)
  1011. continue
  1012. elif mode is not None:
  1013. current_interpolation_mode = int(mode)
  1014. # Set operation code if provided
  1015. if d is not None:
  1016. current_operation_code = int(d)
  1017. # Nothing created! Pen Up.
  1018. if current_operation_code == 2:
  1019. log.warning("Arc with D2. (%d)" % line_num)
  1020. if len(path) > 1:
  1021. if last_path_aperture is None:
  1022. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1023. # --- BUFFERED ---
  1024. width = self.apertures[last_path_aperture]["size"]
  1025. buffered = LineString(path).buffer(width/2)
  1026. poly_buffer.append(buffered)
  1027. current_x = x
  1028. current_y = y
  1029. path = [[current_x, current_y]] # Start new path
  1030. continue
  1031. # Flash should not happen here
  1032. if current_operation_code == 3:
  1033. log.error("Trying to flash within arc. (%d)" % line_num)
  1034. continue
  1035. if quadrant_mode == 'MULTI':
  1036. center = [i + current_x, j + current_y]
  1037. radius = sqrt(i**2 + j**2)
  1038. start = arctan2(-j, -i) # Start angle
  1039. # Numerical errors might prevent start == stop therefore
  1040. # we check ahead of time. This should result in a
  1041. # 360 degree arc.
  1042. if current_x == x and current_y == y:
  1043. stop = start
  1044. else:
  1045. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1046. this_arc = arc(center, radius, start, stop,
  1047. arcdir[current_interpolation_mode],
  1048. self.steps_per_circ)
  1049. # Last point in path is current point
  1050. current_x = this_arc[-1][0]
  1051. current_y = this_arc[-1][1]
  1052. # Append
  1053. path += this_arc
  1054. last_path_aperture = current_aperture
  1055. continue
  1056. if quadrant_mode == 'SINGLE':
  1057. center_candidates = [
  1058. [i + current_x, j + current_y],
  1059. [-i + current_x, j + current_y],
  1060. [i + current_x, -j + current_y],
  1061. [-i + current_x, -j + current_y]
  1062. ]
  1063. valid = False
  1064. log.debug("I: %f J: %f" % (i, j))
  1065. for center in center_candidates:
  1066. radius = sqrt(i**2 + j**2)
  1067. # Make sure radius to start is the same as radius to end.
  1068. radius2 = sqrt((center[0] - x)**2 + (center[1] - y)**2)
  1069. if radius2 < radius*0.95 or radius2 > radius*1.05:
  1070. continue # Not a valid center.
  1071. # Correct i and j and continue as with multi-quadrant.
  1072. i = center[0] - current_x
  1073. j = center[1] - current_y
  1074. start = arctan2(-j, -i) # Start angle
  1075. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1076. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  1077. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  1078. (current_x, current_y, center[0], center[1], x, y))
  1079. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  1080. (start*180/pi, stop*180/pi, arcdir[current_interpolation_mode],
  1081. angle*180/pi, pi/2*180/pi, angle <= (pi+1e-6)/2))
  1082. if angle <= (pi+1e-6)/2:
  1083. log.debug("########## ACCEPTING ARC ############")
  1084. this_arc = arc(center, radius, start, stop,
  1085. arcdir[current_interpolation_mode],
  1086. self.steps_per_circ)
  1087. current_x = this_arc[-1][0]
  1088. current_y = this_arc[-1][1]
  1089. path += this_arc
  1090. last_path_aperture = current_aperture
  1091. valid = True
  1092. break
  1093. if valid:
  1094. continue
  1095. else:
  1096. log.warning("Invalid arc in line %d." % line_num)
  1097. ### Operation code alone
  1098. # Operation code alone, usually just D03 (Flash)
  1099. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  1100. match = self.opcode_re.search(gline)
  1101. if match:
  1102. current_operation_code = int(match.group(1))
  1103. if current_operation_code == 3:
  1104. ## --- Buffered ---
  1105. try:
  1106. flash = Gerber.create_flash_geometry(Point(path[-1]),
  1107. self.apertures[current_aperture])
  1108. poly_buffer.append(flash)
  1109. except IndexError:
  1110. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  1111. continue
  1112. ### G74/75* - Single or multiple quadrant arcs
  1113. match = self.quad_re.search(gline)
  1114. if match:
  1115. if match.group(1) == '4':
  1116. quadrant_mode = 'SINGLE'
  1117. else:
  1118. quadrant_mode = 'MULTI'
  1119. continue
  1120. ### G36* - Begin region
  1121. if self.regionon_re.search(gline):
  1122. if len(path) > 1:
  1123. # Take care of what is left in the path
  1124. ## --- Buffered ---
  1125. width = self.apertures[last_path_aperture]["size"]
  1126. geo = LineString(path).buffer(width/2)
  1127. poly_buffer.append(geo)
  1128. path = [path[-1]]
  1129. making_region = True
  1130. continue
  1131. ### G37* - End region
  1132. if self.regionoff_re.search(gline):
  1133. making_region = False
  1134. # Only one path defines region?
  1135. # This can happen if D02 happened before G37 and
  1136. # is not and error.
  1137. if len(path) < 3:
  1138. # print "ERROR: Path contains less than 3 points:"
  1139. # print path
  1140. # print "Line (%d): " % line_num, gline
  1141. # path = []
  1142. #path = [[current_x, current_y]]
  1143. continue
  1144. # For regions we may ignore an aperture that is None
  1145. # self.regions.append({"polygon": Polygon(path),
  1146. # "aperture": last_path_aperture})
  1147. # --- Buffered ---
  1148. region = Polygon(path)
  1149. if not region.is_valid:
  1150. region = region.buffer(0)
  1151. poly_buffer.append(region)
  1152. path = [[current_x, current_y]] # Start new path
  1153. continue
  1154. ### Aperture definitions %ADD...
  1155. match = self.ad_re.search(gline)
  1156. if match:
  1157. log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  1158. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  1159. continue
  1160. ### G01/2/3* - Interpolation mode change
  1161. # Can occur along with coordinates and operation code but
  1162. # sometimes by itself (handled here).
  1163. # Example: G01*
  1164. match = self.interp_re.search(gline)
  1165. if match:
  1166. current_interpolation_mode = int(match.group(1))
  1167. continue
  1168. ### Tool/aperture change
  1169. # Example: D12*
  1170. match = self.tool_re.search(gline)
  1171. if match:
  1172. log.debug("Line %d: Aperture change to (%s)" % (line_num, match.group(1)))
  1173. current_aperture = match.group(1)
  1174. # Take care of the current path with the previous tool
  1175. if len(path) > 1:
  1176. # --- Buffered ----
  1177. width = self.apertures[last_path_aperture]["size"]
  1178. geo = LineString(path).buffer(width/2)
  1179. poly_buffer.append(geo)
  1180. path = [path[-1]]
  1181. continue
  1182. ### Polarity change
  1183. # Example: %LPD*% or %LPC*%
  1184. match = self.lpol_re.search(gline)
  1185. if match:
  1186. if len(path) > 1 and current_polarity != match.group(1):
  1187. # --- Buffered ----
  1188. width = self.apertures[last_path_aperture]["size"]
  1189. geo = LineString(path).buffer(width/2)
  1190. poly_buffer.append(geo)
  1191. path = [path[-1]]
  1192. # --- Apply buffer ---
  1193. if current_polarity == 'D':
  1194. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1195. else:
  1196. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1197. poly_buffer = []
  1198. current_polarity = match.group(1)
  1199. continue
  1200. ### Number format
  1201. # Example: %FSLAX24Y24*%
  1202. # TODO: This is ignoring most of the format. Implement the rest.
  1203. match = self.fmt_re.search(gline)
  1204. if match:
  1205. absolute = {'A': True, 'I': False}
  1206. self.int_digits = int(match.group(3))
  1207. self.frac_digits = int(match.group(4))
  1208. continue
  1209. ### Mode (IN/MM)
  1210. # Example: %MOIN*%
  1211. match = self.mode_re.search(gline)
  1212. if match:
  1213. self.units = match.group(1)
  1214. continue
  1215. ### Units (G70/1) OBSOLETE
  1216. match = self.units_re.search(gline)
  1217. if match:
  1218. self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  1219. continue
  1220. ### Absolute/relative coordinates G90/1 OBSOLETE
  1221. match = self.absrel_re.search(gline)
  1222. if match:
  1223. absolute = {'0': True, '1': False}[match.group(1)]
  1224. continue
  1225. #### Ignored lines
  1226. ## Comments
  1227. match = self.comm_re.search(gline)
  1228. if match:
  1229. continue
  1230. ## EOF
  1231. match = self.eof_re.search(gline)
  1232. if match:
  1233. continue
  1234. ### Line did not match any pattern. Warn user.
  1235. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1236. if len(path) > 1:
  1237. # EOF, create shapely LineString if something still in path
  1238. ## --- Buffered ---
  1239. width = self.apertures[last_path_aperture]["size"]
  1240. geo = LineString(path).buffer(width/2)
  1241. poly_buffer.append(geo)
  1242. # --- Apply buffer ---
  1243. if current_polarity == 'D':
  1244. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1245. else:
  1246. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1247. except Exception, err:
  1248. #print traceback.format_exc()
  1249. log.error("PARSING FAILED. Line %d: %s" % (line_num, gline))
  1250. raise
  1251. @staticmethod
  1252. def create_flash_geometry(location, aperture):
  1253. if type(location) == list:
  1254. location = Point(location)
  1255. if aperture['type'] == 'C': # Circles
  1256. return location.buffer(aperture['size']/2)
  1257. if aperture['type'] == 'R': # Rectangles
  1258. loc = location.coords[0]
  1259. width = aperture['width']
  1260. height = aperture['height']
  1261. minx = loc[0] - width/2
  1262. maxx = loc[0] + width/2
  1263. miny = loc[1] - height/2
  1264. maxy = loc[1] + height/2
  1265. return shply_box(minx, miny, maxx, maxy)
  1266. if aperture['type'] == 'O': # Obround
  1267. loc = location.coords[0]
  1268. width = aperture['width']
  1269. height = aperture['height']
  1270. if width > height:
  1271. p1 = Point(loc[0] + 0.5*(width-height), loc[1])
  1272. p2 = Point(loc[0] - 0.5*(width-height), loc[1])
  1273. c1 = p1.buffer(height*0.5)
  1274. c2 = p2.buffer(height*0.5)
  1275. else:
  1276. p1 = Point(loc[0], loc[1] + 0.5*(height-width))
  1277. p2 = Point(loc[0], loc[1] - 0.5*(height-width))
  1278. c1 = p1.buffer(width*0.5)
  1279. c2 = p2.buffer(width*0.5)
  1280. return cascaded_union([c1, c2]).convex_hull
  1281. if aperture['type'] == 'P': # Regular polygon
  1282. loc = location.coords[0]
  1283. diam = aperture['diam']
  1284. n_vertices = aperture['nVertices']
  1285. points = []
  1286. for i in range(0, n_vertices):
  1287. x = loc[0] + diam * (cos(2 * pi * i / n_vertices))
  1288. y = loc[1] + diam * (sin(2 * pi * i / n_vertices))
  1289. points.append((x, y))
  1290. ply = Polygon(points)
  1291. if 'rotation' in aperture:
  1292. ply = affinity.rotate(ply, aperture['rotation'])
  1293. return ply
  1294. if aperture['type'] == 'AM': # Aperture Macro
  1295. loc = location.coords[0]
  1296. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1297. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1298. return None
  1299. def create_geometry(self):
  1300. """
  1301. Geometry from a Gerber file is made up entirely of polygons.
  1302. Every stroke (linear or circular) has an aperture which gives
  1303. it thickness. Additionally, aperture strokes have non-zero area,
  1304. and regions naturally do as well.
  1305. :rtype : None
  1306. :return: None
  1307. """
  1308. # self.buffer_paths()
  1309. #
  1310. # self.fix_regions()
  1311. #
  1312. # self.do_flashes()
  1313. #
  1314. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1315. # [poly['polygon'] for poly in self.regions] +
  1316. # self.flash_geometry)
  1317. def get_bounding_box(self, margin=0.0, rounded=False):
  1318. """
  1319. Creates and returns a rectangular polygon bounding at a distance of
  1320. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1321. can optionally have rounded corners of radius equal to margin.
  1322. :param margin: Distance to enlarge the rectangular bounding
  1323. box in both positive and negative, x and y axes.
  1324. :type margin: float
  1325. :param rounded: Wether or not to have rounded corners.
  1326. :type rounded: bool
  1327. :return: The bounding box.
  1328. :rtype: Shapely.Polygon
  1329. """
  1330. bbox = self.solid_geometry.envelope.buffer(margin)
  1331. if not rounded:
  1332. bbox = bbox.envelope
  1333. return bbox
  1334. class Excellon(Geometry):
  1335. """
  1336. *ATTRIBUTES*
  1337. * ``tools`` (dict): The key is the tool name and the value is
  1338. a dictionary specifying the tool:
  1339. ================ ====================================
  1340. Key Value
  1341. ================ ====================================
  1342. C Diameter of the tool
  1343. Others Not supported (Ignored).
  1344. ================ ====================================
  1345. * ``drills`` (list): Each is a dictionary:
  1346. ================ ====================================
  1347. Key Value
  1348. ================ ====================================
  1349. point (Shapely.Point) Where to drill
  1350. tool (str) A key in ``tools``
  1351. ================ ====================================
  1352. """
  1353. def __init__(self, zeros="L"):
  1354. """
  1355. The constructor takes no parameters.
  1356. :return: Excellon object.
  1357. :rtype: Excellon
  1358. """
  1359. Geometry.__init__(self)
  1360. self.tools = {}
  1361. self.drills = []
  1362. # Trailing "T" or leading "L" (default)
  1363. #self.zeros = "T"
  1364. self.zeros = zeros
  1365. # Attributes to be included in serialization
  1366. # Always append to it because it carries contents
  1367. # from Geometry.
  1368. self.ser_attrs += ['tools', 'drills', 'zeros']
  1369. #### Patterns ####
  1370. # Regex basics:
  1371. # ^ - beginning
  1372. # $ - end
  1373. # *: 0 or more, +: 1 or more, ?: 0 or 1
  1374. # M48 - Beggining of Part Program Header
  1375. self.hbegin_re = re.compile(r'^M48$')
  1376. # M95 or % - End of Part Program Header
  1377. # NOTE: % has different meaning in the body
  1378. self.hend_re = re.compile(r'^(?:M95|%)$')
  1379. # FMAT Excellon format
  1380. self.fmat_re = re.compile(r'^FMAT,([12])$')
  1381. # Number format and units
  1382. # INCH uses 6 digits
  1383. # METRIC uses 5/6
  1384. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  1385. # Tool definition/parameters (?= is look-ahead
  1386. # NOTE: This might be an overkill!
  1387. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  1388. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1389. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1390. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1391. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  1392. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1393. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1394. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1395. # Tool select
  1396. # Can have additional data after tool number but
  1397. # is ignored if present in the header.
  1398. # Warning: This will match toolset_re too.
  1399. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  1400. self.toolsel_re = re.compile(r'^T(\d+)')
  1401. # Comment
  1402. self.comm_re = re.compile(r'^;(.*)$')
  1403. # Absolute/Incremental G90/G91
  1404. self.absinc_re = re.compile(r'^G9([01])$')
  1405. # Modes of operation
  1406. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  1407. self.modes_re = re.compile(r'^G0([012345])')
  1408. # Measuring mode
  1409. # 1-metric, 2-inch
  1410. self.meas_re = re.compile(r'^M7([12])$')
  1411. # Coordinates
  1412. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  1413. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  1414. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  1415. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  1416. # R - Repeat hole (# times, X offset, Y offset)
  1417. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  1418. # Various stop/pause commands
  1419. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  1420. # Parse coordinates
  1421. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  1422. def parse_file(self, filename):
  1423. """
  1424. Reads the specified file as array of lines as
  1425. passes it to ``parse_lines()``.
  1426. :param filename: The file to be read and parsed.
  1427. :type filename: str
  1428. :return: None
  1429. """
  1430. efile = open(filename, 'r')
  1431. estr = efile.readlines()
  1432. efile.close()
  1433. self.parse_lines(estr)
  1434. def parse_lines(self, elines):
  1435. """
  1436. Main Excellon parser.
  1437. :param elines: List of strings, each being a line of Excellon code.
  1438. :type elines: list
  1439. :return: None
  1440. """
  1441. # State variables
  1442. current_tool = ""
  1443. in_header = False
  1444. current_x = None
  1445. current_y = None
  1446. #### Parsing starts here ####
  1447. line_num = 0 # Line number
  1448. for eline in elines:
  1449. line_num += 1
  1450. ### Cleanup lines
  1451. eline = eline.strip(' \r\n')
  1452. ## Header Begin/End ##
  1453. if self.hbegin_re.search(eline):
  1454. in_header = True
  1455. continue
  1456. if self.hend_re.search(eline):
  1457. in_header = False
  1458. continue
  1459. #### Body ####
  1460. if not in_header:
  1461. ## Tool change ##
  1462. match = self.toolsel_re.search(eline)
  1463. if match:
  1464. current_tool = str(int(match.group(1)))
  1465. continue
  1466. ## Coordinates without period ##
  1467. match = self.coordsnoperiod_re.search(eline)
  1468. if match:
  1469. try:
  1470. #x = float(match.group(1))/10000
  1471. x = self.parse_number(match.group(1))
  1472. current_x = x
  1473. except TypeError:
  1474. x = current_x
  1475. try:
  1476. #y = float(match.group(2))/10000
  1477. y = self.parse_number(match.group(2))
  1478. current_y = y
  1479. except TypeError:
  1480. y = current_y
  1481. if x is None or y is None:
  1482. log.error("Missing coordinates")
  1483. continue
  1484. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1485. continue
  1486. ## Coordinates with period: Use literally. ##
  1487. match = self.coordsperiod_re.search(eline)
  1488. if match:
  1489. try:
  1490. x = float(match.group(1))
  1491. current_x = x
  1492. except TypeError:
  1493. x = current_x
  1494. try:
  1495. y = float(match.group(2))
  1496. current_y = y
  1497. except TypeError:
  1498. y = current_y
  1499. if x is None or y is None:
  1500. log.error("Missing coordinates")
  1501. continue
  1502. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1503. continue
  1504. #### Header ####
  1505. if in_header:
  1506. ## Tool definitions ##
  1507. match = self.toolset_re.search(eline)
  1508. if match:
  1509. name = str(int(match.group(1)))
  1510. spec = {
  1511. "C": float(match.group(2)),
  1512. # "F": float(match.group(3)),
  1513. # "S": float(match.group(4)),
  1514. # "B": float(match.group(5)),
  1515. # "H": float(match.group(6)),
  1516. # "Z": float(match.group(7))
  1517. }
  1518. self.tools[name] = spec
  1519. continue
  1520. ## Units and number format ##
  1521. match = self.units_re.match(eline)
  1522. if match:
  1523. self.zeros = match.group(2) or self.zeros # "T" or "L". Might be empty
  1524. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  1525. continue
  1526. log.warning("Line ignored: %s" % eline)
  1527. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  1528. def parse_number(self, number_str):
  1529. """
  1530. Parses coordinate numbers without period.
  1531. :param number_str: String representing the numerical value.
  1532. :type number_str: str
  1533. :return: Floating point representation of the number
  1534. :rtype: foat
  1535. """
  1536. if self.zeros == "L":
  1537. # With leading zeros, when you type in a coordinate,
  1538. # the leading zeros must always be included. Trailing zeros
  1539. # are unneeded and may be left off. The CNC-7 will automatically add them.
  1540. # r'^[-\+]?(0*)(\d*)'
  1541. # 6 digits are divided by 10^4
  1542. # If less than size digits, they are automatically added,
  1543. # 5 digits then are divided by 10^3 and so on.
  1544. match = self.leadingzeros_re.search(number_str)
  1545. return float(number_str)/(10**(len(match.group(1)) + len(match.group(2)) - 2))
  1546. else: # Trailing
  1547. # You must show all zeros to the right of the number and can omit
  1548. # all zeros to the left of the number. The CNC-7 will count the number
  1549. # of digits you typed and automatically fill in the missing zeros.
  1550. if self.units.lower() == "in": # Inches is 00.0000
  1551. return float(number_str)/10000
  1552. return float(number_str)/1000 # Metric is 000.000
  1553. def create_geometry(self):
  1554. """
  1555. Creates circles of the tool diameter at every point
  1556. specified in ``self.drills``.
  1557. :return: None
  1558. """
  1559. self.solid_geometry = []
  1560. for drill in self.drills:
  1561. #poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  1562. tooldia = self.tools[drill['tool']]['C']
  1563. poly = drill['point'].buffer(tooldia/2.0)
  1564. self.solid_geometry.append(poly)
  1565. def scale(self, factor):
  1566. """
  1567. Scales geometry on the XY plane in the object by a given factor.
  1568. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1569. :param factor: Number by which to scale the object.
  1570. :type factor: float
  1571. :return: None
  1572. :rtype: NOne
  1573. """
  1574. # Drills
  1575. for drill in self.drills:
  1576. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  1577. self.create_geometry()
  1578. def offset(self, vect):
  1579. """
  1580. Offsets geometry on the XY plane in the object by a given vector.
  1581. :param vect: (x, y) offset vector.
  1582. :type vect: tuple
  1583. :return: None
  1584. """
  1585. dx, dy = vect
  1586. # Drills
  1587. for drill in self.drills:
  1588. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  1589. # Recreate geometry
  1590. self.create_geometry()
  1591. def mirror(self, axis, point):
  1592. """
  1593. :param axis: "X" or "Y" indicates around which axis to mirror.
  1594. :type axis: str
  1595. :param point: [x, y] point belonging to the mirror axis.
  1596. :type point: list
  1597. :return: None
  1598. """
  1599. px, py = point
  1600. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1601. # Modify data
  1602. for drill in self.drills:
  1603. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  1604. # Recreate geometry
  1605. self.create_geometry()
  1606. def convert_units(self, units):
  1607. factor = Geometry.convert_units(self, units)
  1608. # Tools
  1609. for tname in self.tools:
  1610. self.tools[tname]["C"] *= factor
  1611. self.create_geometry()
  1612. return factor
  1613. class CNCjob(Geometry):
  1614. """
  1615. Represents work to be done by a CNC machine.
  1616. *ATTRIBUTES*
  1617. * ``gcode_parsed`` (list): Each is a dictionary:
  1618. ===================== =========================================
  1619. Key Value
  1620. ===================== =========================================
  1621. geom (Shapely.LineString) Tool path (XY plane)
  1622. kind (string) "AB", A is "T" (travel) or
  1623. "C" (cut). B is "F" (fast) or "S" (slow).
  1624. ===================== =========================================
  1625. """
  1626. defaults = {
  1627. "zdownrate": None
  1628. }
  1629. def __init__(self, units="in", kind="generic", z_move=0.1,
  1630. feedrate=3.0, z_cut=-0.002, tooldia=0.0, zdownrate=None):
  1631. Geometry.__init__(self)
  1632. self.kind = kind
  1633. self.units = units
  1634. self.z_cut = z_cut
  1635. self.z_move = z_move
  1636. self.feedrate = feedrate
  1637. self.tooldia = tooldia
  1638. self.unitcode = {"IN": "G20", "MM": "G21"}
  1639. self.pausecode = "G04 P1"
  1640. self.feedminutecode = "G94"
  1641. self.absolutecode = "G90"
  1642. self.gcode = ""
  1643. self.input_geometry_bounds = None
  1644. self.gcode_parsed = None
  1645. self.steps_per_circ = 20 # Used when parsing G-code arcs
  1646. if zdownrate is not None:
  1647. self.zdownrate = float(zdownrate)
  1648. elif CNCjob.defaults["zdownrate"] is not None:
  1649. self.zdownrate = float(CNCjob.defaults["zdownrate"])
  1650. else:
  1651. self.zdownrate = None
  1652. # Attributes to be included in serialization
  1653. # Always append to it because it carries contents
  1654. # from Geometry.
  1655. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  1656. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  1657. 'steps_per_circ']
  1658. # Buffer for linear (No polygons or iterable geometry) elements
  1659. # and their properties.
  1660. self.flat_geometry = []
  1661. # 2D index of self.flat_geometry
  1662. self.flat_geometry_rtree = rtindex.Index()
  1663. # Current insert position to flat_geometry
  1664. self.fg_current_index = 0
  1665. def flatten(self, geo):
  1666. """
  1667. Flattens the input geometry into an array of non-iterable geometry
  1668. elements and indexes into rtree by their first and last coordinate
  1669. pairs.
  1670. :param geo:
  1671. :return:
  1672. """
  1673. try:
  1674. for g in geo:
  1675. self.flatten(g)
  1676. except TypeError: # is not iterable
  1677. self.flat_geometry.append({"path": geo})
  1678. self.flat_geometry_rtree.insert(self.fg_current_index, geo.coords[0])
  1679. self.flat_geometry_rtree.insert(self.fg_current_index, geo.coords[-1])
  1680. self.fg_current_index += 1
  1681. def convert_units(self, units):
  1682. factor = Geometry.convert_units(self, units)
  1683. log.debug("CNCjob.convert_units()")
  1684. self.z_cut *= factor
  1685. self.z_move *= factor
  1686. self.feedrate *= factor
  1687. self.tooldia *= factor
  1688. return factor
  1689. def generate_from_excellon(self, exobj):
  1690. """
  1691. Generates G-code for drilling from Excellon object.
  1692. self.gcode becomes a list, each element is a
  1693. different job for each tool in the excellon code.
  1694. """
  1695. self.kind = "drill"
  1696. self.gcode = []
  1697. t = "G00 X%.4fY%.4f\n"
  1698. down = "G01 Z%.4f\n" % self.z_cut
  1699. up = "G01 Z%.4f\n" % self.z_move
  1700. for tool in exobj.tools:
  1701. points = []
  1702. for drill in exobj.drill:
  1703. if drill['tool'] == tool:
  1704. points.append(drill['point'])
  1705. gcode = self.unitcode[self.units.upper()] + "\n"
  1706. gcode += self.absolutecode + "\n"
  1707. gcode += self.feedminutecode + "\n"
  1708. gcode += "F%.2f\n" % self.feedrate
  1709. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1710. gcode += "M03\n" # Spindle start
  1711. gcode += self.pausecode + "\n"
  1712. for point in points:
  1713. gcode += t % point
  1714. gcode += down + up
  1715. gcode += t % (0, 0)
  1716. gcode += "M05\n" # Spindle stop
  1717. self.gcode.append(gcode)
  1718. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  1719. """
  1720. Creates gcode for this object from an Excellon object
  1721. for the specified tools.
  1722. :param exobj: Excellon object to process
  1723. :type exobj: Excellon
  1724. :param tools: Comma separated tool names
  1725. :type: tools: str
  1726. :return: None
  1727. :rtype: None
  1728. """
  1729. log.debug("Creating CNC Job from Excellon...")
  1730. if tools == "all":
  1731. tools = [tool for tool in exobj.tools]
  1732. else:
  1733. tools = [x.strip() for x in tools.split(",")]
  1734. tools = filter(lambda i: i in exobj.tools, tools)
  1735. log.debug("Tools are: %s" % str(tools))
  1736. points = []
  1737. for drill in exobj.drills:
  1738. if drill['tool'] in tools:
  1739. points.append(drill['point'])
  1740. log.debug("Found %d drills." % len(points))
  1741. #self.kind = "drill"
  1742. self.gcode = []
  1743. t = "G00 X%.4fY%.4f\n"
  1744. down = "G01 Z%.4f\n" % self.z_cut
  1745. up = "G01 Z%.4f\n" % self.z_move
  1746. gcode = self.unitcode[self.units.upper()] + "\n"
  1747. gcode += self.absolutecode + "\n"
  1748. gcode += self.feedminutecode + "\n"
  1749. gcode += "F%.2f\n" % self.feedrate
  1750. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1751. gcode += "M03\n" # Spindle start
  1752. gcode += self.pausecode + "\n"
  1753. for point in points:
  1754. x, y = point.coords.xy
  1755. gcode += t % (x[0], y[0])
  1756. gcode += down + up
  1757. gcode += t % (0, 0)
  1758. gcode += "M05\n" # Spindle stop
  1759. self.gcode = gcode
  1760. def generate_from_geometry(self, geometry, append=True, tooldia=None, tolerance=0):
  1761. """
  1762. Generates G-Code from a Geometry object. Stores in ``self.gcode``.
  1763. :param geometry: Geometry defining the toolpath
  1764. :type geometry: Geometry
  1765. :param append: Wether to append to self.gcode or re-write it.
  1766. :type append: bool
  1767. :param tooldia: If given, sets the tooldia property but does
  1768. not affect the process in any other way.
  1769. :type tooldia: bool
  1770. :param tolerance: All points in the simplified object will be within the
  1771. tolerance distance of the original geometry.
  1772. :return: None
  1773. :rtype: None
  1774. """
  1775. if tooldia is not None:
  1776. self.tooldia = tooldia
  1777. self.input_geometry_bounds = geometry.bounds()
  1778. if not append:
  1779. self.gcode = ""
  1780. # Initial G-Code
  1781. self.gcode = self.unitcode[self.units.upper()] + "\n"
  1782. self.gcode += self.absolutecode + "\n"
  1783. self.gcode += self.feedminutecode + "\n"
  1784. self.gcode += "F%.2f\n" % self.feedrate
  1785. self.gcode += "G00 Z%.4f\n" % self.z_move # Move (up) to travel height
  1786. self.gcode += "M03\n" # Spindle start
  1787. self.gcode += self.pausecode + "\n"
  1788. # Iterate over geometry and run individual methods
  1789. # depending on type
  1790. for geo in geometry.solid_geometry:
  1791. if type(geo) == Polygon:
  1792. self.gcode += self.polygon2gcode(geo, tolerance=tolerance)
  1793. continue
  1794. if type(geo) == LineString or type(geo) == LinearRing:
  1795. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1796. continue
  1797. if type(geo) == Point:
  1798. self.gcode += self.point2gcode(geo)
  1799. continue
  1800. if type(geo) == MultiPolygon:
  1801. for poly in geo:
  1802. self.gcode += self.polygon2gcode(poly, tolerance=tolerance)
  1803. continue
  1804. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  1805. # Finish
  1806. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1807. self.gcode += "G00 X0Y0\n"
  1808. self.gcode += "M05\n" # Spindle stop
  1809. def generate_from_geometry_2(self, geometry, append=True, tooldia=None, tolerance=0):
  1810. """
  1811. Second algorithm to generate from Geometry.
  1812. :param geometry:
  1813. :param append:
  1814. :param tooldia:
  1815. :param tolerance:
  1816. :return:
  1817. """
  1818. assert isinstance(geometry, Geometry)
  1819. flat_geometry, rtindex = geometry.flatten_to_paths()
  1820. if tooldia is not None:
  1821. self.tooldia = tooldia
  1822. self.input_geometry_bounds = geometry.bounds()
  1823. if not append:
  1824. self.gcode = ""
  1825. # Initial G-Code
  1826. self.gcode = self.unitcode[self.units.upper()] + "\n"
  1827. self.gcode += self.absolutecode + "\n"
  1828. self.gcode += self.feedminutecode + "\n"
  1829. self.gcode += "F%.2f\n" % self.feedrate
  1830. self.gcode += "G00 Z%.4f\n" % self.z_move # Move (up) to travel height
  1831. self.gcode += "M03\n" # Spindle start
  1832. self.gcode += self.pausecode + "\n"
  1833. # Iterate over geometry and run individual methods
  1834. # depending on type
  1835. # for geo in flat_geometry:
  1836. #
  1837. # if type(geo) == LineString or type(geo) == LinearRing:
  1838. # self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1839. # continue
  1840. #
  1841. # if type(geo) == Point:
  1842. # self.gcode += self.point2gcode(geo)
  1843. # continue
  1844. #
  1845. # log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  1846. hits = list(rtindex.nearest((0, 0), 1))
  1847. while len(hits) > 0:
  1848. geo = flat_geometry[hits[0]]
  1849. if type(geo) == LineString or type(geo) == LinearRing:
  1850. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1851. elif type(geo) == Point:
  1852. self.gcode += self.point2gcode(geo)
  1853. else:
  1854. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  1855. start_pt = geo.coords[0]
  1856. stop_pt = geo.coords[-1]
  1857. rtindex.delete(hits[0], start_pt)
  1858. rtindex.delete(hits[0], stop_pt)
  1859. hits = list(rtindex.nearest(stop_pt, 1))
  1860. # Finish
  1861. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1862. self.gcode += "G00 X0Y0\n"
  1863. self.gcode += "M05\n" # Spindle stop
  1864. def pre_parse(self, gtext):
  1865. """
  1866. Separates parts of the G-Code text into a list of dictionaries.
  1867. Used by ``self.gcode_parse()``.
  1868. :param gtext: A single string with g-code
  1869. """
  1870. # Units: G20-inches, G21-mm
  1871. units_re = re.compile(r'^G2([01])')
  1872. # TODO: This has to be re-done
  1873. gcmds = []
  1874. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  1875. for line in lines:
  1876. # Clean up
  1877. line = line.strip()
  1878. # Remove comments
  1879. # NOTE: Limited to 1 bracket pair
  1880. op = line.find("(")
  1881. cl = line.find(")")
  1882. #if op > -1 and cl > op:
  1883. if cl > op > -1:
  1884. #comment = line[op+1:cl]
  1885. line = line[:op] + line[(cl+1):]
  1886. # Units
  1887. match = units_re.match(line)
  1888. if match:
  1889. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  1890. # Parse GCode
  1891. # 0 4 12
  1892. # G01 X-0.007 Y-0.057
  1893. # --> codes_idx = [0, 4, 12]
  1894. codes = "NMGXYZIJFP"
  1895. codes_idx = []
  1896. i = 0
  1897. for ch in line:
  1898. if ch in codes:
  1899. codes_idx.append(i)
  1900. i += 1
  1901. n_codes = len(codes_idx)
  1902. if n_codes == 0:
  1903. continue
  1904. # Separate codes in line
  1905. parts = []
  1906. for p in range(n_codes-1):
  1907. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  1908. parts.append(line[codes_idx[-1]:].strip())
  1909. # Separate codes from values
  1910. cmds = {}
  1911. for part in parts:
  1912. cmds[part[0]] = float(part[1:])
  1913. gcmds.append(cmds)
  1914. return gcmds
  1915. def gcode_parse(self):
  1916. """
  1917. G-Code parser (from self.gcode). Generates dictionary with
  1918. single-segment LineString's and "kind" indicating cut or travel,
  1919. fast or feedrate speed.
  1920. """
  1921. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1922. # Results go here
  1923. geometry = []
  1924. # TODO: Merge into single parser?
  1925. gobjs = self.pre_parse(self.gcode)
  1926. # Last known instruction
  1927. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  1928. # Current path: temporary storage until tool is
  1929. # lifted or lowered.
  1930. path = [(0, 0)]
  1931. # Process every instruction
  1932. for gobj in gobjs:
  1933. ## Changing height
  1934. if 'Z' in gobj:
  1935. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  1936. log.warning("Non-orthogonal motion: From %s" % str(current))
  1937. log.warning(" To: %s" % str(gobj))
  1938. current['Z'] = gobj['Z']
  1939. # Store the path into geometry and reset path
  1940. if len(path) > 1:
  1941. geometry.append({"geom": LineString(path),
  1942. "kind": kind})
  1943. path = [path[-1]] # Start with the last point of last path.
  1944. if 'G' in gobj:
  1945. current['G'] = int(gobj['G'])
  1946. if 'X' in gobj or 'Y' in gobj:
  1947. if 'X' in gobj:
  1948. x = gobj['X']
  1949. else:
  1950. x = current['X']
  1951. if 'Y' in gobj:
  1952. y = gobj['Y']
  1953. else:
  1954. y = current['Y']
  1955. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1956. if current['Z'] > 0:
  1957. kind[0] = 'T'
  1958. if current['G'] > 0:
  1959. kind[1] = 'S'
  1960. arcdir = [None, None, "cw", "ccw"]
  1961. if current['G'] in [0, 1]: # line
  1962. path.append((x, y))
  1963. if current['G'] in [2, 3]: # arc
  1964. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  1965. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  1966. start = arctan2(-gobj['J'], -gobj['I'])
  1967. stop = arctan2(-center[1]+y, -center[0]+x)
  1968. path += arc(center, radius, start, stop,
  1969. arcdir[current['G']],
  1970. self.steps_per_circ)
  1971. # Update current instruction
  1972. for code in gobj:
  1973. current[code] = gobj[code]
  1974. # There might not be a change in height at the
  1975. # end, therefore, see here too if there is
  1976. # a final path.
  1977. if len(path) > 1:
  1978. geometry.append({"geom": LineString(path),
  1979. "kind": kind})
  1980. self.gcode_parsed = geometry
  1981. return geometry
  1982. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  1983. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1984. # alpha={"T": 0.3, "C": 1.0}):
  1985. # """
  1986. # Creates a Matplotlib figure with a plot of the
  1987. # G-code job.
  1988. # """
  1989. # if tooldia is None:
  1990. # tooldia = self.tooldia
  1991. #
  1992. # fig = Figure(dpi=dpi)
  1993. # ax = fig.add_subplot(111)
  1994. # ax.set_aspect(1)
  1995. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  1996. # ax.set_xlim(xmin-margin, xmax+margin)
  1997. # ax.set_ylim(ymin-margin, ymax+margin)
  1998. #
  1999. # if tooldia == 0:
  2000. # for geo in self.gcode_parsed:
  2001. # linespec = '--'
  2002. # linecolor = color[geo['kind'][0]][1]
  2003. # if geo['kind'][0] == 'C':
  2004. # linespec = 'k-'
  2005. # x, y = geo['geom'].coords.xy
  2006. # ax.plot(x, y, linespec, color=linecolor)
  2007. # else:
  2008. # for geo in self.gcode_parsed:
  2009. # poly = geo['geom'].buffer(tooldia/2.0)
  2010. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  2011. # edgecolor=color[geo['kind'][0]][1],
  2012. # alpha=alpha[geo['kind'][0]], zorder=2)
  2013. # ax.add_patch(patch)
  2014. #
  2015. # return fig
  2016. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  2017. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  2018. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  2019. """
  2020. Plots the G-code job onto the given axes.
  2021. :param axes: Matplotlib axes on which to plot.
  2022. :param tooldia: Tool diameter.
  2023. :param dpi: Not used!
  2024. :param margin: Not used!
  2025. :param color: Color specification.
  2026. :param alpha: Transparency specification.
  2027. :param tool_tolerance: Tolerance when drawing the toolshape.
  2028. :return: None
  2029. """
  2030. if tooldia is None:
  2031. tooldia = self.tooldia
  2032. if tooldia == 0:
  2033. for geo in self.gcode_parsed:
  2034. linespec = '--'
  2035. linecolor = color[geo['kind'][0]][1]
  2036. if geo['kind'][0] == 'C':
  2037. linespec = 'k-'
  2038. x, y = geo['geom'].coords.xy
  2039. axes.plot(x, y, linespec, color=linecolor)
  2040. else:
  2041. for geo in self.gcode_parsed:
  2042. poly = geo['geom'].buffer(tooldia/2.0).simplify(tool_tolerance)
  2043. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  2044. edgecolor=color[geo['kind'][0]][1],
  2045. alpha=alpha[geo['kind'][0]], zorder=2)
  2046. axes.add_patch(patch)
  2047. def create_geometry(self):
  2048. # TODO: This takes forever. Too much data?
  2049. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  2050. def polygon2gcode(self, polygon, tolerance=0):
  2051. """
  2052. Creates G-Code for the exterior and all interior paths
  2053. of a polygon.
  2054. :param polygon: A Shapely.Polygon
  2055. :type polygon: Shapely.Polygon
  2056. :param tolerance: All points in the simplified object will be within the
  2057. tolerance distance of the original geometry.
  2058. :type tolerance: float
  2059. :return: G-code to cut along polygon.
  2060. :rtype: str
  2061. """
  2062. if tolerance > 0:
  2063. target_polygon = polygon.simplify(tolerance)
  2064. else:
  2065. target_polygon = polygon
  2066. gcode = ""
  2067. t = "G0%d X%.4fY%.4f\n"
  2068. path = list(target_polygon.exterior.coords) # Polygon exterior
  2069. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2070. if self.zdownrate is not None:
  2071. gcode += "F%.2f\n" % self.zdownrate
  2072. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2073. gcode += "F%.2f\n" % self.feedrate
  2074. else:
  2075. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2076. for pt in path[1:]:
  2077. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2078. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2079. for ints in target_polygon.interiors: # Polygon interiors
  2080. path = list(ints.coords)
  2081. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2082. if self.zdownrate is not None:
  2083. gcode += "F%.2f\n" % self.zdownrate
  2084. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2085. gcode += "F%.2f\n" % self.feedrate
  2086. else:
  2087. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2088. for pt in path[1:]:
  2089. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2090. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2091. return gcode
  2092. def linear2gcode(self, linear, tolerance=0):
  2093. """
  2094. Generates G-code to cut along the linear feature.
  2095. :param linear: The path to cut along.
  2096. :type: Shapely.LinearRing or Shapely.Linear String
  2097. :param tolerance: All points in the simplified object will be within the
  2098. tolerance distance of the original geometry.
  2099. :type tolerance: float
  2100. :return: G-code to cut alon the linear feature.
  2101. :rtype: str
  2102. """
  2103. if tolerance > 0:
  2104. target_linear = linear.simplify(tolerance)
  2105. else:
  2106. target_linear = linear
  2107. gcode = ""
  2108. t = "G0%d X%.4fY%.4f\n"
  2109. path = list(target_linear.coords)
  2110. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2111. if self.zdownrate is not None:
  2112. gcode += "F%.2f\n" % self.zdownrate
  2113. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2114. gcode += "F%.2f\n" % self.feedrate
  2115. else:
  2116. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2117. for pt in path[1:]:
  2118. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2119. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2120. return gcode
  2121. def point2gcode(self, point):
  2122. gcode = ""
  2123. t = "G0%d X%.4fY%.4f\n"
  2124. path = list(point.coords)
  2125. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2126. if self.zdownrate is not None:
  2127. gcode += "F%.2f\n" % self.zdownrate
  2128. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2129. gcode += "F%.2f\n" % self.feedrate
  2130. else:
  2131. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2132. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2133. return gcode
  2134. def scale(self, factor):
  2135. """
  2136. Scales all the geometry on the XY plane in the object by the
  2137. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  2138. not altered.
  2139. :param factor: Number by which to scale the object.
  2140. :type factor: float
  2141. :return: None
  2142. :rtype: None
  2143. """
  2144. for g in self.gcode_parsed:
  2145. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  2146. self.create_geometry()
  2147. def offset(self, vect):
  2148. """
  2149. Offsets all the geometry on the XY plane in the object by the
  2150. given vector.
  2151. :param vect: (x, y) offset vector.
  2152. :type vect: tuple
  2153. :return: None
  2154. """
  2155. dx, dy = vect
  2156. for g in self.gcode_parsed:
  2157. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  2158. self.create_geometry()
  2159. # def get_bounds(geometry_set):
  2160. # xmin = Inf
  2161. # ymin = Inf
  2162. # xmax = -Inf
  2163. # ymax = -Inf
  2164. #
  2165. # #print "Getting bounds of:", str(geometry_set)
  2166. # for gs in geometry_set:
  2167. # try:
  2168. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  2169. # xmin = min([xmin, gxmin])
  2170. # ymin = min([ymin, gymin])
  2171. # xmax = max([xmax, gxmax])
  2172. # ymax = max([ymax, gymax])
  2173. # except:
  2174. # print "DEV WARNING: Tried to get bounds of empty geometry."
  2175. #
  2176. # return [xmin, ymin, xmax, ymax]
  2177. def get_bounds(geometry_list):
  2178. xmin = Inf
  2179. ymin = Inf
  2180. xmax = -Inf
  2181. ymax = -Inf
  2182. #print "Getting bounds of:", str(geometry_set)
  2183. for gs in geometry_list:
  2184. try:
  2185. gxmin, gymin, gxmax, gymax = gs.bounds()
  2186. xmin = min([xmin, gxmin])
  2187. ymin = min([ymin, gymin])
  2188. xmax = max([xmax, gxmax])
  2189. ymax = max([ymax, gymax])
  2190. except:
  2191. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  2192. return [xmin, ymin, xmax, ymax]
  2193. def arc(center, radius, start, stop, direction, steps_per_circ):
  2194. """
  2195. Creates a list of point along the specified arc.
  2196. :param center: Coordinates of the center [x, y]
  2197. :type center: list
  2198. :param radius: Radius of the arc.
  2199. :type radius: float
  2200. :param start: Starting angle in radians
  2201. :type start: float
  2202. :param stop: End angle in radians
  2203. :type stop: float
  2204. :param direction: Orientation of the arc, "CW" or "CCW"
  2205. :type direction: string
  2206. :param steps_per_circ: Number of straight line segments to
  2207. represent a circle.
  2208. :type steps_per_circ: int
  2209. :return: The desired arc, as list of tuples
  2210. :rtype: list
  2211. """
  2212. # TODO: Resolution should be established by fraction of total length, not angle.
  2213. da_sign = {"cw": -1.0, "ccw": 1.0}
  2214. points = []
  2215. if direction == "ccw" and stop <= start:
  2216. stop += 2*pi
  2217. if direction == "cw" and stop >= start:
  2218. stop -= 2*pi
  2219. angle = abs(stop - start)
  2220. #angle = stop-start
  2221. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  2222. delta_angle = da_sign[direction]*angle*1.0/steps
  2223. for i in range(steps+1):
  2224. theta = start + delta_angle*i
  2225. points.append((center[0]+radius*cos(theta), center[1]+radius*sin(theta)))
  2226. return points
  2227. def arc_angle(start, stop, direction):
  2228. if direction == "ccw" and stop <= start:
  2229. stop += 2*pi
  2230. if direction == "cw" and stop >= start:
  2231. stop -= 2*pi
  2232. angle = abs(stop - start)
  2233. return angle
  2234. # def clear_poly(poly, tooldia, overlap=0.1):
  2235. # """
  2236. # Creates a list of Shapely geometry objects covering the inside
  2237. # of a Shapely.Polygon. Use for removing all the copper in a region
  2238. # or bed flattening.
  2239. #
  2240. # :param poly: Target polygon
  2241. # :type poly: Shapely.Polygon
  2242. # :param tooldia: Diameter of the tool
  2243. # :type tooldia: float
  2244. # :param overlap: Fraction of the tool diameter to overlap
  2245. # in each pass.
  2246. # :type overlap: float
  2247. # :return: list of Shapely.Polygon
  2248. # :rtype: list
  2249. # """
  2250. # poly_cuts = [poly.buffer(-tooldia/2.0)]
  2251. # while True:
  2252. # poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  2253. # if poly.area > 0:
  2254. # poly_cuts.append(poly)
  2255. # else:
  2256. # break
  2257. # return poly_cuts
  2258. def find_polygon(poly_set, point):
  2259. """
  2260. Return the first polygon in the list of polygons poly_set
  2261. that contains the given point.
  2262. """
  2263. p = Point(point)
  2264. for poly in poly_set:
  2265. if poly.contains(p):
  2266. return poly
  2267. return None
  2268. def to_dict(obj):
  2269. """
  2270. Makes a Shapely geometry object into serializeable form.
  2271. :param obj: Shapely geometry.
  2272. :type obj: BaseGeometry
  2273. :return: Dictionary with serializable form if ``obj`` was
  2274. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  2275. """
  2276. if isinstance(obj, ApertureMacro):
  2277. return {
  2278. "__class__": "ApertureMacro",
  2279. "__inst__": obj.to_dict()
  2280. }
  2281. if isinstance(obj, BaseGeometry):
  2282. return {
  2283. "__class__": "Shply",
  2284. "__inst__": sdumps(obj)
  2285. }
  2286. return obj
  2287. def dict2obj(d):
  2288. """
  2289. Default deserializer.
  2290. :param d: Serializable dictionary representation of an object
  2291. to be reconstructed.
  2292. :return: Reconstructed object.
  2293. """
  2294. if '__class__' in d and '__inst__' in d:
  2295. if d['__class__'] == "Shply":
  2296. return sloads(d['__inst__'])
  2297. if d['__class__'] == "ApertureMacro":
  2298. am = ApertureMacro()
  2299. am.from_dict(d['__inst__'])
  2300. return am
  2301. return d
  2302. else:
  2303. return d
  2304. def plotg(geo, solid_poly=False):
  2305. try:
  2306. _ = iter(geo)
  2307. except:
  2308. geo = [geo]
  2309. for g in geo:
  2310. if type(g) == Polygon:
  2311. if solid_poly:
  2312. patch = PolygonPatch(g,
  2313. facecolor="#BBF268",
  2314. edgecolor="#006E20",
  2315. alpha=0.75,
  2316. zorder=2)
  2317. ax = subplot(111)
  2318. ax.add_patch(patch)
  2319. else:
  2320. x, y = g.exterior.coords.xy
  2321. plot(x, y)
  2322. for ints in g.interiors:
  2323. x, y = ints.coords.xy
  2324. plot(x, y)
  2325. continue
  2326. if type(g) == LineString or type(g) == LinearRing:
  2327. x, y = g.coords.xy
  2328. plot(x, y)
  2329. continue
  2330. if type(g) == Point:
  2331. x, y = g.coords.xy
  2332. plot(x, y, 'o')
  2333. continue
  2334. try:
  2335. _ = iter(g)
  2336. plotg(g)
  2337. except:
  2338. log.error("Cannot plot: " + str(type(g)))
  2339. continue
  2340. def parse_gerber_number(strnumber, frac_digits):
  2341. """
  2342. Parse a single number of Gerber coordinates.
  2343. :param strnumber: String containing a number in decimal digits
  2344. from a coordinate data block, possibly with a leading sign.
  2345. :type strnumber: str
  2346. :param frac_digits: Number of digits used for the fractional
  2347. part of the number
  2348. :type frac_digits: int
  2349. :return: The number in floating point.
  2350. :rtype: float
  2351. """
  2352. return int(strnumber)*(10**(-frac_digits))
  2353. def voronoi(P):
  2354. """
  2355. Returns a list of all edges of the voronoi diagram for the given input points.
  2356. """
  2357. delauny = Delaunay(P)
  2358. triangles = delauny.points[delauny.vertices]
  2359. circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  2360. long_lines_endpoints = []
  2361. lineIndices = []
  2362. for i, triangle in enumerate(triangles):
  2363. circum_center = circum_centers[i]
  2364. for j, neighbor in enumerate(delauny.neighbors[i]):
  2365. if neighbor != -1:
  2366. lineIndices.append((i, neighbor))
  2367. else:
  2368. ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  2369. ps = np.array((ps[1], -ps[0]))
  2370. middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  2371. di = middle - triangle[j]
  2372. ps /= np.linalg.norm(ps)
  2373. di /= np.linalg.norm(di)
  2374. if np.dot(di, ps) < 0.0:
  2375. ps *= -1000.0
  2376. else:
  2377. ps *= 1000.0
  2378. long_lines_endpoints.append(circum_center + ps)
  2379. lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  2380. vertices = np.vstack((circum_centers, long_lines_endpoints))
  2381. # filter out any duplicate lines
  2382. lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  2383. lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  2384. lineIndicesUnique = np.unique(lineIndicesTupled)
  2385. return vertices, lineIndicesUnique
  2386. def triangle_csc(pts):
  2387. rows, cols = pts.shape
  2388. A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  2389. [np.ones((1, rows)), np.zeros((1, 1))]])
  2390. b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  2391. x = np.linalg.solve(A,b)
  2392. bary_coords = x[:-1]
  2393. return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  2394. def voronoi_cell_lines(points, vertices, lineIndices):
  2395. """
  2396. Returns a mapping from a voronoi cell to its edges.
  2397. :param points: shape (m,2)
  2398. :param vertices: shape (n,2)
  2399. :param lineIndices: shape (o,2)
  2400. :rtype: dict point index -> list of shape (n,2) with vertex indices
  2401. """
  2402. kd = KDTree(points)
  2403. cells = collections.defaultdict(list)
  2404. for i1, i2 in lineIndices:
  2405. v1, v2 = vertices[i1], vertices[i2]
  2406. mid = (v1+v2)/2
  2407. _, (p1Idx, p2Idx) = kd.query(mid, 2)
  2408. cells[p1Idx].append((i1, i2))
  2409. cells[p2Idx].append((i1, i2))
  2410. return cells
  2411. def voronoi_edges2polygons(cells):
  2412. """
  2413. Transforms cell edges into polygons.
  2414. :param cells: as returned from voronoi_cell_lines
  2415. :rtype: dict point index -> list of vertex indices which form a polygon
  2416. """
  2417. # first, close the outer cells
  2418. for pIdx, lineIndices_ in cells.items():
  2419. dangling_lines = []
  2420. for i1, i2 in lineIndices_:
  2421. connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  2422. assert 1 <= len(connections) <= 2
  2423. if len(connections) == 1:
  2424. dangling_lines.append((i1, i2))
  2425. assert len(dangling_lines) in [0, 2]
  2426. if len(dangling_lines) == 2:
  2427. (i11, i12), (i21, i22) = dangling_lines
  2428. # determine which line ends are unconnected
  2429. connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  2430. i11Unconnected = len(connected) == 0
  2431. connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  2432. i21Unconnected = len(connected) == 0
  2433. startIdx = i11 if i11Unconnected else i12
  2434. endIdx = i21 if i21Unconnected else i22
  2435. cells[pIdx].append((startIdx, endIdx))
  2436. # then, form polygons by storing vertex indices in (counter-)clockwise order
  2437. polys = dict()
  2438. for pIdx, lineIndices_ in cells.items():
  2439. # get a directed graph which contains both directions and arbitrarily follow one of both
  2440. directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  2441. directedGraphMap = collections.defaultdict(list)
  2442. for (i1, i2) in directedGraph:
  2443. directedGraphMap[i1].append(i2)
  2444. orderedEdges = []
  2445. currentEdge = directedGraph[0]
  2446. while len(orderedEdges) < len(lineIndices_):
  2447. i1 = currentEdge[1]
  2448. i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  2449. nextEdge = (i1, i2)
  2450. orderedEdges.append(nextEdge)
  2451. currentEdge = nextEdge
  2452. polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  2453. return polys
  2454. def voronoi_polygons(points):
  2455. """
  2456. Returns the voronoi polygon for each input point.
  2457. :param points: shape (n,2)
  2458. :rtype: list of n polygons where each polygon is an array of vertices
  2459. """
  2460. vertices, lineIndices = voronoi(points)
  2461. cells = voronoi_cell_lines(points, vertices, lineIndices)
  2462. polys = voronoi_edges2polygons(cells)
  2463. polylist = []
  2464. for i in xrange(len(points)):
  2465. poly = vertices[np.asarray(polys[i])]
  2466. polylist.append(poly)
  2467. return polylist
  2468. class Zprofile:
  2469. def __init__(self):
  2470. # data contains lists of [x, y, z]
  2471. self.data = []
  2472. # Computed voronoi polygons (shapely)
  2473. self.polygons = []
  2474. pass
  2475. def plot_polygons(self):
  2476. axes = plt.subplot(1, 1, 1)
  2477. plt.axis([-0.05, 1.05, -0.05, 1.05])
  2478. for poly in self.polygons:
  2479. p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  2480. axes.add_patch(p)
  2481. def init_from_csv(self, filename):
  2482. pass
  2483. def init_from_string(self, zpstring):
  2484. pass
  2485. def init_from_list(self, zplist):
  2486. self.data = zplist
  2487. def generate_polygons(self):
  2488. self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  2489. def normalize(self, origin):
  2490. pass
  2491. def paste(self, path):
  2492. """
  2493. Return a list of dictionaries containing the parts of the original
  2494. path and their z-axis offset.
  2495. """
  2496. # At most one region/polygon will contain the path
  2497. containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  2498. if len(containing) > 0:
  2499. return [{"path": path, "z": self.data[containing[0]][2]}]
  2500. # All region indexes that intersect with the path
  2501. crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  2502. return [{"path": path.intersection(self.polygons[i]),
  2503. "z": self.data[i][2]} for i in crossing]
  2504. def autolist(obj):
  2505. try:
  2506. _ = iter(obj)
  2507. return obj
  2508. except TypeError:
  2509. return [obj]