camlib.py 121 KB

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