camlib.py 108 KB

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