camlib.py 116 KB

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