camlib.py 114 KB

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