camlib.py 141 KB

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