cbook.py 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350
  1. """
  2. A collection of utility functions and classes. Originally, many
  3. (but not all) were from the Python Cookbook -- hence the name cbook.
  4. """
  5. import collections
  6. import collections.abc
  7. import contextlib
  8. import functools
  9. import gzip
  10. import itertools
  11. import math
  12. import operator
  13. import os
  14. from pathlib import Path
  15. import shlex
  16. import subprocess
  17. import sys
  18. import time
  19. import traceback
  20. import types
  21. import weakref
  22. import numpy as np
  23. try:
  24. from numpy.exceptions import VisibleDeprecationWarning # numpy >= 1.25
  25. except ImportError:
  26. from numpy import VisibleDeprecationWarning
  27. import matplotlib
  28. from matplotlib import _api, _c_internal_utils
  29. def _get_running_interactive_framework():
  30. """
  31. Return the interactive framework whose event loop is currently running, if
  32. any, or "headless" if no event loop can be started, or None.
  33. Returns
  34. -------
  35. Optional[str]
  36. One of the following values: "qt", "gtk3", "gtk4", "wx", "tk",
  37. "macosx", "headless", ``None``.
  38. """
  39. # Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as
  40. # entries can also have been explicitly set to None.
  41. QtWidgets = (
  42. sys.modules.get("PyQt6.QtWidgets")
  43. or sys.modules.get("PySide6.QtWidgets")
  44. or sys.modules.get("PyQt5.QtWidgets")
  45. or sys.modules.get("PySide2.QtWidgets")
  46. )
  47. if QtWidgets and QtWidgets.QApplication.instance():
  48. return "qt"
  49. Gtk = sys.modules.get("gi.repository.Gtk")
  50. if Gtk:
  51. if Gtk.MAJOR_VERSION == 4:
  52. from gi.repository import GLib
  53. if GLib.main_depth():
  54. return "gtk4"
  55. if Gtk.MAJOR_VERSION == 3 and Gtk.main_level():
  56. return "gtk3"
  57. wx = sys.modules.get("wx")
  58. if wx and wx.GetApp():
  59. return "wx"
  60. tkinter = sys.modules.get("tkinter")
  61. if tkinter:
  62. codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__}
  63. for frame in sys._current_frames().values():
  64. while frame:
  65. if frame.f_code in codes:
  66. return "tk"
  67. frame = frame.f_back
  68. # premetively break reference cycle between locals and the frame
  69. del frame
  70. macosx = sys.modules.get("matplotlib.backends._macosx")
  71. if macosx and macosx.event_loop_is_running():
  72. return "macosx"
  73. if not _c_internal_utils.display_is_valid():
  74. return "headless"
  75. return None
  76. def _exception_printer(exc):
  77. if _get_running_interactive_framework() in ["headless", None]:
  78. raise exc
  79. else:
  80. traceback.print_exc()
  81. class _StrongRef:
  82. """
  83. Wrapper similar to a weakref, but keeping a strong reference to the object.
  84. """
  85. def __init__(self, obj):
  86. self._obj = obj
  87. def __call__(self):
  88. return self._obj
  89. def __eq__(self, other):
  90. return isinstance(other, _StrongRef) and self._obj == other._obj
  91. def __hash__(self):
  92. return hash(self._obj)
  93. def _weak_or_strong_ref(func, callback):
  94. """
  95. Return a `WeakMethod` wrapping *func* if possible, else a `_StrongRef`.
  96. """
  97. try:
  98. return weakref.WeakMethod(func, callback)
  99. except TypeError:
  100. return _StrongRef(func)
  101. class CallbackRegistry:
  102. """
  103. Handle registering, processing, blocking, and disconnecting
  104. for a set of signals and callbacks:
  105. >>> def oneat(x):
  106. ... print('eat', x)
  107. >>> def ondrink(x):
  108. ... print('drink', x)
  109. >>> from matplotlib.cbook import CallbackRegistry
  110. >>> callbacks = CallbackRegistry()
  111. >>> id_eat = callbacks.connect('eat', oneat)
  112. >>> id_drink = callbacks.connect('drink', ondrink)
  113. >>> callbacks.process('drink', 123)
  114. drink 123
  115. >>> callbacks.process('eat', 456)
  116. eat 456
  117. >>> callbacks.process('be merry', 456) # nothing will be called
  118. >>> callbacks.disconnect(id_eat)
  119. >>> callbacks.process('eat', 456) # nothing will be called
  120. >>> with callbacks.blocked(signal='drink'):
  121. ... callbacks.process('drink', 123) # nothing will be called
  122. >>> callbacks.process('drink', 123)
  123. drink 123
  124. In practice, one should always disconnect all callbacks when they are
  125. no longer needed to avoid dangling references (and thus memory leaks).
  126. However, real code in Matplotlib rarely does so, and due to its design,
  127. it is rather difficult to place this kind of code. To get around this,
  128. and prevent this class of memory leaks, we instead store weak references
  129. to bound methods only, so when the destination object needs to die, the
  130. CallbackRegistry won't keep it alive.
  131. Parameters
  132. ----------
  133. exception_handler : callable, optional
  134. If not None, *exception_handler* must be a function that takes an
  135. `Exception` as single parameter. It gets called with any `Exception`
  136. raised by the callbacks during `CallbackRegistry.process`, and may
  137. either re-raise the exception or handle it in another manner.
  138. The default handler prints the exception (with `traceback.print_exc`) if
  139. an interactive event loop is running; it re-raises the exception if no
  140. interactive event loop is running.
  141. signals : list, optional
  142. If not None, *signals* is a list of signals that this registry handles:
  143. attempting to `process` or to `connect` to a signal not in the list
  144. throws a `ValueError`. The default, None, does not restrict the
  145. handled signals.
  146. """
  147. # We maintain two mappings:
  148. # callbacks: signal -> {cid -> weakref-to-callback}
  149. # _func_cid_map: signal -> {weakref-to-callback -> cid}
  150. def __init__(self, exception_handler=_exception_printer, *, signals=None):
  151. self._signals = None if signals is None else list(signals) # Copy it.
  152. self.exception_handler = exception_handler
  153. self.callbacks = {}
  154. self._cid_gen = itertools.count()
  155. self._func_cid_map = {}
  156. # A hidden variable that marks cids that need to be pickled.
  157. self._pickled_cids = set()
  158. def __getstate__(self):
  159. return {
  160. **vars(self),
  161. # In general, callbacks may not be pickled, so we just drop them,
  162. # unless directed otherwise by self._pickled_cids.
  163. "callbacks": {s: {cid: proxy() for cid, proxy in d.items()
  164. if cid in self._pickled_cids}
  165. for s, d in self.callbacks.items()},
  166. # It is simpler to reconstruct this from callbacks in __setstate__.
  167. "_func_cid_map": None,
  168. "_cid_gen": next(self._cid_gen)
  169. }
  170. def __setstate__(self, state):
  171. cid_count = state.pop('_cid_gen')
  172. vars(self).update(state)
  173. self.callbacks = {
  174. s: {cid: _weak_or_strong_ref(func, self._remove_proxy)
  175. for cid, func in d.items()}
  176. for s, d in self.callbacks.items()}
  177. self._func_cid_map = {
  178. s: {proxy: cid for cid, proxy in d.items()}
  179. for s, d in self.callbacks.items()}
  180. self._cid_gen = itertools.count(cid_count)
  181. def connect(self, signal, func):
  182. """Register *func* to be called when signal *signal* is generated."""
  183. if self._signals is not None:
  184. _api.check_in_list(self._signals, signal=signal)
  185. self._func_cid_map.setdefault(signal, {})
  186. proxy = _weak_or_strong_ref(func, self._remove_proxy)
  187. if proxy in self._func_cid_map[signal]:
  188. return self._func_cid_map[signal][proxy]
  189. cid = next(self._cid_gen)
  190. self._func_cid_map[signal][proxy] = cid
  191. self.callbacks.setdefault(signal, {})
  192. self.callbacks[signal][cid] = proxy
  193. return cid
  194. def _connect_picklable(self, signal, func):
  195. """
  196. Like `.connect`, but the callback is kept when pickling/unpickling.
  197. Currently internal-use only.
  198. """
  199. cid = self.connect(signal, func)
  200. self._pickled_cids.add(cid)
  201. return cid
  202. # Keep a reference to sys.is_finalizing, as sys may have been cleared out
  203. # at that point.
  204. def _remove_proxy(self, proxy, *, _is_finalizing=sys.is_finalizing):
  205. if _is_finalizing():
  206. # Weakrefs can't be properly torn down at that point anymore.
  207. return
  208. for signal, proxy_to_cid in list(self._func_cid_map.items()):
  209. cid = proxy_to_cid.pop(proxy, None)
  210. if cid is not None:
  211. del self.callbacks[signal][cid]
  212. self._pickled_cids.discard(cid)
  213. break
  214. else:
  215. # Not found
  216. return
  217. # Clean up empty dicts
  218. if len(self.callbacks[signal]) == 0:
  219. del self.callbacks[signal]
  220. del self._func_cid_map[signal]
  221. def disconnect(self, cid):
  222. """
  223. Disconnect the callback registered with callback id *cid*.
  224. No error is raised if such a callback does not exist.
  225. """
  226. self._pickled_cids.discard(cid)
  227. # Clean up callbacks
  228. for signal, cid_to_proxy in list(self.callbacks.items()):
  229. proxy = cid_to_proxy.pop(cid, None)
  230. if proxy is not None:
  231. break
  232. else:
  233. # Not found
  234. return
  235. proxy_to_cid = self._func_cid_map[signal]
  236. for current_proxy, current_cid in list(proxy_to_cid.items()):
  237. if current_cid == cid:
  238. assert proxy is current_proxy
  239. del proxy_to_cid[current_proxy]
  240. # Clean up empty dicts
  241. if len(self.callbacks[signal]) == 0:
  242. del self.callbacks[signal]
  243. del self._func_cid_map[signal]
  244. def process(self, s, *args, **kwargs):
  245. """
  246. Process signal *s*.
  247. All of the functions registered to receive callbacks on *s* will be
  248. called with ``*args`` and ``**kwargs``.
  249. """
  250. if self._signals is not None:
  251. _api.check_in_list(self._signals, signal=s)
  252. for ref in list(self.callbacks.get(s, {}).values()):
  253. func = ref()
  254. if func is not None:
  255. try:
  256. func(*args, **kwargs)
  257. # this does not capture KeyboardInterrupt, SystemExit,
  258. # and GeneratorExit
  259. except Exception as exc:
  260. if self.exception_handler is not None:
  261. self.exception_handler(exc)
  262. else:
  263. raise
  264. @contextlib.contextmanager
  265. def blocked(self, *, signal=None):
  266. """
  267. Block callback signals from being processed.
  268. A context manager to temporarily block/disable callback signals
  269. from being processed by the registered listeners.
  270. Parameters
  271. ----------
  272. signal : str, optional
  273. The callback signal to block. The default is to block all signals.
  274. """
  275. orig = self.callbacks
  276. try:
  277. if signal is None:
  278. # Empty out the callbacks
  279. self.callbacks = {}
  280. else:
  281. # Only remove the specific signal
  282. self.callbacks = {k: orig[k] for k in orig if k != signal}
  283. yield
  284. finally:
  285. self.callbacks = orig
  286. class silent_list(list):
  287. """
  288. A list with a short ``repr()``.
  289. This is meant to be used for a homogeneous list of artists, so that they
  290. don't cause long, meaningless output.
  291. Instead of ::
  292. [<matplotlib.lines.Line2D object at 0x7f5749fed3c8>,
  293. <matplotlib.lines.Line2D object at 0x7f5749fed4e0>,
  294. <matplotlib.lines.Line2D object at 0x7f5758016550>]
  295. one will get ::
  296. <a list of 3 Line2D objects>
  297. If ``self.type`` is None, the type name is obtained from the first item in
  298. the list (if any).
  299. """
  300. def __init__(self, type, seq=None):
  301. self.type = type
  302. if seq is not None:
  303. self.extend(seq)
  304. def __repr__(self):
  305. if self.type is not None or len(self) != 0:
  306. tp = self.type if self.type is not None else type(self[0]).__name__
  307. return f"<a list of {len(self)} {tp} objects>"
  308. else:
  309. return "<an empty list>"
  310. def _local_over_kwdict(
  311. local_var, kwargs, *keys,
  312. warning_cls=_api.MatplotlibDeprecationWarning):
  313. out = local_var
  314. for key in keys:
  315. kwarg_val = kwargs.pop(key, None)
  316. if kwarg_val is not None:
  317. if out is None:
  318. out = kwarg_val
  319. else:
  320. _api.warn_external(f'"{key}" keyword argument will be ignored',
  321. warning_cls)
  322. return out
  323. def strip_math(s):
  324. """
  325. Remove latex formatting from mathtext.
  326. Only handles fully math and fully non-math strings.
  327. """
  328. if len(s) >= 2 and s[0] == s[-1] == "$":
  329. s = s[1:-1]
  330. for tex, plain in [
  331. (r"\times", "x"), # Specifically for Formatter support.
  332. (r"\mathdefault", ""),
  333. (r"\rm", ""),
  334. (r"\cal", ""),
  335. (r"\tt", ""),
  336. (r"\it", ""),
  337. ("\\", ""),
  338. ("{", ""),
  339. ("}", ""),
  340. ]:
  341. s = s.replace(tex, plain)
  342. return s
  343. def _strip_comment(s):
  344. """Strip everything from the first unquoted #."""
  345. pos = 0
  346. while True:
  347. quote_pos = s.find('"', pos)
  348. hash_pos = s.find('#', pos)
  349. if quote_pos < 0:
  350. without_comment = s if hash_pos < 0 else s[:hash_pos]
  351. return without_comment.strip()
  352. elif 0 <= hash_pos < quote_pos:
  353. return s[:hash_pos].strip()
  354. else:
  355. closing_quote_pos = s.find('"', quote_pos + 1)
  356. if closing_quote_pos < 0:
  357. raise ValueError(
  358. f"Missing closing quote in: {s!r}. If you need a double-"
  359. 'quote inside a string, use escaping: e.g. "the \" char"')
  360. pos = closing_quote_pos + 1 # behind closing quote
  361. def is_writable_file_like(obj):
  362. """Return whether *obj* looks like a file object with a *write* method."""
  363. return callable(getattr(obj, 'write', None))
  364. def file_requires_unicode(x):
  365. """
  366. Return whether the given writable file-like object requires Unicode to be
  367. written to it.
  368. """
  369. try:
  370. x.write(b'')
  371. except TypeError:
  372. return True
  373. else:
  374. return False
  375. def to_filehandle(fname, flag='r', return_opened=False, encoding=None):
  376. """
  377. Convert a path to an open file handle or pass-through a file-like object.
  378. Consider using `open_file_cm` instead, as it allows one to properly close
  379. newly created file objects more easily.
  380. Parameters
  381. ----------
  382. fname : str or path-like or file-like
  383. If `str` or `os.PathLike`, the file is opened using the flags specified
  384. by *flag* and *encoding*. If a file-like object, it is passed through.
  385. flag : str, default: 'r'
  386. Passed as the *mode* argument to `open` when *fname* is `str` or
  387. `os.PathLike`; ignored if *fname* is file-like.
  388. return_opened : bool, default: False
  389. If True, return both the file object and a boolean indicating whether
  390. this was a new file (that the caller needs to close). If False, return
  391. only the new file.
  392. encoding : str or None, default: None
  393. Passed as the *mode* argument to `open` when *fname* is `str` or
  394. `os.PathLike`; ignored if *fname* is file-like.
  395. Returns
  396. -------
  397. fh : file-like
  398. opened : bool
  399. *opened* is only returned if *return_opened* is True.
  400. """
  401. if isinstance(fname, os.PathLike):
  402. fname = os.fspath(fname)
  403. if isinstance(fname, str):
  404. if fname.endswith('.gz'):
  405. fh = gzip.open(fname, flag)
  406. elif fname.endswith('.bz2'):
  407. # python may not be compiled with bz2 support,
  408. # bury import until we need it
  409. import bz2
  410. fh = bz2.BZ2File(fname, flag)
  411. else:
  412. fh = open(fname, flag, encoding=encoding)
  413. opened = True
  414. elif hasattr(fname, 'seek'):
  415. fh = fname
  416. opened = False
  417. else:
  418. raise ValueError('fname must be a PathLike or file handle')
  419. if return_opened:
  420. return fh, opened
  421. return fh
  422. def open_file_cm(path_or_file, mode="r", encoding=None):
  423. r"""Pass through file objects and context-manage path-likes."""
  424. fh, opened = to_filehandle(path_or_file, mode, True, encoding)
  425. return fh if opened else contextlib.nullcontext(fh)
  426. def is_scalar_or_string(val):
  427. """Return whether the given object is a scalar or string like."""
  428. return isinstance(val, str) or not np.iterable(val)
  429. @_api.delete_parameter(
  430. "3.8", "np_load", alternative="open(get_sample_data(..., asfileobj=False))")
  431. def get_sample_data(fname, asfileobj=True, *, np_load=True):
  432. """
  433. Return a sample data file. *fname* is a path relative to the
  434. :file:`mpl-data/sample_data` directory. If *asfileobj* is `True`
  435. return a file object, otherwise just a file path.
  436. Sample data files are stored in the 'mpl-data/sample_data' directory within
  437. the Matplotlib package.
  438. If the filename ends in .gz, the file is implicitly ungzipped. If the
  439. filename ends with .npy or .npz, and *asfileobj* is `True`, the file is
  440. loaded with `numpy.load`.
  441. """
  442. path = _get_data_path('sample_data', fname)
  443. if asfileobj:
  444. suffix = path.suffix.lower()
  445. if suffix == '.gz':
  446. return gzip.open(path)
  447. elif suffix in ['.npy', '.npz']:
  448. if np_load:
  449. return np.load(path)
  450. else:
  451. return path.open('rb')
  452. elif suffix in ['.csv', '.xrc', '.txt']:
  453. return path.open('r')
  454. else:
  455. return path.open('rb')
  456. else:
  457. return str(path)
  458. def _get_data_path(*args):
  459. """
  460. Return the `pathlib.Path` to a resource file provided by Matplotlib.
  461. ``*args`` specify a path relative to the base data path.
  462. """
  463. return Path(matplotlib.get_data_path(), *args)
  464. def flatten(seq, scalarp=is_scalar_or_string):
  465. """
  466. Return a generator of flattened nested containers.
  467. For example:
  468. >>> from matplotlib.cbook import flatten
  469. >>> l = (('John', ['Hunter']), (1, 23), [[([42, (5, 23)], )]])
  470. >>> print(list(flatten(l)))
  471. ['John', 'Hunter', 1, 23, 42, 5, 23]
  472. By: Composite of Holger Krekel and Luther Blissett
  473. From: https://code.activestate.com/recipes/121294/
  474. and Recipe 1.12 in cookbook
  475. """
  476. for item in seq:
  477. if scalarp(item) or item is None:
  478. yield item
  479. else:
  480. yield from flatten(item, scalarp)
  481. @_api.deprecated("3.8")
  482. class Stack:
  483. """
  484. Stack of elements with a movable cursor.
  485. Mimics home/back/forward in a web browser.
  486. """
  487. def __init__(self, default=None):
  488. self.clear()
  489. self._default = default
  490. def __call__(self):
  491. """Return the current element, or None."""
  492. if not self._elements:
  493. return self._default
  494. else:
  495. return self._elements[self._pos]
  496. def __len__(self):
  497. return len(self._elements)
  498. def __getitem__(self, ind):
  499. return self._elements[ind]
  500. def forward(self):
  501. """Move the position forward and return the current element."""
  502. self._pos = min(self._pos + 1, len(self._elements) - 1)
  503. return self()
  504. def back(self):
  505. """Move the position back and return the current element."""
  506. if self._pos > 0:
  507. self._pos -= 1
  508. return self()
  509. def push(self, o):
  510. """
  511. Push *o* to the stack at current position. Discard all later elements.
  512. *o* is returned.
  513. """
  514. self._elements = self._elements[:self._pos + 1] + [o]
  515. self._pos = len(self._elements) - 1
  516. return self()
  517. def home(self):
  518. """
  519. Push the first element onto the top of the stack.
  520. The first element is returned.
  521. """
  522. if not self._elements:
  523. return
  524. self.push(self._elements[0])
  525. return self()
  526. def empty(self):
  527. """Return whether the stack is empty."""
  528. return len(self._elements) == 0
  529. def clear(self):
  530. """Empty the stack."""
  531. self._pos = -1
  532. self._elements = []
  533. def bubble(self, o):
  534. """
  535. Raise all references of *o* to the top of the stack, and return it.
  536. Raises
  537. ------
  538. ValueError
  539. If *o* is not in the stack.
  540. """
  541. if o not in self._elements:
  542. raise ValueError('Given element not contained in the stack')
  543. old_elements = self._elements.copy()
  544. self.clear()
  545. top_elements = []
  546. for elem in old_elements:
  547. if elem == o:
  548. top_elements.append(elem)
  549. else:
  550. self.push(elem)
  551. for _ in top_elements:
  552. self.push(o)
  553. return o
  554. def remove(self, o):
  555. """
  556. Remove *o* from the stack.
  557. Raises
  558. ------
  559. ValueError
  560. If *o* is not in the stack.
  561. """
  562. if o not in self._elements:
  563. raise ValueError('Given element not contained in the stack')
  564. old_elements = self._elements.copy()
  565. self.clear()
  566. for elem in old_elements:
  567. if elem != o:
  568. self.push(elem)
  569. class _Stack:
  570. """
  571. Stack of elements with a movable cursor.
  572. Mimics home/back/forward in a web browser.
  573. """
  574. def __init__(self):
  575. self._pos = -1
  576. self._elements = []
  577. def clear(self):
  578. """Empty the stack."""
  579. self._pos = -1
  580. self._elements = []
  581. def __call__(self):
  582. """Return the current element, or None."""
  583. return self._elements[self._pos] if self._elements else None
  584. def __len__(self):
  585. return len(self._elements)
  586. def __getitem__(self, ind):
  587. return self._elements[ind]
  588. def forward(self):
  589. """Move the position forward and return the current element."""
  590. self._pos = min(self._pos + 1, len(self._elements) - 1)
  591. return self()
  592. def back(self):
  593. """Move the position back and return the current element."""
  594. self._pos = max(self._pos - 1, 0)
  595. return self()
  596. def push(self, o):
  597. """
  598. Push *o* to the stack after the current position, and return *o*.
  599. Discard all later elements.
  600. """
  601. self._elements[self._pos + 1:] = [o]
  602. self._pos = len(self._elements) - 1
  603. return o
  604. def home(self):
  605. """
  606. Push the first element onto the top of the stack.
  607. The first element is returned.
  608. """
  609. return self.push(self._elements[0]) if self._elements else None
  610. def safe_masked_invalid(x, copy=False):
  611. x = np.array(x, subok=True, copy=copy)
  612. if not x.dtype.isnative:
  613. # If we have already made a copy, do the byteswap in place, else make a
  614. # copy with the byte order swapped.
  615. # Swap to native order.
  616. x = x.byteswap(inplace=copy).view(x.dtype.newbyteorder('N'))
  617. try:
  618. xm = np.ma.masked_where(~(np.isfinite(x)), x, copy=False)
  619. except TypeError:
  620. return x
  621. return xm
  622. def print_cycles(objects, outstream=sys.stdout, show_progress=False):
  623. """
  624. Print loops of cyclic references in the given *objects*.
  625. It is often useful to pass in ``gc.garbage`` to find the cycles that are
  626. preventing some objects from being garbage collected.
  627. Parameters
  628. ----------
  629. objects
  630. A list of objects to find cycles in.
  631. outstream
  632. The stream for output.
  633. show_progress : bool
  634. If True, print the number of objects reached as they are found.
  635. """
  636. import gc
  637. def print_path(path):
  638. for i, step in enumerate(path):
  639. # next "wraps around"
  640. next = path[(i + 1) % len(path)]
  641. outstream.write(" %s -- " % type(step))
  642. if isinstance(step, dict):
  643. for key, val in step.items():
  644. if val is next:
  645. outstream.write(f"[{key!r}]")
  646. break
  647. if key is next:
  648. outstream.write(f"[key] = {val!r}")
  649. break
  650. elif isinstance(step, list):
  651. outstream.write("[%d]" % step.index(next))
  652. elif isinstance(step, tuple):
  653. outstream.write("( tuple )")
  654. else:
  655. outstream.write(repr(step))
  656. outstream.write(" ->\n")
  657. outstream.write("\n")
  658. def recurse(obj, start, all, current_path):
  659. if show_progress:
  660. outstream.write("%d\r" % len(all))
  661. all[id(obj)] = None
  662. referents = gc.get_referents(obj)
  663. for referent in referents:
  664. # If we've found our way back to the start, this is
  665. # a cycle, so print it out
  666. if referent is start:
  667. print_path(current_path)
  668. # Don't go back through the original list of objects, or
  669. # through temporary references to the object, since those
  670. # are just an artifact of the cycle detector itself.
  671. elif referent is objects or isinstance(referent, types.FrameType):
  672. continue
  673. # We haven't seen this object before, so recurse
  674. elif id(referent) not in all:
  675. recurse(referent, start, all, current_path + [obj])
  676. for obj in objects:
  677. outstream.write(f"Examining: {obj!r}\n")
  678. recurse(obj, obj, {}, [])
  679. class Grouper:
  680. """
  681. A disjoint-set data structure.
  682. Objects can be joined using :meth:`join`, tested for connectedness
  683. using :meth:`joined`, and all disjoint sets can be retrieved by
  684. using the object as an iterator.
  685. The objects being joined must be hashable and weak-referenceable.
  686. Examples
  687. --------
  688. >>> from matplotlib.cbook import Grouper
  689. >>> class Foo:
  690. ... def __init__(self, s):
  691. ... self.s = s
  692. ... def __repr__(self):
  693. ... return self.s
  694. ...
  695. >>> a, b, c, d, e, f = [Foo(x) for x in 'abcdef']
  696. >>> grp = Grouper()
  697. >>> grp.join(a, b)
  698. >>> grp.join(b, c)
  699. >>> grp.join(d, e)
  700. >>> list(grp)
  701. [[a, b, c], [d, e]]
  702. >>> grp.joined(a, b)
  703. True
  704. >>> grp.joined(a, c)
  705. True
  706. >>> grp.joined(a, d)
  707. False
  708. """
  709. def __init__(self, init=()):
  710. self._mapping = weakref.WeakKeyDictionary(
  711. {x: weakref.WeakSet([x]) for x in init})
  712. def __getstate__(self):
  713. return {
  714. **vars(self),
  715. # Convert weak refs to strong ones.
  716. "_mapping": {k: set(v) for k, v in self._mapping.items()},
  717. }
  718. def __setstate__(self, state):
  719. vars(self).update(state)
  720. # Convert strong refs to weak ones.
  721. self._mapping = weakref.WeakKeyDictionary(
  722. {k: weakref.WeakSet(v) for k, v in self._mapping.items()})
  723. def __contains__(self, item):
  724. return item in self._mapping
  725. @_api.deprecated("3.8", alternative="none, you no longer need to clean a Grouper")
  726. def clean(self):
  727. """Clean dead weak references from the dictionary."""
  728. def join(self, a, *args):
  729. """
  730. Join given arguments into the same set. Accepts one or more arguments.
  731. """
  732. mapping = self._mapping
  733. set_a = mapping.setdefault(a, weakref.WeakSet([a]))
  734. for arg in args:
  735. set_b = mapping.get(arg, weakref.WeakSet([arg]))
  736. if set_b is not set_a:
  737. if len(set_b) > len(set_a):
  738. set_a, set_b = set_b, set_a
  739. set_a.update(set_b)
  740. for elem in set_b:
  741. mapping[elem] = set_a
  742. def joined(self, a, b):
  743. """Return whether *a* and *b* are members of the same set."""
  744. return (self._mapping.get(a, object()) is self._mapping.get(b))
  745. def remove(self, a):
  746. """Remove *a* from the grouper, doing nothing if it is not there."""
  747. set_a = self._mapping.pop(a, None)
  748. if set_a:
  749. set_a.remove(a)
  750. def __iter__(self):
  751. """
  752. Iterate over each of the disjoint sets as a list.
  753. The iterator is invalid if interleaved with calls to join().
  754. """
  755. unique_groups = {id(group): group for group in self._mapping.values()}
  756. for group in unique_groups.values():
  757. yield [x for x in group]
  758. def get_siblings(self, a):
  759. """Return all of the items joined with *a*, including itself."""
  760. siblings = self._mapping.get(a, [a])
  761. return [x for x in siblings]
  762. class GrouperView:
  763. """Immutable view over a `.Grouper`."""
  764. def __init__(self, grouper): self._grouper = grouper
  765. def __contains__(self, item): return item in self._grouper
  766. def __iter__(self): return iter(self._grouper)
  767. def joined(self, a, b): return self._grouper.joined(a, b)
  768. def get_siblings(self, a): return self._grouper.get_siblings(a)
  769. def simple_linear_interpolation(a, steps):
  770. """
  771. Resample an array with ``steps - 1`` points between original point pairs.
  772. Along each column of *a*, ``(steps - 1)`` points are introduced between
  773. each original values; the values are linearly interpolated.
  774. Parameters
  775. ----------
  776. a : array, shape (n, ...)
  777. steps : int
  778. Returns
  779. -------
  780. array
  781. shape ``((n - 1) * steps + 1, ...)``
  782. """
  783. fps = a.reshape((len(a), -1))
  784. xp = np.arange(len(a)) * steps
  785. x = np.arange((len(a) - 1) * steps + 1)
  786. return (np.column_stack([np.interp(x, xp, fp) for fp in fps.T])
  787. .reshape((len(x),) + a.shape[1:]))
  788. def delete_masked_points(*args):
  789. """
  790. Find all masked and/or non-finite points in a set of arguments,
  791. and return the arguments with only the unmasked points remaining.
  792. Arguments can be in any of 5 categories:
  793. 1) 1-D masked arrays
  794. 2) 1-D ndarrays
  795. 3) ndarrays with more than one dimension
  796. 4) other non-string iterables
  797. 5) anything else
  798. The first argument must be in one of the first four categories;
  799. any argument with a length differing from that of the first
  800. argument (and hence anything in category 5) then will be
  801. passed through unchanged.
  802. Masks are obtained from all arguments of the correct length
  803. in categories 1, 2, and 4; a point is bad if masked in a masked
  804. array or if it is a nan or inf. No attempt is made to
  805. extract a mask from categories 2, 3, and 4 if `numpy.isfinite`
  806. does not yield a Boolean array.
  807. All input arguments that are not passed unchanged are returned
  808. as ndarrays after removing the points or rows corresponding to
  809. masks in any of the arguments.
  810. A vastly simpler version of this function was originally
  811. written as a helper for Axes.scatter().
  812. """
  813. if not len(args):
  814. return ()
  815. if is_scalar_or_string(args[0]):
  816. raise ValueError("First argument must be a sequence")
  817. nrecs = len(args[0])
  818. margs = []
  819. seqlist = [False] * len(args)
  820. for i, x in enumerate(args):
  821. if not isinstance(x, str) and np.iterable(x) and len(x) == nrecs:
  822. seqlist[i] = True
  823. if isinstance(x, np.ma.MaskedArray):
  824. if x.ndim > 1:
  825. raise ValueError("Masked arrays must be 1-D")
  826. else:
  827. x = np.asarray(x)
  828. margs.append(x)
  829. masks = [] # List of masks that are True where good.
  830. for i, x in enumerate(margs):
  831. if seqlist[i]:
  832. if x.ndim > 1:
  833. continue # Don't try to get nan locations unless 1-D.
  834. if isinstance(x, np.ma.MaskedArray):
  835. masks.append(~np.ma.getmaskarray(x)) # invert the mask
  836. xd = x.data
  837. else:
  838. xd = x
  839. try:
  840. mask = np.isfinite(xd)
  841. if isinstance(mask, np.ndarray):
  842. masks.append(mask)
  843. except Exception: # Fixme: put in tuple of possible exceptions?
  844. pass
  845. if len(masks):
  846. mask = np.logical_and.reduce(masks)
  847. igood = mask.nonzero()[0]
  848. if len(igood) < nrecs:
  849. for i, x in enumerate(margs):
  850. if seqlist[i]:
  851. margs[i] = x[igood]
  852. for i, x in enumerate(margs):
  853. if seqlist[i] and isinstance(x, np.ma.MaskedArray):
  854. margs[i] = x.filled()
  855. return margs
  856. def _combine_masks(*args):
  857. """
  858. Find all masked and/or non-finite points in a set of arguments,
  859. and return the arguments as masked arrays with a common mask.
  860. Arguments can be in any of 5 categories:
  861. 1) 1-D masked arrays
  862. 2) 1-D ndarrays
  863. 3) ndarrays with more than one dimension
  864. 4) other non-string iterables
  865. 5) anything else
  866. The first argument must be in one of the first four categories;
  867. any argument with a length differing from that of the first
  868. argument (and hence anything in category 5) then will be
  869. passed through unchanged.
  870. Masks are obtained from all arguments of the correct length
  871. in categories 1, 2, and 4; a point is bad if masked in a masked
  872. array or if it is a nan or inf. No attempt is made to
  873. extract a mask from categories 2 and 4 if `numpy.isfinite`
  874. does not yield a Boolean array. Category 3 is included to
  875. support RGB or RGBA ndarrays, which are assumed to have only
  876. valid values and which are passed through unchanged.
  877. All input arguments that are not passed unchanged are returned
  878. as masked arrays if any masked points are found, otherwise as
  879. ndarrays.
  880. """
  881. if not len(args):
  882. return ()
  883. if is_scalar_or_string(args[0]):
  884. raise ValueError("First argument must be a sequence")
  885. nrecs = len(args[0])
  886. margs = [] # Output args; some may be modified.
  887. seqlist = [False] * len(args) # Flags: True if output will be masked.
  888. masks = [] # List of masks.
  889. for i, x in enumerate(args):
  890. if is_scalar_or_string(x) or len(x) != nrecs:
  891. margs.append(x) # Leave it unmodified.
  892. else:
  893. if isinstance(x, np.ma.MaskedArray) and x.ndim > 1:
  894. raise ValueError("Masked arrays must be 1-D")
  895. try:
  896. x = np.asanyarray(x)
  897. except (VisibleDeprecationWarning, ValueError):
  898. # NumPy 1.19 raises a warning about ragged arrays, but we want
  899. # to accept basically anything here.
  900. x = np.asanyarray(x, dtype=object)
  901. if x.ndim == 1:
  902. x = safe_masked_invalid(x)
  903. seqlist[i] = True
  904. if np.ma.is_masked(x):
  905. masks.append(np.ma.getmaskarray(x))
  906. margs.append(x) # Possibly modified.
  907. if len(masks):
  908. mask = np.logical_or.reduce(masks)
  909. for i, x in enumerate(margs):
  910. if seqlist[i]:
  911. margs[i] = np.ma.array(x, mask=mask)
  912. return margs
  913. def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None,
  914. autorange=False):
  915. r"""
  916. Return a list of dictionaries of statistics used to draw a series of box
  917. and whisker plots using `~.Axes.bxp`.
  918. Parameters
  919. ----------
  920. X : array-like
  921. Data that will be represented in the boxplots. Should have 2 or
  922. fewer dimensions.
  923. whis : float or (float, float), default: 1.5
  924. The position of the whiskers.
  925. If a float, the lower whisker is at the lowest datum above
  926. ``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum below
  927. ``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and third
  928. quartiles. The default value of ``whis = 1.5`` corresponds to Tukey's
  929. original definition of boxplots.
  930. If a pair of floats, they indicate the percentiles at which to draw the
  931. whiskers (e.g., (5, 95)). In particular, setting this to (0, 100)
  932. results in whiskers covering the whole range of the data.
  933. In the edge case where ``Q1 == Q3``, *whis* is automatically set to
  934. (0, 100) (cover the whole range of the data) if *autorange* is True.
  935. Beyond the whiskers, data are considered outliers and are plotted as
  936. individual points.
  937. bootstrap : int, optional
  938. Number of times the confidence intervals around the median
  939. should be bootstrapped (percentile method).
  940. labels : array-like, optional
  941. Labels for each dataset. Length must be compatible with
  942. dimensions of *X*.
  943. autorange : bool, optional (False)
  944. When `True` and the data are distributed such that the 25th and 75th
  945. percentiles are equal, ``whis`` is set to (0, 100) such that the
  946. whisker ends are at the minimum and maximum of the data.
  947. Returns
  948. -------
  949. list of dict
  950. A list of dictionaries containing the results for each column
  951. of data. Keys of each dictionary are the following:
  952. ======== ===================================
  953. Key Value Description
  954. ======== ===================================
  955. label tick label for the boxplot
  956. mean arithmetic mean value
  957. med 50th percentile
  958. q1 first quartile (25th percentile)
  959. q3 third quartile (75th percentile)
  960. iqr interquartile range
  961. cilo lower notch around the median
  962. cihi upper notch around the median
  963. whislo end of the lower whisker
  964. whishi end of the upper whisker
  965. fliers outliers
  966. ======== ===================================
  967. Notes
  968. -----
  969. Non-bootstrapping approach to confidence interval uses Gaussian-based
  970. asymptotic approximation:
  971. .. math::
  972. \mathrm{med} \pm 1.57 \times \frac{\mathrm{iqr}}{\sqrt{N}}
  973. General approach from:
  974. McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of
  975. Boxplots", The American Statistician, 32:12-16.
  976. """
  977. def _bootstrap_median(data, N=5000):
  978. # determine 95% confidence intervals of the median
  979. M = len(data)
  980. percentiles = [2.5, 97.5]
  981. bs_index = np.random.randint(M, size=(N, M))
  982. bsData = data[bs_index]
  983. estimate = np.median(bsData, axis=1, overwrite_input=True)
  984. CI = np.percentile(estimate, percentiles)
  985. return CI
  986. def _compute_conf_interval(data, med, iqr, bootstrap):
  987. if bootstrap is not None:
  988. # Do a bootstrap estimate of notch locations.
  989. # get conf. intervals around median
  990. CI = _bootstrap_median(data, N=bootstrap)
  991. notch_min = CI[0]
  992. notch_max = CI[1]
  993. else:
  994. N = len(data)
  995. notch_min = med - 1.57 * iqr / np.sqrt(N)
  996. notch_max = med + 1.57 * iqr / np.sqrt(N)
  997. return notch_min, notch_max
  998. # output is a list of dicts
  999. bxpstats = []
  1000. # convert X to a list of lists
  1001. X = _reshape_2D(X, "X")
  1002. ncols = len(X)
  1003. if labels is None:
  1004. labels = itertools.repeat(None)
  1005. elif len(labels) != ncols:
  1006. raise ValueError("Dimensions of labels and X must be compatible")
  1007. input_whis = whis
  1008. for ii, (x, label) in enumerate(zip(X, labels)):
  1009. # empty dict
  1010. stats = {}
  1011. if label is not None:
  1012. stats['label'] = label
  1013. # restore whis to the input values in case it got changed in the loop
  1014. whis = input_whis
  1015. # note tricksiness, append up here and then mutate below
  1016. bxpstats.append(stats)
  1017. # if empty, bail
  1018. if len(x) == 0:
  1019. stats['fliers'] = np.array([])
  1020. stats['mean'] = np.nan
  1021. stats['med'] = np.nan
  1022. stats['q1'] = np.nan
  1023. stats['q3'] = np.nan
  1024. stats['iqr'] = np.nan
  1025. stats['cilo'] = np.nan
  1026. stats['cihi'] = np.nan
  1027. stats['whislo'] = np.nan
  1028. stats['whishi'] = np.nan
  1029. continue
  1030. # up-convert to an array, just to be safe
  1031. x = np.asarray(x)
  1032. # arithmetic mean
  1033. stats['mean'] = np.mean(x)
  1034. # medians and quartiles
  1035. q1, med, q3 = np.percentile(x, [25, 50, 75])
  1036. # interquartile range
  1037. stats['iqr'] = q3 - q1
  1038. if stats['iqr'] == 0 and autorange:
  1039. whis = (0, 100)
  1040. # conf. interval around median
  1041. stats['cilo'], stats['cihi'] = _compute_conf_interval(
  1042. x, med, stats['iqr'], bootstrap
  1043. )
  1044. # lowest/highest non-outliers
  1045. if np.iterable(whis) and not isinstance(whis, str):
  1046. loval, hival = np.percentile(x, whis)
  1047. elif np.isreal(whis):
  1048. loval = q1 - whis * stats['iqr']
  1049. hival = q3 + whis * stats['iqr']
  1050. else:
  1051. raise ValueError('whis must be a float or list of percentiles')
  1052. # get high extreme
  1053. wiskhi = x[x <= hival]
  1054. if len(wiskhi) == 0 or np.max(wiskhi) < q3:
  1055. stats['whishi'] = q3
  1056. else:
  1057. stats['whishi'] = np.max(wiskhi)
  1058. # get low extreme
  1059. wisklo = x[x >= loval]
  1060. if len(wisklo) == 0 or np.min(wisklo) > q1:
  1061. stats['whislo'] = q1
  1062. else:
  1063. stats['whislo'] = np.min(wisklo)
  1064. # compute a single array of outliers
  1065. stats['fliers'] = np.concatenate([
  1066. x[x < stats['whislo']],
  1067. x[x > stats['whishi']],
  1068. ])
  1069. # add in the remaining stats
  1070. stats['q1'], stats['med'], stats['q3'] = q1, med, q3
  1071. return bxpstats
  1072. #: Maps short codes for line style to their full name used by backends.
  1073. ls_mapper = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'}
  1074. #: Maps full names for line styles used by backends to their short codes.
  1075. ls_mapper_r = {v: k for k, v in ls_mapper.items()}
  1076. def contiguous_regions(mask):
  1077. """
  1078. Return a list of (ind0, ind1) such that ``mask[ind0:ind1].all()`` is
  1079. True and we cover all such regions.
  1080. """
  1081. mask = np.asarray(mask, dtype=bool)
  1082. if not mask.size:
  1083. return []
  1084. # Find the indices of region changes, and correct offset
  1085. idx, = np.nonzero(mask[:-1] != mask[1:])
  1086. idx += 1
  1087. # List operations are faster for moderately sized arrays
  1088. idx = idx.tolist()
  1089. # Add first and/or last index if needed
  1090. if mask[0]:
  1091. idx = [0] + idx
  1092. if mask[-1]:
  1093. idx.append(len(mask))
  1094. return list(zip(idx[::2], idx[1::2]))
  1095. def is_math_text(s):
  1096. """
  1097. Return whether the string *s* contains math expressions.
  1098. This is done by checking whether *s* contains an even number of
  1099. non-escaped dollar signs.
  1100. """
  1101. s = str(s)
  1102. dollar_count = s.count(r'$') - s.count(r'\$')
  1103. even_dollars = (dollar_count > 0 and dollar_count % 2 == 0)
  1104. return even_dollars
  1105. def _to_unmasked_float_array(x):
  1106. """
  1107. Convert a sequence to a float array; if input was a masked array, masked
  1108. values are converted to nans.
  1109. """
  1110. if hasattr(x, 'mask'):
  1111. return np.ma.asarray(x, float).filled(np.nan)
  1112. else:
  1113. return np.asarray(x, float)
  1114. def _check_1d(x):
  1115. """Convert scalars to 1D arrays; pass-through arrays as is."""
  1116. # Unpack in case of e.g. Pandas or xarray object
  1117. x = _unpack_to_numpy(x)
  1118. # plot requires `shape` and `ndim`. If passed an
  1119. # object that doesn't provide them, then force to numpy array.
  1120. # Note this will strip unit information.
  1121. if (not hasattr(x, 'shape') or
  1122. not hasattr(x, 'ndim') or
  1123. len(x.shape) < 1):
  1124. return np.atleast_1d(x)
  1125. else:
  1126. return x
  1127. def _reshape_2D(X, name):
  1128. """
  1129. Use Fortran ordering to convert ndarrays and lists of iterables to lists of
  1130. 1D arrays.
  1131. Lists of iterables are converted by applying `numpy.asanyarray` to each of
  1132. their elements. 1D ndarrays are returned in a singleton list containing
  1133. them. 2D ndarrays are converted to the list of their *columns*.
  1134. *name* is used to generate the error message for invalid inputs.
  1135. """
  1136. # Unpack in case of e.g. Pandas or xarray object
  1137. X = _unpack_to_numpy(X)
  1138. # Iterate over columns for ndarrays.
  1139. if isinstance(X, np.ndarray):
  1140. X = X.T
  1141. if len(X) == 0:
  1142. return [[]]
  1143. elif X.ndim == 1 and np.ndim(X[0]) == 0:
  1144. # 1D array of scalars: directly return it.
  1145. return [X]
  1146. elif X.ndim in [1, 2]:
  1147. # 2D array, or 1D array of iterables: flatten them first.
  1148. return [np.reshape(x, -1) for x in X]
  1149. else:
  1150. raise ValueError(f'{name} must have 2 or fewer dimensions')
  1151. # Iterate over list of iterables.
  1152. if len(X) == 0:
  1153. return [[]]
  1154. result = []
  1155. is_1d = True
  1156. for xi in X:
  1157. # check if this is iterable, except for strings which we
  1158. # treat as singletons.
  1159. if not isinstance(xi, str):
  1160. try:
  1161. iter(xi)
  1162. except TypeError:
  1163. pass
  1164. else:
  1165. is_1d = False
  1166. xi = np.asanyarray(xi)
  1167. nd = np.ndim(xi)
  1168. if nd > 1:
  1169. raise ValueError(f'{name} must have 2 or fewer dimensions')
  1170. result.append(xi.reshape(-1))
  1171. if is_1d:
  1172. # 1D array of scalars: directly return it.
  1173. return [np.reshape(result, -1)]
  1174. else:
  1175. # 2D array, or 1D array of iterables: use flattened version.
  1176. return result
  1177. def violin_stats(X, method, points=100, quantiles=None):
  1178. """
  1179. Return a list of dictionaries of data which can be used to draw a series
  1180. of violin plots.
  1181. See the ``Returns`` section below to view the required keys of the
  1182. dictionary.
  1183. Users can skip this function and pass a user-defined set of dictionaries
  1184. with the same keys to `~.axes.Axes.violinplot` instead of using Matplotlib
  1185. to do the calculations. See the *Returns* section below for the keys
  1186. that must be present in the dictionaries.
  1187. Parameters
  1188. ----------
  1189. X : array-like
  1190. Sample data that will be used to produce the gaussian kernel density
  1191. estimates. Must have 2 or fewer dimensions.
  1192. method : callable
  1193. The method used to calculate the kernel density estimate for each
  1194. column of data. When called via ``method(v, coords)``, it should
  1195. return a vector of the values of the KDE evaluated at the values
  1196. specified in coords.
  1197. points : int, default: 100
  1198. Defines the number of points to evaluate each of the gaussian kernel
  1199. density estimates at.
  1200. quantiles : array-like, default: None
  1201. Defines (if not None) a list of floats in interval [0, 1] for each
  1202. column of data, which represents the quantiles that will be rendered
  1203. for that column of data. Must have 2 or fewer dimensions. 1D array will
  1204. be treated as a singleton list containing them.
  1205. Returns
  1206. -------
  1207. list of dict
  1208. A list of dictionaries containing the results for each column of data.
  1209. The dictionaries contain at least the following:
  1210. - coords: A list of scalars containing the coordinates this particular
  1211. kernel density estimate was evaluated at.
  1212. - vals: A list of scalars containing the values of the kernel density
  1213. estimate at each of the coordinates given in *coords*.
  1214. - mean: The mean value for this column of data.
  1215. - median: The median value for this column of data.
  1216. - min: The minimum value for this column of data.
  1217. - max: The maximum value for this column of data.
  1218. - quantiles: The quantile values for this column of data.
  1219. """
  1220. # List of dictionaries describing each of the violins.
  1221. vpstats = []
  1222. # Want X to be a list of data sequences
  1223. X = _reshape_2D(X, "X")
  1224. # Want quantiles to be as the same shape as data sequences
  1225. if quantiles is not None and len(quantiles) != 0:
  1226. quantiles = _reshape_2D(quantiles, "quantiles")
  1227. # Else, mock quantiles if it's none or empty
  1228. else:
  1229. quantiles = [[]] * len(X)
  1230. # quantiles should have the same size as dataset
  1231. if len(X) != len(quantiles):
  1232. raise ValueError("List of violinplot statistics and quantiles values"
  1233. " must have the same length")
  1234. # Zip x and quantiles
  1235. for (x, q) in zip(X, quantiles):
  1236. # Dictionary of results for this distribution
  1237. stats = {}
  1238. # Calculate basic stats for the distribution
  1239. min_val = np.min(x)
  1240. max_val = np.max(x)
  1241. quantile_val = np.percentile(x, 100 * q)
  1242. # Evaluate the kernel density estimate
  1243. coords = np.linspace(min_val, max_val, points)
  1244. stats['vals'] = method(x, coords)
  1245. stats['coords'] = coords
  1246. # Store additional statistics for this distribution
  1247. stats['mean'] = np.mean(x)
  1248. stats['median'] = np.median(x)
  1249. stats['min'] = min_val
  1250. stats['max'] = max_val
  1251. stats['quantiles'] = np.atleast_1d(quantile_val)
  1252. # Append to output
  1253. vpstats.append(stats)
  1254. return vpstats
  1255. def pts_to_prestep(x, *args):
  1256. """
  1257. Convert continuous line to pre-steps.
  1258. Given a set of ``N`` points, convert to ``2N - 1`` points, which when
  1259. connected linearly give a step function which changes values at the
  1260. beginning of the intervals.
  1261. Parameters
  1262. ----------
  1263. x : array
  1264. The x location of the steps. May be empty.
  1265. y1, ..., yp : array
  1266. y arrays to be turned into steps; all must be the same length as ``x``.
  1267. Returns
  1268. -------
  1269. array
  1270. The x and y values converted to steps in the same order as the input;
  1271. can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
  1272. length ``N``, each of these arrays will be length ``2N + 1``. For
  1273. ``N=0``, the length will be 0.
  1274. Examples
  1275. --------
  1276. >>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)
  1277. """
  1278. steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
  1279. # In all `pts_to_*step` functions, only assign once using *x* and *args*,
  1280. # as converting to an array may be expensive.
  1281. steps[0, 0::2] = x
  1282. steps[0, 1::2] = steps[0, 0:-2:2]
  1283. steps[1:, 0::2] = args
  1284. steps[1:, 1::2] = steps[1:, 2::2]
  1285. return steps
  1286. def pts_to_poststep(x, *args):
  1287. """
  1288. Convert continuous line to post-steps.
  1289. Given a set of ``N`` points convert to ``2N + 1`` points, which when
  1290. connected linearly give a step function which changes values at the end of
  1291. the intervals.
  1292. Parameters
  1293. ----------
  1294. x : array
  1295. The x location of the steps. May be empty.
  1296. y1, ..., yp : array
  1297. y arrays to be turned into steps; all must be the same length as ``x``.
  1298. Returns
  1299. -------
  1300. array
  1301. The x and y values converted to steps in the same order as the input;
  1302. can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
  1303. length ``N``, each of these arrays will be length ``2N + 1``. For
  1304. ``N=0``, the length will be 0.
  1305. Examples
  1306. --------
  1307. >>> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2)
  1308. """
  1309. steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
  1310. steps[0, 0::2] = x
  1311. steps[0, 1::2] = steps[0, 2::2]
  1312. steps[1:, 0::2] = args
  1313. steps[1:, 1::2] = steps[1:, 0:-2:2]
  1314. return steps
  1315. def pts_to_midstep(x, *args):
  1316. """
  1317. Convert continuous line to mid-steps.
  1318. Given a set of ``N`` points convert to ``2N`` points which when connected
  1319. linearly give a step function which changes values at the middle of the
  1320. intervals.
  1321. Parameters
  1322. ----------
  1323. x : array
  1324. The x location of the steps. May be empty.
  1325. y1, ..., yp : array
  1326. y arrays to be turned into steps; all must be the same length as
  1327. ``x``.
  1328. Returns
  1329. -------
  1330. array
  1331. The x and y values converted to steps in the same order as the input;
  1332. can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
  1333. length ``N``, each of these arrays will be length ``2N``.
  1334. Examples
  1335. --------
  1336. >>> x_s, y1_s, y2_s = pts_to_midstep(x, y1, y2)
  1337. """
  1338. steps = np.zeros((1 + len(args), 2 * len(x)))
  1339. x = np.asanyarray(x)
  1340. steps[0, 1:-1:2] = steps[0, 2::2] = (x[:-1] + x[1:]) / 2
  1341. steps[0, :1] = x[:1] # Also works for zero-sized input.
  1342. steps[0, -1:] = x[-1:]
  1343. steps[1:, 0::2] = args
  1344. steps[1:, 1::2] = steps[1:, 0::2]
  1345. return steps
  1346. STEP_LOOKUP_MAP = {'default': lambda x, y: (x, y),
  1347. 'steps': pts_to_prestep,
  1348. 'steps-pre': pts_to_prestep,
  1349. 'steps-post': pts_to_poststep,
  1350. 'steps-mid': pts_to_midstep}
  1351. def index_of(y):
  1352. """
  1353. A helper function to create reasonable x values for the given *y*.
  1354. This is used for plotting (x, y) if x values are not explicitly given.
  1355. First try ``y.index`` (assuming *y* is a `pandas.Series`), if that
  1356. fails, use ``range(len(y))``.
  1357. This will be extended in the future to deal with more types of
  1358. labeled data.
  1359. Parameters
  1360. ----------
  1361. y : float or array-like
  1362. Returns
  1363. -------
  1364. x, y : ndarray
  1365. The x and y values to plot.
  1366. """
  1367. try:
  1368. return y.index.to_numpy(), y.to_numpy()
  1369. except AttributeError:
  1370. pass
  1371. try:
  1372. y = _check_1d(y)
  1373. except (VisibleDeprecationWarning, ValueError):
  1374. # NumPy 1.19 will warn on ragged input, and we can't actually use it.
  1375. pass
  1376. else:
  1377. return np.arange(y.shape[0], dtype=float), y
  1378. raise ValueError('Input could not be cast to an at-least-1D NumPy array')
  1379. def safe_first_element(obj):
  1380. """
  1381. Return the first element in *obj*.
  1382. This is a type-independent way of obtaining the first element,
  1383. supporting both index access and the iterator protocol.
  1384. """
  1385. return _safe_first_finite(obj, skip_nonfinite=False)
  1386. def _safe_first_finite(obj, *, skip_nonfinite=True):
  1387. """
  1388. Return the first finite element in *obj* if one is available and skip_nonfinite is
  1389. True. Otherwise, return the first element.
  1390. This is a method for internal use.
  1391. This is a type-independent way of obtaining the first finite element, supporting
  1392. both index access and the iterator protocol.
  1393. """
  1394. def safe_isfinite(val):
  1395. if val is None:
  1396. return False
  1397. try:
  1398. return math.isfinite(val)
  1399. except (TypeError, ValueError):
  1400. pass
  1401. try:
  1402. return np.isfinite(val) if np.isscalar(val) else True
  1403. except TypeError:
  1404. # This is something that NumPy cannot make heads or tails of,
  1405. # assume "finite"
  1406. return True
  1407. if skip_nonfinite is False:
  1408. if isinstance(obj, collections.abc.Iterator):
  1409. # needed to accept `array.flat` as input.
  1410. # np.flatiter reports as an instance of collections.Iterator
  1411. # but can still be indexed via [].
  1412. # This has the side effect of re-setting the iterator, but
  1413. # that is acceptable.
  1414. try:
  1415. return obj[0]
  1416. except TypeError:
  1417. pass
  1418. raise RuntimeError("matplotlib does not support generators "
  1419. "as input")
  1420. return next(iter(obj))
  1421. elif isinstance(obj, np.flatiter):
  1422. # TODO do the finite filtering on this
  1423. return obj[0]
  1424. elif isinstance(obj, collections.abc.Iterator):
  1425. raise RuntimeError("matplotlib does not "
  1426. "support generators as input")
  1427. else:
  1428. for val in obj:
  1429. if safe_isfinite(val):
  1430. return val
  1431. return safe_first_element(obj)
  1432. def sanitize_sequence(data):
  1433. """
  1434. Convert dictview objects to list. Other inputs are returned unchanged.
  1435. """
  1436. return (list(data) if isinstance(data, collections.abc.MappingView)
  1437. else data)
  1438. def normalize_kwargs(kw, alias_mapping=None):
  1439. """
  1440. Helper function to normalize kwarg inputs.
  1441. Parameters
  1442. ----------
  1443. kw : dict or None
  1444. A dict of keyword arguments. None is explicitly supported and treated
  1445. as an empty dict, to support functions with an optional parameter of
  1446. the form ``props=None``.
  1447. alias_mapping : dict or Artist subclass or Artist instance, optional
  1448. A mapping between a canonical name to a list of aliases, in order of
  1449. precedence from lowest to highest.
  1450. If the canonical value is not in the list it is assumed to have the
  1451. highest priority.
  1452. If an Artist subclass or instance is passed, use its properties alias
  1453. mapping.
  1454. Raises
  1455. ------
  1456. TypeError
  1457. To match what Python raises if invalid arguments/keyword arguments are
  1458. passed to a callable.
  1459. """
  1460. from matplotlib.artist import Artist
  1461. if kw is None:
  1462. return {}
  1463. # deal with default value of alias_mapping
  1464. if alias_mapping is None:
  1465. alias_mapping = {}
  1466. elif (isinstance(alias_mapping, type) and issubclass(alias_mapping, Artist)
  1467. or isinstance(alias_mapping, Artist)):
  1468. alias_mapping = getattr(alias_mapping, "_alias_map", {})
  1469. to_canonical = {alias: canonical
  1470. for canonical, alias_list in alias_mapping.items()
  1471. for alias in alias_list}
  1472. canonical_to_seen = {}
  1473. ret = {} # output dictionary
  1474. for k, v in kw.items():
  1475. canonical = to_canonical.get(k, k)
  1476. if canonical in canonical_to_seen:
  1477. raise TypeError(f"Got both {canonical_to_seen[canonical]!r} and "
  1478. f"{k!r}, which are aliases of one another")
  1479. canonical_to_seen[canonical] = k
  1480. ret[canonical] = v
  1481. return ret
  1482. @contextlib.contextmanager
  1483. def _lock_path(path):
  1484. """
  1485. Context manager for locking a path.
  1486. Usage::
  1487. with _lock_path(path):
  1488. ...
  1489. Another thread or process that attempts to lock the same path will wait
  1490. until this context manager is exited.
  1491. The lock is implemented by creating a temporary file in the parent
  1492. directory, so that directory must exist and be writable.
  1493. """
  1494. path = Path(path)
  1495. lock_path = path.with_name(path.name + ".matplotlib-lock")
  1496. retries = 50
  1497. sleeptime = 0.1
  1498. for _ in range(retries):
  1499. try:
  1500. with lock_path.open("xb"):
  1501. break
  1502. except FileExistsError:
  1503. time.sleep(sleeptime)
  1504. else:
  1505. raise TimeoutError("""\
  1506. Lock error: Matplotlib failed to acquire the following lock file:
  1507. {}
  1508. This maybe due to another process holding this lock file. If you are sure no
  1509. other Matplotlib process is running, remove this file and try again.""".format(
  1510. lock_path))
  1511. try:
  1512. yield
  1513. finally:
  1514. lock_path.unlink()
  1515. def _topmost_artist(
  1516. artists,
  1517. _cached_max=functools.partial(max, key=operator.attrgetter("zorder"))):
  1518. """
  1519. Get the topmost artist of a list.
  1520. In case of a tie, return the *last* of the tied artists, as it will be
  1521. drawn on top of the others. `max` returns the first maximum in case of
  1522. ties, so we need to iterate over the list in reverse order.
  1523. """
  1524. return _cached_max(reversed(artists))
  1525. def _str_equal(obj, s):
  1526. """
  1527. Return whether *obj* is a string equal to string *s*.
  1528. This helper solely exists to handle the case where *obj* is a numpy array,
  1529. because in such cases, a naive ``obj == s`` would yield an array, which
  1530. cannot be used in a boolean context.
  1531. """
  1532. return isinstance(obj, str) and obj == s
  1533. def _str_lower_equal(obj, s):
  1534. """
  1535. Return whether *obj* is a string equal, when lowercased, to string *s*.
  1536. This helper solely exists to handle the case where *obj* is a numpy array,
  1537. because in such cases, a naive ``obj == s`` would yield an array, which
  1538. cannot be used in a boolean context.
  1539. """
  1540. return isinstance(obj, str) and obj.lower() == s
  1541. def _array_perimeter(arr):
  1542. """
  1543. Get the elements on the perimeter of *arr*.
  1544. Parameters
  1545. ----------
  1546. arr : ndarray, shape (M, N)
  1547. The input array.
  1548. Returns
  1549. -------
  1550. ndarray, shape (2*(M - 1) + 2*(N - 1),)
  1551. The elements on the perimeter of the array::
  1552. [arr[0, 0], ..., arr[0, -1], ..., arr[-1, -1], ..., arr[-1, 0], ...]
  1553. Examples
  1554. --------
  1555. >>> i, j = np.ogrid[:3, :4]
  1556. >>> a = i*10 + j
  1557. >>> a
  1558. array([[ 0, 1, 2, 3],
  1559. [10, 11, 12, 13],
  1560. [20, 21, 22, 23]])
  1561. >>> _array_perimeter(a)
  1562. array([ 0, 1, 2, 3, 13, 23, 22, 21, 20, 10])
  1563. """
  1564. # note we use Python's half-open ranges to avoid repeating
  1565. # the corners
  1566. forward = np.s_[0:-1] # [0 ... -1)
  1567. backward = np.s_[-1:0:-1] # [-1 ... 0)
  1568. return np.concatenate((
  1569. arr[0, forward],
  1570. arr[forward, -1],
  1571. arr[-1, backward],
  1572. arr[backward, 0],
  1573. ))
  1574. def _unfold(arr, axis, size, step):
  1575. """
  1576. Append an extra dimension containing sliding windows along *axis*.
  1577. All windows are of size *size* and begin with every *step* elements.
  1578. Parameters
  1579. ----------
  1580. arr : ndarray, shape (N_1, ..., N_k)
  1581. The input array
  1582. axis : int
  1583. Axis along which the windows are extracted
  1584. size : int
  1585. Size of the windows
  1586. step : int
  1587. Stride between first elements of subsequent windows.
  1588. Returns
  1589. -------
  1590. ndarray, shape (N_1, ..., 1 + (N_axis-size)/step, ..., N_k, size)
  1591. Examples
  1592. --------
  1593. >>> i, j = np.ogrid[:3, :7]
  1594. >>> a = i*10 + j
  1595. >>> a
  1596. array([[ 0, 1, 2, 3, 4, 5, 6],
  1597. [10, 11, 12, 13, 14, 15, 16],
  1598. [20, 21, 22, 23, 24, 25, 26]])
  1599. >>> _unfold(a, axis=1, size=3, step=2)
  1600. array([[[ 0, 1, 2],
  1601. [ 2, 3, 4],
  1602. [ 4, 5, 6]],
  1603. [[10, 11, 12],
  1604. [12, 13, 14],
  1605. [14, 15, 16]],
  1606. [[20, 21, 22],
  1607. [22, 23, 24],
  1608. [24, 25, 26]]])
  1609. """
  1610. new_shape = [*arr.shape, size]
  1611. new_strides = [*arr.strides, arr.strides[axis]]
  1612. new_shape[axis] = (new_shape[axis] - size) // step + 1
  1613. new_strides[axis] = new_strides[axis] * step
  1614. return np.lib.stride_tricks.as_strided(arr,
  1615. shape=new_shape,
  1616. strides=new_strides,
  1617. writeable=False)
  1618. def _array_patch_perimeters(x, rstride, cstride):
  1619. """
  1620. Extract perimeters of patches from *arr*.
  1621. Extracted patches are of size (*rstride* + 1) x (*cstride* + 1) and
  1622. share perimeters with their neighbors. The ordering of the vertices matches
  1623. that returned by ``_array_perimeter``.
  1624. Parameters
  1625. ----------
  1626. x : ndarray, shape (N, M)
  1627. Input array
  1628. rstride : int
  1629. Vertical (row) stride between corresponding elements of each patch
  1630. cstride : int
  1631. Horizontal (column) stride between corresponding elements of each patch
  1632. Returns
  1633. -------
  1634. ndarray, shape (N/rstride * M/cstride, 2 * (rstride + cstride))
  1635. """
  1636. assert rstride > 0 and cstride > 0
  1637. assert (x.shape[0] - 1) % rstride == 0
  1638. assert (x.shape[1] - 1) % cstride == 0
  1639. # We build up each perimeter from four half-open intervals. Here is an
  1640. # illustrated explanation for rstride == cstride == 3
  1641. #
  1642. # T T T R
  1643. # L R
  1644. # L R
  1645. # L B B B
  1646. #
  1647. # where T means that this element will be in the top array, R for right,
  1648. # B for bottom and L for left. Each of the arrays below has a shape of:
  1649. #
  1650. # (number of perimeters that can be extracted vertically,
  1651. # number of perimeters that can be extracted horizontally,
  1652. # cstride for top and bottom and rstride for left and right)
  1653. #
  1654. # Note that _unfold doesn't incur any memory copies, so the only costly
  1655. # operation here is the np.concatenate.
  1656. top = _unfold(x[:-1:rstride, :-1], 1, cstride, cstride)
  1657. bottom = _unfold(x[rstride::rstride, 1:], 1, cstride, cstride)[..., ::-1]
  1658. right = _unfold(x[:-1, cstride::cstride], 0, rstride, rstride)
  1659. left = _unfold(x[1:, :-1:cstride], 0, rstride, rstride)[..., ::-1]
  1660. return (np.concatenate((top, right, bottom, left), axis=2)
  1661. .reshape(-1, 2 * (rstride + cstride)))
  1662. @contextlib.contextmanager
  1663. def _setattr_cm(obj, **kwargs):
  1664. """
  1665. Temporarily set some attributes; restore original state at context exit.
  1666. """
  1667. sentinel = object()
  1668. origs = {}
  1669. for attr in kwargs:
  1670. orig = getattr(obj, attr, sentinel)
  1671. if attr in obj.__dict__ or orig is sentinel:
  1672. # if we are pulling from the instance dict or the object
  1673. # does not have this attribute we can trust the above
  1674. origs[attr] = orig
  1675. else:
  1676. # if the attribute is not in the instance dict it must be
  1677. # from the class level
  1678. cls_orig = getattr(type(obj), attr)
  1679. # if we are dealing with a property (but not a general descriptor)
  1680. # we want to set the original value back.
  1681. if isinstance(cls_orig, property):
  1682. origs[attr] = orig
  1683. # otherwise this is _something_ we are going to shadow at
  1684. # the instance dict level from higher up in the MRO. We
  1685. # are going to assume we can delattr(obj, attr) to clean
  1686. # up after ourselves. It is possible that this code will
  1687. # fail if used with a non-property custom descriptor which
  1688. # implements __set__ (and __delete__ does not act like a
  1689. # stack). However, this is an internal tool and we do not
  1690. # currently have any custom descriptors.
  1691. else:
  1692. origs[attr] = sentinel
  1693. try:
  1694. for attr, val in kwargs.items():
  1695. setattr(obj, attr, val)
  1696. yield
  1697. finally:
  1698. for attr, orig in origs.items():
  1699. if orig is sentinel:
  1700. delattr(obj, attr)
  1701. else:
  1702. setattr(obj, attr, orig)
  1703. class _OrderedSet(collections.abc.MutableSet):
  1704. def __init__(self):
  1705. self._od = collections.OrderedDict()
  1706. def __contains__(self, key):
  1707. return key in self._od
  1708. def __iter__(self):
  1709. return iter(self._od)
  1710. def __len__(self):
  1711. return len(self._od)
  1712. def add(self, key):
  1713. self._od.pop(key, None)
  1714. self._od[key] = None
  1715. def discard(self, key):
  1716. self._od.pop(key, None)
  1717. # Agg's buffers are unmultiplied RGBA8888, which neither PyQt<=5.1 nor cairo
  1718. # support; however, both do support premultiplied ARGB32.
  1719. def _premultiplied_argb32_to_unmultiplied_rgba8888(buf):
  1720. """
  1721. Convert a premultiplied ARGB32 buffer to an unmultiplied RGBA8888 buffer.
  1722. """
  1723. rgba = np.take( # .take() ensures C-contiguity of the result.
  1724. buf,
  1725. [2, 1, 0, 3] if sys.byteorder == "little" else [1, 2, 3, 0], axis=2)
  1726. rgb = rgba[..., :-1]
  1727. alpha = rgba[..., -1]
  1728. # Un-premultiply alpha. The formula is the same as in cairo-png.c.
  1729. mask = alpha != 0
  1730. for channel in np.rollaxis(rgb, -1):
  1731. channel[mask] = (
  1732. (channel[mask].astype(int) * 255 + alpha[mask] // 2)
  1733. // alpha[mask])
  1734. return rgba
  1735. def _unmultiplied_rgba8888_to_premultiplied_argb32(rgba8888):
  1736. """
  1737. Convert an unmultiplied RGBA8888 buffer to a premultiplied ARGB32 buffer.
  1738. """
  1739. if sys.byteorder == "little":
  1740. argb32 = np.take(rgba8888, [2, 1, 0, 3], axis=2)
  1741. rgb24 = argb32[..., :-1]
  1742. alpha8 = argb32[..., -1:]
  1743. else:
  1744. argb32 = np.take(rgba8888, [3, 0, 1, 2], axis=2)
  1745. alpha8 = argb32[..., :1]
  1746. rgb24 = argb32[..., 1:]
  1747. # Only bother premultiplying when the alpha channel is not fully opaque,
  1748. # as the cost is not negligible. The unsafe cast is needed to do the
  1749. # multiplication in-place in an integer buffer.
  1750. if alpha8.min() != 0xff:
  1751. np.multiply(rgb24, alpha8 / 0xff, out=rgb24, casting="unsafe")
  1752. return argb32
  1753. def _get_nonzero_slices(buf):
  1754. """
  1755. Return the bounds of the nonzero region of a 2D array as a pair of slices.
  1756. ``buf[_get_nonzero_slices(buf)]`` is the smallest sub-rectangle in *buf*
  1757. that encloses all non-zero entries in *buf*. If *buf* is fully zero, then
  1758. ``(slice(0, 0), slice(0, 0))`` is returned.
  1759. """
  1760. x_nz, = buf.any(axis=0).nonzero()
  1761. y_nz, = buf.any(axis=1).nonzero()
  1762. if len(x_nz) and len(y_nz):
  1763. l, r = x_nz[[0, -1]]
  1764. b, t = y_nz[[0, -1]]
  1765. return slice(b, t + 1), slice(l, r + 1)
  1766. else:
  1767. return slice(0, 0), slice(0, 0)
  1768. def _pformat_subprocess(command):
  1769. """Pretty-format a subprocess command for printing/logging purposes."""
  1770. return (command if isinstance(command, str)
  1771. else " ".join(shlex.quote(os.fspath(arg)) for arg in command))
  1772. def _check_and_log_subprocess(command, logger, **kwargs):
  1773. """
  1774. Run *command*, returning its stdout output if it succeeds.
  1775. If it fails (exits with nonzero return code), raise an exception whose text
  1776. includes the failed command and captured stdout and stderr output.
  1777. Regardless of the return code, the command is logged at DEBUG level on
  1778. *logger*. In case of success, the output is likewise logged.
  1779. """
  1780. logger.debug('%s', _pformat_subprocess(command))
  1781. proc = subprocess.run(command, capture_output=True, **kwargs)
  1782. if proc.returncode:
  1783. stdout = proc.stdout
  1784. if isinstance(stdout, bytes):
  1785. stdout = stdout.decode()
  1786. stderr = proc.stderr
  1787. if isinstance(stderr, bytes):
  1788. stderr = stderr.decode()
  1789. raise RuntimeError(
  1790. f"The command\n"
  1791. f" {_pformat_subprocess(command)}\n"
  1792. f"failed and generated the following output:\n"
  1793. f"{stdout}\n"
  1794. f"and the following error:\n"
  1795. f"{stderr}")
  1796. if proc.stdout:
  1797. logger.debug("stdout:\n%s", proc.stdout)
  1798. if proc.stderr:
  1799. logger.debug("stderr:\n%s", proc.stderr)
  1800. return proc.stdout
  1801. def _backend_module_name(name):
  1802. """
  1803. Convert a backend name (either a standard backend -- "Agg", "TkAgg", ... --
  1804. or a custom backend -- "module://...") to the corresponding module name).
  1805. """
  1806. return (name[9:] if name.startswith("module://")
  1807. else f"matplotlib.backends.backend_{name.lower()}")
  1808. def _setup_new_guiapp():
  1809. """
  1810. Perform OS-dependent setup when Matplotlib creates a new GUI application.
  1811. """
  1812. # Windows: If not explicit app user model id has been set yet (so we're not
  1813. # already embedded), then set it to "matplotlib", so that taskbar icons are
  1814. # correct.
  1815. try:
  1816. _c_internal_utils.Win32_GetCurrentProcessExplicitAppUserModelID()
  1817. except OSError:
  1818. _c_internal_utils.Win32_SetCurrentProcessExplicitAppUserModelID(
  1819. "matplotlib")
  1820. def _format_approx(number, precision):
  1821. """
  1822. Format the number with at most the number of decimals given as precision.
  1823. Remove trailing zeros and possibly the decimal point.
  1824. """
  1825. return f'{number:.{precision}f}'.rstrip('0').rstrip('.') or '0'
  1826. def _g_sig_digits(value, delta):
  1827. """
  1828. Return the number of significant digits to %g-format *value*, assuming that
  1829. it is known with an error of *delta*.
  1830. """
  1831. if delta == 0:
  1832. # delta = 0 may occur when trying to format values over a tiny range;
  1833. # in that case, replace it by the distance to the closest float.
  1834. delta = abs(np.spacing(value))
  1835. # If e.g. value = 45.67 and delta = 0.02, then we want to round to 2 digits
  1836. # after the decimal point (floor(log10(0.02)) = -2); 45.67 contributes 2
  1837. # digits before the decimal point (floor(log10(45.67)) + 1 = 2): the total
  1838. # is 4 significant digits. A value of 0 contributes 1 "digit" before the
  1839. # decimal point.
  1840. # For inf or nan, the precision doesn't matter.
  1841. return max(
  1842. 0,
  1843. (math.floor(math.log10(abs(value))) + 1 if value else 1)
  1844. - math.floor(math.log10(delta))) if math.isfinite(value) else 0
  1845. def _unikey_or_keysym_to_mplkey(unikey, keysym):
  1846. """
  1847. Convert a Unicode key or X keysym to a Matplotlib key name.
  1848. The Unicode key is checked first; this avoids having to list most printable
  1849. keysyms such as ``EuroSign``.
  1850. """
  1851. # For non-printable characters, gtk3 passes "\0" whereas tk passes an "".
  1852. if unikey and unikey.isprintable():
  1853. return unikey
  1854. key = keysym.lower()
  1855. if key.startswith("kp_"): # keypad_x (including kp_enter).
  1856. key = key[3:]
  1857. if key.startswith("page_"): # page_{up,down}
  1858. key = key.replace("page_", "page")
  1859. if key.endswith(("_l", "_r")): # alt_l, ctrl_l, shift_l.
  1860. key = key[:-2]
  1861. if sys.platform == "darwin" and key == "meta":
  1862. # meta should be reported as command on mac
  1863. key = "cmd"
  1864. key = {
  1865. "return": "enter",
  1866. "prior": "pageup", # Used by tk.
  1867. "next": "pagedown", # Used by tk.
  1868. }.get(key, key)
  1869. return key
  1870. @functools.cache
  1871. def _make_class_factory(mixin_class, fmt, attr_name=None):
  1872. """
  1873. Return a function that creates picklable classes inheriting from a mixin.
  1874. After ::
  1875. factory = _make_class_factory(FooMixin, fmt, attr_name)
  1876. FooAxes = factory(Axes)
  1877. ``Foo`` is a class that inherits from ``FooMixin`` and ``Axes`` and **is
  1878. picklable** (picklability is what differentiates this from a plain call to
  1879. `type`). Its ``__name__`` is set to ``fmt.format(Axes.__name__)`` and the
  1880. base class is stored in the ``attr_name`` attribute, if not None.
  1881. Moreover, the return value of ``factory`` is memoized: calls with the same
  1882. ``Axes`` class always return the same subclass.
  1883. """
  1884. @functools.cache
  1885. def class_factory(axes_class):
  1886. # if we have already wrapped this class, declare victory!
  1887. if issubclass(axes_class, mixin_class):
  1888. return axes_class
  1889. # The parameter is named "axes_class" for backcompat but is really just
  1890. # a base class; no axes semantics are used.
  1891. base_class = axes_class
  1892. class subcls(mixin_class, base_class):
  1893. # Better approximation than __module__ = "matplotlib.cbook".
  1894. __module__ = mixin_class.__module__
  1895. def __reduce__(self):
  1896. return (_picklable_class_constructor,
  1897. (mixin_class, fmt, attr_name, base_class),
  1898. self.__getstate__())
  1899. subcls.__name__ = subcls.__qualname__ = fmt.format(base_class.__name__)
  1900. if attr_name is not None:
  1901. setattr(subcls, attr_name, base_class)
  1902. return subcls
  1903. class_factory.__module__ = mixin_class.__module__
  1904. return class_factory
  1905. def _picklable_class_constructor(mixin_class, fmt, attr_name, base_class):
  1906. """Internal helper for _make_class_factory."""
  1907. factory = _make_class_factory(mixin_class, fmt, attr_name)
  1908. cls = factory(base_class)
  1909. return cls.__new__(cls)
  1910. def _unpack_to_numpy(x):
  1911. """Internal helper to extract data from e.g. pandas and xarray objects."""
  1912. if isinstance(x, np.ndarray):
  1913. # If numpy, return directly
  1914. return x
  1915. if hasattr(x, 'to_numpy'):
  1916. # Assume that any to_numpy() method actually returns a numpy array
  1917. return x.to_numpy()
  1918. if hasattr(x, 'values'):
  1919. xtmp = x.values
  1920. # For example a dict has a 'values' attribute, but it is not a property
  1921. # so in this case we do not want to return a function
  1922. if isinstance(xtmp, np.ndarray):
  1923. return xtmp
  1924. return x
  1925. def _auto_format_str(fmt, value):
  1926. """
  1927. Apply *value* to the format string *fmt*.
  1928. This works both with unnamed %-style formatting and
  1929. unnamed {}-style formatting. %-style formatting has priority.
  1930. If *fmt* is %-style formattable that will be used. Otherwise,
  1931. {}-formatting is applied. Strings without formatting placeholders
  1932. are passed through as is.
  1933. Examples
  1934. --------
  1935. >>> _auto_format_str('%.2f m', 0.2)
  1936. '0.20 m'
  1937. >>> _auto_format_str('{} m', 0.2)
  1938. '0.2 m'
  1939. >>> _auto_format_str('const', 0.2)
  1940. 'const'
  1941. >>> _auto_format_str('%d or {}', 0.2)
  1942. '0 or {}'
  1943. """
  1944. try:
  1945. return fmt % (value,)
  1946. except (TypeError, ValueError):
  1947. return fmt.format(value)