camlib.py 118 KB

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