camlib.py 120 KB

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