camlib.py 126 KB

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