camlib.py 124 KB

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