camlib.py 121 KB

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