camlib.py 140 KB

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