camlib.py 114 KB

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