camlib.py 114 KB

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