camlib.py 134 KB

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