camlib.py 130 KB

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