camlib.py 133 KB

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