camlib.py 119 KB

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