camlib.py 109 KB

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