camlib.py 140 KB

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