camlib.py 114 KB

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