camlib.py 119 KB

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