camlib.py 143 KB

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