camlib.py 114 KB

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