camlib.py 134 KB

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