camlib.py 114 KB

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