camlib.py 112 KB

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