camlib.py 117 KB

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