camlib.py 106 KB

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