camlib.py 122 KB

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