camlib.py 117 KB

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