camlib.py 124 KB

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