transforms.py 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996
  1. """
  2. Matplotlib includes a framework for arbitrary geometric transformations that is used to
  3. determine the final position of all elements drawn on the canvas.
  4. Transforms are composed into trees of `TransformNode` objects
  5. whose actual value depends on their children. When the contents of
  6. children change, their parents are automatically invalidated. The
  7. next time an invalidated transform is accessed, it is recomputed to
  8. reflect those changes. This invalidation/caching approach prevents
  9. unnecessary recomputations of transforms, and contributes to better
  10. interactive performance.
  11. For example, here is a graph of the transform tree used to plot data to the figure:
  12. .. graphviz:: /api/transforms.dot
  13. :alt: Diagram of transform tree from data to figure coordinates.
  14. The framework can be used for both affine and non-affine
  15. transformations. However, for speed, we want to use the backend
  16. renderers to perform affine transformations whenever possible.
  17. Therefore, it is possible to perform just the affine or non-affine
  18. part of a transformation on a set of data. The affine is always
  19. assumed to occur after the non-affine. For any transform::
  20. full transform == non-affine part + affine part
  21. The backends are not expected to handle non-affine transformations
  22. themselves.
  23. See the tutorial :ref:`transforms_tutorial` for examples
  24. of how to use transforms.
  25. """
  26. # Note: There are a number of places in the code where we use `np.min` or
  27. # `np.minimum` instead of the builtin `min`, and likewise for `max`. This is
  28. # done so that `nan`s are propagated, instead of being silently dropped.
  29. import functools
  30. import itertools
  31. import textwrap
  32. import weakref
  33. import math
  34. import numpy as np
  35. from numpy.linalg import inv
  36. from matplotlib import _api
  37. from matplotlib._path import (
  38. affine_transform, count_bboxes_overlapping_bbox, update_path_extents)
  39. from .path import Path
  40. DEBUG = False
  41. def _make_str_method(*args, **kwargs):
  42. """
  43. Generate a ``__str__`` method for a `.Transform` subclass.
  44. After ::
  45. class T:
  46. __str__ = _make_str_method("attr", key="other")
  47. ``str(T(...))`` will be
  48. .. code-block:: text
  49. {type(T).__name__}(
  50. {self.attr},
  51. key={self.other})
  52. """
  53. indent = functools.partial(textwrap.indent, prefix=" " * 4)
  54. def strrepr(x): return repr(x) if isinstance(x, str) else str(x)
  55. return lambda self: (
  56. type(self).__name__ + "("
  57. + ",".join([*(indent("\n" + strrepr(getattr(self, arg)))
  58. for arg in args),
  59. *(indent("\n" + k + "=" + strrepr(getattr(self, arg)))
  60. for k, arg in kwargs.items())])
  61. + ")")
  62. class TransformNode:
  63. """
  64. The base class for anything that participates in the transform tree
  65. and needs to invalidate its parents or be invalidated. This includes
  66. classes that are not really transforms, such as bounding boxes, since some
  67. transforms depend on bounding boxes to compute their values.
  68. """
  69. # Invalidation may affect only the affine part. If the
  70. # invalidation was "affine-only", the _invalid member is set to
  71. # INVALID_AFFINE_ONLY
  72. # Possible values for the _invalid attribute.
  73. _VALID, _INVALID_AFFINE_ONLY, _INVALID_FULL = range(3)
  74. # Some metadata about the transform, used to determine whether an
  75. # invalidation is affine-only
  76. is_affine = False
  77. is_bbox = _api.deprecated("3.9")(_api.classproperty(lambda cls: False))
  78. pass_through = False
  79. """
  80. If pass_through is True, all ancestors will always be
  81. invalidated, even if 'self' is already invalid.
  82. """
  83. def __init__(self, shorthand_name=None):
  84. """
  85. Parameters
  86. ----------
  87. shorthand_name : str
  88. A string representing the "name" of the transform. The name carries
  89. no significance other than to improve the readability of
  90. ``str(transform)`` when DEBUG=True.
  91. """
  92. self._parents = {}
  93. # Initially invalid, until first computation.
  94. self._invalid = self._INVALID_FULL
  95. self._shorthand_name = shorthand_name or ''
  96. if DEBUG:
  97. def __str__(self):
  98. # either just return the name of this TransformNode, or its repr
  99. return self._shorthand_name or repr(self)
  100. def __getstate__(self):
  101. # turn the dictionary with weak values into a normal dictionary
  102. return {**self.__dict__,
  103. '_parents': {k: v() for k, v in self._parents.items()}}
  104. def __setstate__(self, data_dict):
  105. self.__dict__ = data_dict
  106. # turn the normal dictionary back into a dictionary with weak values
  107. # The extra lambda is to provide a callback to remove dead
  108. # weakrefs from the dictionary when garbage collection is done.
  109. self._parents = {
  110. k: weakref.ref(v, lambda _, pop=self._parents.pop, k=k: pop(k))
  111. for k, v in self._parents.items() if v is not None}
  112. def __copy__(self):
  113. cls = type(self)
  114. other = cls.__new__(cls)
  115. other.__dict__.update(self.__dict__)
  116. # If `c = a + b; a1 = copy(a)`, then modifications to `a1` do not
  117. # propagate back to `c`, i.e. we need to clear the parents of `a1`.
  118. other._parents = {}
  119. # If `c = a + b; c1 = copy(c)`, then modifications to `a` also need to
  120. # be propagated to `c1`.
  121. for key, val in vars(self).items():
  122. if isinstance(val, TransformNode) and id(self) in val._parents:
  123. other.set_children(val) # val == getattr(other, key)
  124. return other
  125. def invalidate(self):
  126. """
  127. Invalidate this `TransformNode` and triggers an invalidation of its
  128. ancestors. Should be called any time the transform changes.
  129. """
  130. return self._invalidate_internal(
  131. level=self._INVALID_AFFINE_ONLY if self.is_affine else self._INVALID_FULL,
  132. invalidating_node=self)
  133. def _invalidate_internal(self, level, invalidating_node):
  134. """
  135. Called by :meth:`invalidate` and subsequently ascends the transform
  136. stack calling each TransformNode's _invalidate_internal method.
  137. """
  138. # If we are already more invalid than the currently propagated invalidation,
  139. # then we don't need to do anything.
  140. if level <= self._invalid and not self.pass_through:
  141. return
  142. self._invalid = level
  143. for parent in list(self._parents.values()):
  144. parent = parent() # Dereference the weak reference.
  145. if parent is not None:
  146. parent._invalidate_internal(level=level, invalidating_node=self)
  147. def set_children(self, *children):
  148. """
  149. Set the children of the transform, to let the invalidation
  150. system know which transforms can invalidate this transform.
  151. Should be called from the constructor of any transforms that
  152. depend on other transforms.
  153. """
  154. # Parents are stored as weak references, so that if the
  155. # parents are destroyed, references from the children won't
  156. # keep them alive.
  157. id_self = id(self)
  158. for child in children:
  159. # Use weak references so this dictionary won't keep obsolete nodes
  160. # alive; the callback deletes the dictionary entry. This is a
  161. # performance improvement over using WeakValueDictionary.
  162. ref = weakref.ref(
  163. self, lambda _, pop=child._parents.pop, k=id_self: pop(k))
  164. child._parents[id_self] = ref
  165. def frozen(self):
  166. """
  167. Return a frozen copy of this transform node. The frozen copy will not
  168. be updated when its children change. Useful for storing a previously
  169. known state of a transform where ``copy.deepcopy()`` might normally be
  170. used.
  171. """
  172. return self
  173. class BboxBase(TransformNode):
  174. """
  175. The base class of all bounding boxes.
  176. This class is immutable; `Bbox` is a mutable subclass.
  177. The canonical representation is as two points, with no
  178. restrictions on their ordering. Convenience properties are
  179. provided to get the left, bottom, right and top edges and width
  180. and height, but these are not stored explicitly.
  181. """
  182. is_bbox = _api.deprecated("3.9")(_api.classproperty(lambda cls: True))
  183. is_affine = True
  184. if DEBUG:
  185. @staticmethod
  186. def _check(points):
  187. if isinstance(points, np.ma.MaskedArray):
  188. _api.warn_external("Bbox bounds are a masked array.")
  189. points = np.asarray(points)
  190. if any((points[1, :] - points[0, :]) == 0):
  191. _api.warn_external("Singular Bbox.")
  192. def frozen(self):
  193. return Bbox(self.get_points().copy())
  194. frozen.__doc__ = TransformNode.__doc__
  195. def __array__(self, *args, **kwargs):
  196. return self.get_points()
  197. @property
  198. def x0(self):
  199. """
  200. The first of the pair of *x* coordinates that define the bounding box.
  201. This is not guaranteed to be less than :attr:`x1` (for that, use
  202. :attr:`xmin`).
  203. """
  204. return self.get_points()[0, 0]
  205. @property
  206. def y0(self):
  207. """
  208. The first of the pair of *y* coordinates that define the bounding box.
  209. This is not guaranteed to be less than :attr:`y1` (for that, use
  210. :attr:`ymin`).
  211. """
  212. return self.get_points()[0, 1]
  213. @property
  214. def x1(self):
  215. """
  216. The second of the pair of *x* coordinates that define the bounding box.
  217. This is not guaranteed to be greater than :attr:`x0` (for that, use
  218. :attr:`xmax`).
  219. """
  220. return self.get_points()[1, 0]
  221. @property
  222. def y1(self):
  223. """
  224. The second of the pair of *y* coordinates that define the bounding box.
  225. This is not guaranteed to be greater than :attr:`y0` (for that, use
  226. :attr:`ymax`).
  227. """
  228. return self.get_points()[1, 1]
  229. @property
  230. def p0(self):
  231. """
  232. The first pair of (*x*, *y*) coordinates that define the bounding box.
  233. This is not guaranteed to be the bottom-left corner (for that, use
  234. :attr:`min`).
  235. """
  236. return self.get_points()[0]
  237. @property
  238. def p1(self):
  239. """
  240. The second pair of (*x*, *y*) coordinates that define the bounding box.
  241. This is not guaranteed to be the top-right corner (for that, use
  242. :attr:`max`).
  243. """
  244. return self.get_points()[1]
  245. @property
  246. def xmin(self):
  247. """The left edge of the bounding box."""
  248. return np.min(self.get_points()[:, 0])
  249. @property
  250. def ymin(self):
  251. """The bottom edge of the bounding box."""
  252. return np.min(self.get_points()[:, 1])
  253. @property
  254. def xmax(self):
  255. """The right edge of the bounding box."""
  256. return np.max(self.get_points()[:, 0])
  257. @property
  258. def ymax(self):
  259. """The top edge of the bounding box."""
  260. return np.max(self.get_points()[:, 1])
  261. @property
  262. def min(self):
  263. """The bottom-left corner of the bounding box."""
  264. return np.min(self.get_points(), axis=0)
  265. @property
  266. def max(self):
  267. """The top-right corner of the bounding box."""
  268. return np.max(self.get_points(), axis=0)
  269. @property
  270. def intervalx(self):
  271. """
  272. The pair of *x* coordinates that define the bounding box.
  273. This is not guaranteed to be sorted from left to right.
  274. """
  275. return self.get_points()[:, 0]
  276. @property
  277. def intervaly(self):
  278. """
  279. The pair of *y* coordinates that define the bounding box.
  280. This is not guaranteed to be sorted from bottom to top.
  281. """
  282. return self.get_points()[:, 1]
  283. @property
  284. def width(self):
  285. """The (signed) width of the bounding box."""
  286. points = self.get_points()
  287. return points[1, 0] - points[0, 0]
  288. @property
  289. def height(self):
  290. """The (signed) height of the bounding box."""
  291. points = self.get_points()
  292. return points[1, 1] - points[0, 1]
  293. @property
  294. def size(self):
  295. """The (signed) width and height of the bounding box."""
  296. points = self.get_points()
  297. return points[1] - points[0]
  298. @property
  299. def bounds(self):
  300. """Return (:attr:`x0`, :attr:`y0`, :attr:`width`, :attr:`height`)."""
  301. (x0, y0), (x1, y1) = self.get_points()
  302. return (x0, y0, x1 - x0, y1 - y0)
  303. @property
  304. def extents(self):
  305. """Return (:attr:`x0`, :attr:`y0`, :attr:`x1`, :attr:`y1`)."""
  306. return self.get_points().flatten() # flatten returns a copy.
  307. def get_points(self):
  308. raise NotImplementedError
  309. def containsx(self, x):
  310. """
  311. Return whether *x* is in the closed (:attr:`x0`, :attr:`x1`) interval.
  312. """
  313. x0, x1 = self.intervalx
  314. return x0 <= x <= x1 or x0 >= x >= x1
  315. def containsy(self, y):
  316. """
  317. Return whether *y* is in the closed (:attr:`y0`, :attr:`y1`) interval.
  318. """
  319. y0, y1 = self.intervaly
  320. return y0 <= y <= y1 or y0 >= y >= y1
  321. def contains(self, x, y):
  322. """
  323. Return whether ``(x, y)`` is in the bounding box or on its edge.
  324. """
  325. return self.containsx(x) and self.containsy(y)
  326. def overlaps(self, other):
  327. """
  328. Return whether this bounding box overlaps with the other bounding box.
  329. Parameters
  330. ----------
  331. other : `.BboxBase`
  332. """
  333. ax1, ay1, ax2, ay2 = self.extents
  334. bx1, by1, bx2, by2 = other.extents
  335. if ax2 < ax1:
  336. ax2, ax1 = ax1, ax2
  337. if ay2 < ay1:
  338. ay2, ay1 = ay1, ay2
  339. if bx2 < bx1:
  340. bx2, bx1 = bx1, bx2
  341. if by2 < by1:
  342. by2, by1 = by1, by2
  343. return ax1 <= bx2 and bx1 <= ax2 and ay1 <= by2 and by1 <= ay2
  344. def fully_containsx(self, x):
  345. """
  346. Return whether *x* is in the open (:attr:`x0`, :attr:`x1`) interval.
  347. """
  348. x0, x1 = self.intervalx
  349. return x0 < x < x1 or x0 > x > x1
  350. def fully_containsy(self, y):
  351. """
  352. Return whether *y* is in the open (:attr:`y0`, :attr:`y1`) interval.
  353. """
  354. y0, y1 = self.intervaly
  355. return y0 < y < y1 or y0 > y > y1
  356. def fully_contains(self, x, y):
  357. """
  358. Return whether ``x, y`` is in the bounding box, but not on its edge.
  359. """
  360. return self.fully_containsx(x) and self.fully_containsy(y)
  361. def fully_overlaps(self, other):
  362. """
  363. Return whether this bounding box overlaps with the other bounding box,
  364. not including the edges.
  365. Parameters
  366. ----------
  367. other : `.BboxBase`
  368. """
  369. ax1, ay1, ax2, ay2 = self.extents
  370. bx1, by1, bx2, by2 = other.extents
  371. if ax2 < ax1:
  372. ax2, ax1 = ax1, ax2
  373. if ay2 < ay1:
  374. ay2, ay1 = ay1, ay2
  375. if bx2 < bx1:
  376. bx2, bx1 = bx1, bx2
  377. if by2 < by1:
  378. by2, by1 = by1, by2
  379. return ax1 < bx2 and bx1 < ax2 and ay1 < by2 and by1 < ay2
  380. def transformed(self, transform):
  381. """
  382. Construct a `Bbox` by statically transforming this one by *transform*.
  383. """
  384. pts = self.get_points()
  385. ll, ul, lr = transform.transform(np.array(
  386. [pts[0], [pts[0, 0], pts[1, 1]], [pts[1, 0], pts[0, 1]]]))
  387. return Bbox([ll, [lr[0], ul[1]]])
  388. coefs = {'C': (0.5, 0.5),
  389. 'SW': (0, 0),
  390. 'S': (0.5, 0),
  391. 'SE': (1.0, 0),
  392. 'E': (1.0, 0.5),
  393. 'NE': (1.0, 1.0),
  394. 'N': (0.5, 1.0),
  395. 'NW': (0, 1.0),
  396. 'W': (0, 0.5)}
  397. def anchored(self, c, container):
  398. """
  399. Return a copy of the `Bbox` anchored to *c* within *container*.
  400. Parameters
  401. ----------
  402. c : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
  403. Either an (*x*, *y*) pair of relative coordinates (0 is left or
  404. bottom, 1 is right or top), 'C' (center), or a cardinal direction
  405. ('SW', southwest, is bottom left, etc.).
  406. container : `Bbox`
  407. The box within which the `Bbox` is positioned.
  408. See Also
  409. --------
  410. .Axes.set_anchor
  411. """
  412. l, b, w, h = container.bounds
  413. L, B, W, H = self.bounds
  414. cx, cy = self.coefs[c] if isinstance(c, str) else c
  415. return Bbox(self._points +
  416. [(l + cx * (w - W)) - L,
  417. (b + cy * (h - H)) - B])
  418. def shrunk(self, mx, my):
  419. """
  420. Return a copy of the `Bbox`, shrunk by the factor *mx*
  421. in the *x* direction and the factor *my* in the *y* direction.
  422. The lower left corner of the box remains unchanged. Normally
  423. *mx* and *my* will be less than 1, but this is not enforced.
  424. """
  425. w, h = self.size
  426. return Bbox([self._points[0],
  427. self._points[0] + [mx * w, my * h]])
  428. def shrunk_to_aspect(self, box_aspect, container=None, fig_aspect=1.0):
  429. """
  430. Return a copy of the `Bbox`, shrunk so that it is as
  431. large as it can be while having the desired aspect ratio,
  432. *box_aspect*. If the box coordinates are relative (i.e.
  433. fractions of a larger box such as a figure) then the
  434. physical aspect ratio of that figure is specified with
  435. *fig_aspect*, so that *box_aspect* can also be given as a
  436. ratio of the absolute dimensions, not the relative dimensions.
  437. """
  438. if box_aspect <= 0 or fig_aspect <= 0:
  439. raise ValueError("'box_aspect' and 'fig_aspect' must be positive")
  440. if container is None:
  441. container = self
  442. w, h = container.size
  443. H = w * box_aspect / fig_aspect
  444. if H <= h:
  445. W = w
  446. else:
  447. W = h * fig_aspect / box_aspect
  448. H = h
  449. return Bbox([self._points[0],
  450. self._points[0] + (W, H)])
  451. def splitx(self, *args):
  452. """
  453. Return a list of new `Bbox` objects formed by splitting the original
  454. one with vertical lines at fractional positions given by *args*.
  455. """
  456. xf = [0, *args, 1]
  457. x0, y0, x1, y1 = self.extents
  458. w = x1 - x0
  459. return [Bbox([[x0 + xf0 * w, y0], [x0 + xf1 * w, y1]])
  460. for xf0, xf1 in itertools.pairwise(xf)]
  461. def splity(self, *args):
  462. """
  463. Return a list of new `Bbox` objects formed by splitting the original
  464. one with horizontal lines at fractional positions given by *args*.
  465. """
  466. yf = [0, *args, 1]
  467. x0, y0, x1, y1 = self.extents
  468. h = y1 - y0
  469. return [Bbox([[x0, y0 + yf0 * h], [x1, y0 + yf1 * h]])
  470. for yf0, yf1 in itertools.pairwise(yf)]
  471. def count_contains(self, vertices):
  472. """
  473. Count the number of vertices contained in the `Bbox`.
  474. Any vertices with a non-finite x or y value are ignored.
  475. Parameters
  476. ----------
  477. vertices : (N, 2) array
  478. """
  479. if len(vertices) == 0:
  480. return 0
  481. vertices = np.asarray(vertices)
  482. with np.errstate(invalid='ignore'):
  483. return (((self.min < vertices) &
  484. (vertices < self.max)).all(axis=1).sum())
  485. def count_overlaps(self, bboxes):
  486. """
  487. Count the number of bounding boxes that overlap this one.
  488. Parameters
  489. ----------
  490. bboxes : sequence of `.BboxBase`
  491. """
  492. return count_bboxes_overlapping_bbox(
  493. self, np.atleast_3d([np.array(x) for x in bboxes]))
  494. def expanded(self, sw, sh):
  495. """
  496. Construct a `Bbox` by expanding this one around its center by the
  497. factors *sw* and *sh*.
  498. """
  499. width = self.width
  500. height = self.height
  501. deltaw = (sw * width - width) / 2.0
  502. deltah = (sh * height - height) / 2.0
  503. a = np.array([[-deltaw, -deltah], [deltaw, deltah]])
  504. return Bbox(self._points + a)
  505. def padded(self, w_pad, h_pad=None):
  506. """
  507. Construct a `Bbox` by padding this one on all four sides.
  508. Parameters
  509. ----------
  510. w_pad : float
  511. Width pad
  512. h_pad : float, optional
  513. Height pad. Defaults to *w_pad*.
  514. """
  515. points = self.get_points()
  516. if h_pad is None:
  517. h_pad = w_pad
  518. return Bbox(points + [[-w_pad, -h_pad], [w_pad, h_pad]])
  519. def translated(self, tx, ty):
  520. """Construct a `Bbox` by translating this one by *tx* and *ty*."""
  521. return Bbox(self._points + (tx, ty))
  522. def corners(self):
  523. """
  524. Return the corners of this rectangle as an array of points.
  525. Specifically, this returns the array
  526. ``[[x0, y0], [x0, y1], [x1, y0], [x1, y1]]``.
  527. """
  528. (x0, y0), (x1, y1) = self.get_points()
  529. return np.array([[x0, y0], [x0, y1], [x1, y0], [x1, y1]])
  530. def rotated(self, radians):
  531. """
  532. Return the axes-aligned bounding box that bounds the result of rotating
  533. this `Bbox` by an angle of *radians*.
  534. """
  535. corners = self.corners()
  536. corners_rotated = Affine2D().rotate(radians).transform(corners)
  537. bbox = Bbox.unit()
  538. bbox.update_from_data_xy(corners_rotated, ignore=True)
  539. return bbox
  540. @staticmethod
  541. def union(bboxes):
  542. """Return a `Bbox` that contains all of the given *bboxes*."""
  543. if not len(bboxes):
  544. raise ValueError("'bboxes' cannot be empty")
  545. x0 = np.min([bbox.xmin for bbox in bboxes])
  546. x1 = np.max([bbox.xmax for bbox in bboxes])
  547. y0 = np.min([bbox.ymin for bbox in bboxes])
  548. y1 = np.max([bbox.ymax for bbox in bboxes])
  549. return Bbox([[x0, y0], [x1, y1]])
  550. @staticmethod
  551. def intersection(bbox1, bbox2):
  552. """
  553. Return the intersection of *bbox1* and *bbox2* if they intersect, or
  554. None if they don't.
  555. """
  556. x0 = np.maximum(bbox1.xmin, bbox2.xmin)
  557. x1 = np.minimum(bbox1.xmax, bbox2.xmax)
  558. y0 = np.maximum(bbox1.ymin, bbox2.ymin)
  559. y1 = np.minimum(bbox1.ymax, bbox2.ymax)
  560. return Bbox([[x0, y0], [x1, y1]]) if x0 <= x1 and y0 <= y1 else None
  561. _default_minpos = np.array([np.inf, np.inf])
  562. class Bbox(BboxBase):
  563. """
  564. A mutable bounding box.
  565. Examples
  566. --------
  567. **Create from known bounds**
  568. The default constructor takes the boundary "points" ``[[xmin, ymin],
  569. [xmax, ymax]]``.
  570. >>> Bbox([[1, 1], [3, 7]])
  571. Bbox([[1.0, 1.0], [3.0, 7.0]])
  572. Alternatively, a Bbox can be created from the flattened points array, the
  573. so-called "extents" ``(xmin, ymin, xmax, ymax)``
  574. >>> Bbox.from_extents(1, 1, 3, 7)
  575. Bbox([[1.0, 1.0], [3.0, 7.0]])
  576. or from the "bounds" ``(xmin, ymin, width, height)``.
  577. >>> Bbox.from_bounds(1, 1, 2, 6)
  578. Bbox([[1.0, 1.0], [3.0, 7.0]])
  579. **Create from collections of points**
  580. The "empty" object for accumulating Bboxs is the null bbox, which is a
  581. stand-in for the empty set.
  582. >>> Bbox.null()
  583. Bbox([[inf, inf], [-inf, -inf]])
  584. Adding points to the null bbox will give you the bbox of those points.
  585. >>> box = Bbox.null()
  586. >>> box.update_from_data_xy([[1, 1]])
  587. >>> box
  588. Bbox([[1.0, 1.0], [1.0, 1.0]])
  589. >>> box.update_from_data_xy([[2, 3], [3, 2]], ignore=False)
  590. >>> box
  591. Bbox([[1.0, 1.0], [3.0, 3.0]])
  592. Setting ``ignore=True`` is equivalent to starting over from a null bbox.
  593. >>> box.update_from_data_xy([[1, 1]], ignore=True)
  594. >>> box
  595. Bbox([[1.0, 1.0], [1.0, 1.0]])
  596. .. warning::
  597. It is recommended to always specify ``ignore`` explicitly. If not, the
  598. default value of ``ignore`` can be changed at any time by code with
  599. access to your Bbox, for example using the method `~.Bbox.ignore`.
  600. **Properties of the ``null`` bbox**
  601. .. note::
  602. The current behavior of `Bbox.null()` may be surprising as it does
  603. not have all of the properties of the "empty set", and as such does
  604. not behave like a "zero" object in the mathematical sense. We may
  605. change that in the future (with a deprecation period).
  606. The null bbox is the identity for intersections
  607. >>> Bbox.intersection(Bbox([[1, 1], [3, 7]]), Bbox.null())
  608. Bbox([[1.0, 1.0], [3.0, 7.0]])
  609. except with itself, where it returns the full space.
  610. >>> Bbox.intersection(Bbox.null(), Bbox.null())
  611. Bbox([[-inf, -inf], [inf, inf]])
  612. A union containing null will always return the full space (not the other
  613. set!)
  614. >>> Bbox.union([Bbox([[0, 0], [0, 0]]), Bbox.null()])
  615. Bbox([[-inf, -inf], [inf, inf]])
  616. """
  617. def __init__(self, points, **kwargs):
  618. """
  619. Parameters
  620. ----------
  621. points : `~numpy.ndarray`
  622. A (2, 2) array of the form ``[[x0, y0], [x1, y1]]``.
  623. """
  624. super().__init__(**kwargs)
  625. points = np.asarray(points, float)
  626. if points.shape != (2, 2):
  627. raise ValueError('Bbox points must be of the form '
  628. '"[[x0, y0], [x1, y1]]".')
  629. self._points = points
  630. self._minpos = _default_minpos.copy()
  631. self._ignore = True
  632. # it is helpful in some contexts to know if the bbox is a
  633. # default or has been mutated; we store the orig points to
  634. # support the mutated methods
  635. self._points_orig = self._points.copy()
  636. if DEBUG:
  637. ___init__ = __init__
  638. def __init__(self, points, **kwargs):
  639. self._check(points)
  640. self.___init__(points, **kwargs)
  641. def invalidate(self):
  642. self._check(self._points)
  643. super().invalidate()
  644. def frozen(self):
  645. # docstring inherited
  646. frozen_bbox = super().frozen()
  647. frozen_bbox._minpos = self.minpos.copy()
  648. return frozen_bbox
  649. @staticmethod
  650. def unit():
  651. """Create a new unit `Bbox` from (0, 0) to (1, 1)."""
  652. return Bbox([[0, 0], [1, 1]])
  653. @staticmethod
  654. def null():
  655. """Create a new null `Bbox` from (inf, inf) to (-inf, -inf)."""
  656. return Bbox([[np.inf, np.inf], [-np.inf, -np.inf]])
  657. @staticmethod
  658. def from_bounds(x0, y0, width, height):
  659. """
  660. Create a new `Bbox` from *x0*, *y0*, *width* and *height*.
  661. *width* and *height* may be negative.
  662. """
  663. return Bbox.from_extents(x0, y0, x0 + width, y0 + height)
  664. @staticmethod
  665. def from_extents(*args, minpos=None):
  666. """
  667. Create a new Bbox from *left*, *bottom*, *right* and *top*.
  668. The *y*-axis increases upwards.
  669. Parameters
  670. ----------
  671. left, bottom, right, top : float
  672. The four extents of the bounding box.
  673. minpos : float or None
  674. If this is supplied, the Bbox will have a minimum positive value
  675. set. This is useful when dealing with logarithmic scales and other
  676. scales where negative bounds result in floating point errors.
  677. """
  678. bbox = Bbox(np.reshape(args, (2, 2)))
  679. if minpos is not None:
  680. bbox._minpos[:] = minpos
  681. return bbox
  682. def __format__(self, fmt):
  683. return (
  684. 'Bbox(x0={0.x0:{1}}, y0={0.y0:{1}}, x1={0.x1:{1}}, y1={0.y1:{1}})'.
  685. format(self, fmt))
  686. def __str__(self):
  687. return format(self, '')
  688. def __repr__(self):
  689. return 'Bbox([[{0.x0}, {0.y0}], [{0.x1}, {0.y1}]])'.format(self)
  690. def ignore(self, value):
  691. """
  692. Set whether the existing bounds of the box should be ignored
  693. by subsequent calls to :meth:`update_from_data_xy`.
  694. value : bool
  695. - When ``True``, subsequent calls to `update_from_data_xy` will
  696. ignore the existing bounds of the `Bbox`.
  697. - When ``False``, subsequent calls to `update_from_data_xy` will
  698. include the existing bounds of the `Bbox`.
  699. """
  700. self._ignore = value
  701. def update_from_path(self, path, ignore=None, updatex=True, updatey=True):
  702. """
  703. Update the bounds of the `Bbox` to contain the vertices of the
  704. provided path. After updating, the bounds will have positive *width*
  705. and *height*; *x0* and *y0* will be the minimal values.
  706. Parameters
  707. ----------
  708. path : `~matplotlib.path.Path`
  709. ignore : bool, optional
  710. - When ``True``, ignore the existing bounds of the `Bbox`.
  711. - When ``False``, include the existing bounds of the `Bbox`.
  712. - When ``None``, use the last value passed to :meth:`ignore`.
  713. updatex, updatey : bool, default: True
  714. When ``True``, update the x/y values.
  715. """
  716. if ignore is None:
  717. ignore = self._ignore
  718. if path.vertices.size == 0:
  719. return
  720. points, minpos, changed = update_path_extents(
  721. path, None, self._points, self._minpos, ignore)
  722. if changed:
  723. self.invalidate()
  724. if updatex:
  725. self._points[:, 0] = points[:, 0]
  726. self._minpos[0] = minpos[0]
  727. if updatey:
  728. self._points[:, 1] = points[:, 1]
  729. self._minpos[1] = minpos[1]
  730. def update_from_data_x(self, x, ignore=None):
  731. """
  732. Update the x-bounds of the `Bbox` based on the passed in data. After
  733. updating, the bounds will have positive *width*, and *x0* will be the
  734. minimal value.
  735. Parameters
  736. ----------
  737. x : `~numpy.ndarray`
  738. Array of x-values.
  739. ignore : bool, optional
  740. - When ``True``, ignore the existing bounds of the `Bbox`.
  741. - When ``False``, include the existing bounds of the `Bbox`.
  742. - When ``None``, use the last value passed to :meth:`ignore`.
  743. """
  744. x = np.ravel(x)
  745. self.update_from_data_xy(np.column_stack([x, np.ones(x.size)]),
  746. ignore=ignore, updatey=False)
  747. def update_from_data_y(self, y, ignore=None):
  748. """
  749. Update the y-bounds of the `Bbox` based on the passed in data. After
  750. updating, the bounds will have positive *height*, and *y0* will be the
  751. minimal value.
  752. Parameters
  753. ----------
  754. y : `~numpy.ndarray`
  755. Array of y-values.
  756. ignore : bool, optional
  757. - When ``True``, ignore the existing bounds of the `Bbox`.
  758. - When ``False``, include the existing bounds of the `Bbox`.
  759. - When ``None``, use the last value passed to :meth:`ignore`.
  760. """
  761. y = np.ravel(y)
  762. self.update_from_data_xy(np.column_stack([np.ones(y.size), y]),
  763. ignore=ignore, updatex=False)
  764. def update_from_data_xy(self, xy, ignore=None, updatex=True, updatey=True):
  765. """
  766. Update the `Bbox` bounds based on the passed in *xy* coordinates.
  767. After updating, the bounds will have positive *width* and *height*;
  768. *x0* and *y0* will be the minimal values.
  769. Parameters
  770. ----------
  771. xy : (N, 2) array-like
  772. The (x, y) coordinates.
  773. ignore : bool, optional
  774. - When ``True``, ignore the existing bounds of the `Bbox`.
  775. - When ``False``, include the existing bounds of the `Bbox`.
  776. - When ``None``, use the last value passed to :meth:`ignore`.
  777. updatex, updatey : bool, default: True
  778. When ``True``, update the x/y values.
  779. """
  780. if len(xy) == 0:
  781. return
  782. path = Path(xy)
  783. self.update_from_path(path, ignore=ignore,
  784. updatex=updatex, updatey=updatey)
  785. @BboxBase.x0.setter
  786. def x0(self, val):
  787. self._points[0, 0] = val
  788. self.invalidate()
  789. @BboxBase.y0.setter
  790. def y0(self, val):
  791. self._points[0, 1] = val
  792. self.invalidate()
  793. @BboxBase.x1.setter
  794. def x1(self, val):
  795. self._points[1, 0] = val
  796. self.invalidate()
  797. @BboxBase.y1.setter
  798. def y1(self, val):
  799. self._points[1, 1] = val
  800. self.invalidate()
  801. @BboxBase.p0.setter
  802. def p0(self, val):
  803. self._points[0] = val
  804. self.invalidate()
  805. @BboxBase.p1.setter
  806. def p1(self, val):
  807. self._points[1] = val
  808. self.invalidate()
  809. @BboxBase.intervalx.setter
  810. def intervalx(self, interval):
  811. self._points[:, 0] = interval
  812. self.invalidate()
  813. @BboxBase.intervaly.setter
  814. def intervaly(self, interval):
  815. self._points[:, 1] = interval
  816. self.invalidate()
  817. @BboxBase.bounds.setter
  818. def bounds(self, bounds):
  819. l, b, w, h = bounds
  820. points = np.array([[l, b], [l + w, b + h]], float)
  821. if np.any(self._points != points):
  822. self._points = points
  823. self.invalidate()
  824. @property
  825. def minpos(self):
  826. """
  827. The minimum positive value in both directions within the Bbox.
  828. This is useful when dealing with logarithmic scales and other scales
  829. where negative bounds result in floating point errors, and will be used
  830. as the minimum extent instead of *p0*.
  831. """
  832. return self._minpos
  833. @minpos.setter
  834. def minpos(self, val):
  835. self._minpos[:] = val
  836. @property
  837. def minposx(self):
  838. """
  839. The minimum positive value in the *x*-direction within the Bbox.
  840. This is useful when dealing with logarithmic scales and other scales
  841. where negative bounds result in floating point errors, and will be used
  842. as the minimum *x*-extent instead of *x0*.
  843. """
  844. return self._minpos[0]
  845. @minposx.setter
  846. def minposx(self, val):
  847. self._minpos[0] = val
  848. @property
  849. def minposy(self):
  850. """
  851. The minimum positive value in the *y*-direction within the Bbox.
  852. This is useful when dealing with logarithmic scales and other scales
  853. where negative bounds result in floating point errors, and will be used
  854. as the minimum *y*-extent instead of *y0*.
  855. """
  856. return self._minpos[1]
  857. @minposy.setter
  858. def minposy(self, val):
  859. self._minpos[1] = val
  860. def get_points(self):
  861. """
  862. Get the points of the bounding box as an array of the form
  863. ``[[x0, y0], [x1, y1]]``.
  864. """
  865. self._invalid = 0
  866. return self._points
  867. def set_points(self, points):
  868. """
  869. Set the points of the bounding box directly from an array of the form
  870. ``[[x0, y0], [x1, y1]]``. No error checking is performed, as this
  871. method is mainly for internal use.
  872. """
  873. if np.any(self._points != points):
  874. self._points = points
  875. self.invalidate()
  876. def set(self, other):
  877. """
  878. Set this bounding box from the "frozen" bounds of another `Bbox`.
  879. """
  880. if np.any(self._points != other.get_points()):
  881. self._points = other.get_points()
  882. self.invalidate()
  883. def mutated(self):
  884. """Return whether the bbox has changed since init."""
  885. return self.mutatedx() or self.mutatedy()
  886. def mutatedx(self):
  887. """Return whether the x-limits have changed since init."""
  888. return (self._points[0, 0] != self._points_orig[0, 0] or
  889. self._points[1, 0] != self._points_orig[1, 0])
  890. def mutatedy(self):
  891. """Return whether the y-limits have changed since init."""
  892. return (self._points[0, 1] != self._points_orig[0, 1] or
  893. self._points[1, 1] != self._points_orig[1, 1])
  894. class TransformedBbox(BboxBase):
  895. """
  896. A `Bbox` that is automatically transformed by a given
  897. transform. When either the child bounding box or transform
  898. changes, the bounds of this bbox will update accordingly.
  899. """
  900. def __init__(self, bbox, transform, **kwargs):
  901. """
  902. Parameters
  903. ----------
  904. bbox : `Bbox`
  905. transform : `Transform`
  906. """
  907. _api.check_isinstance(BboxBase, bbox=bbox)
  908. _api.check_isinstance(Transform, transform=transform)
  909. if transform.input_dims != 2 or transform.output_dims != 2:
  910. raise ValueError(
  911. "The input and output dimensions of 'transform' must be 2")
  912. super().__init__(**kwargs)
  913. self._bbox = bbox
  914. self._transform = transform
  915. self.set_children(bbox, transform)
  916. self._points = None
  917. __str__ = _make_str_method("_bbox", "_transform")
  918. def get_points(self):
  919. # docstring inherited
  920. if self._invalid:
  921. p = self._bbox.get_points()
  922. # Transform all four points, then make a new bounding box
  923. # from the result, taking care to make the orientation the
  924. # same.
  925. points = self._transform.transform(
  926. [[p[0, 0], p[0, 1]],
  927. [p[1, 0], p[0, 1]],
  928. [p[0, 0], p[1, 1]],
  929. [p[1, 0], p[1, 1]]])
  930. points = np.ma.filled(points, 0.0)
  931. xs = min(points[:, 0]), max(points[:, 0])
  932. if p[0, 0] > p[1, 0]:
  933. xs = xs[::-1]
  934. ys = min(points[:, 1]), max(points[:, 1])
  935. if p[0, 1] > p[1, 1]:
  936. ys = ys[::-1]
  937. self._points = np.array([
  938. [xs[0], ys[0]],
  939. [xs[1], ys[1]]
  940. ])
  941. self._invalid = 0
  942. return self._points
  943. if DEBUG:
  944. _get_points = get_points
  945. def get_points(self):
  946. points = self._get_points()
  947. self._check(points)
  948. return points
  949. def contains(self, x, y):
  950. # Docstring inherited.
  951. return self._bbox.contains(*self._transform.inverted().transform((x, y)))
  952. def fully_contains(self, x, y):
  953. # Docstring inherited.
  954. return self._bbox.fully_contains(*self._transform.inverted().transform((x, y)))
  955. class LockableBbox(BboxBase):
  956. """
  957. A `Bbox` where some elements may be locked at certain values.
  958. When the child bounding box changes, the bounds of this bbox will update
  959. accordingly with the exception of the locked elements.
  960. """
  961. def __init__(self, bbox, x0=None, y0=None, x1=None, y1=None, **kwargs):
  962. """
  963. Parameters
  964. ----------
  965. bbox : `Bbox`
  966. The child bounding box to wrap.
  967. x0 : float or None
  968. The locked value for x0, or None to leave unlocked.
  969. y0 : float or None
  970. The locked value for y0, or None to leave unlocked.
  971. x1 : float or None
  972. The locked value for x1, or None to leave unlocked.
  973. y1 : float or None
  974. The locked value for y1, or None to leave unlocked.
  975. """
  976. _api.check_isinstance(BboxBase, bbox=bbox)
  977. super().__init__(**kwargs)
  978. self._bbox = bbox
  979. self.set_children(bbox)
  980. self._points = None
  981. fp = [x0, y0, x1, y1]
  982. mask = [val is None for val in fp]
  983. self._locked_points = np.ma.array(fp, float, mask=mask).reshape((2, 2))
  984. __str__ = _make_str_method("_bbox", "_locked_points")
  985. def get_points(self):
  986. # docstring inherited
  987. if self._invalid:
  988. points = self._bbox.get_points()
  989. self._points = np.where(self._locked_points.mask,
  990. points,
  991. self._locked_points)
  992. self._invalid = 0
  993. return self._points
  994. if DEBUG:
  995. _get_points = get_points
  996. def get_points(self):
  997. points = self._get_points()
  998. self._check(points)
  999. return points
  1000. @property
  1001. def locked_x0(self):
  1002. """
  1003. float or None: The value used for the locked x0.
  1004. """
  1005. if self._locked_points.mask[0, 0]:
  1006. return None
  1007. else:
  1008. return self._locked_points[0, 0]
  1009. @locked_x0.setter
  1010. def locked_x0(self, x0):
  1011. self._locked_points.mask[0, 0] = x0 is None
  1012. self._locked_points.data[0, 0] = x0
  1013. self.invalidate()
  1014. @property
  1015. def locked_y0(self):
  1016. """
  1017. float or None: The value used for the locked y0.
  1018. """
  1019. if self._locked_points.mask[0, 1]:
  1020. return None
  1021. else:
  1022. return self._locked_points[0, 1]
  1023. @locked_y0.setter
  1024. def locked_y0(self, y0):
  1025. self._locked_points.mask[0, 1] = y0 is None
  1026. self._locked_points.data[0, 1] = y0
  1027. self.invalidate()
  1028. @property
  1029. def locked_x1(self):
  1030. """
  1031. float or None: The value used for the locked x1.
  1032. """
  1033. if self._locked_points.mask[1, 0]:
  1034. return None
  1035. else:
  1036. return self._locked_points[1, 0]
  1037. @locked_x1.setter
  1038. def locked_x1(self, x1):
  1039. self._locked_points.mask[1, 0] = x1 is None
  1040. self._locked_points.data[1, 0] = x1
  1041. self.invalidate()
  1042. @property
  1043. def locked_y1(self):
  1044. """
  1045. float or None: The value used for the locked y1.
  1046. """
  1047. if self._locked_points.mask[1, 1]:
  1048. return None
  1049. else:
  1050. return self._locked_points[1, 1]
  1051. @locked_y1.setter
  1052. def locked_y1(self, y1):
  1053. self._locked_points.mask[1, 1] = y1 is None
  1054. self._locked_points.data[1, 1] = y1
  1055. self.invalidate()
  1056. class Transform(TransformNode):
  1057. """
  1058. The base class of all `TransformNode` instances that
  1059. actually perform a transformation.
  1060. All non-affine transformations should be subclasses of this class.
  1061. New affine transformations should be subclasses of `Affine2D`.
  1062. Subclasses of this class should override the following members (at
  1063. minimum):
  1064. - :attr:`input_dims`
  1065. - :attr:`output_dims`
  1066. - :meth:`transform`
  1067. - :meth:`inverted` (if an inverse exists)
  1068. The following attributes may be overridden if the default is unsuitable:
  1069. - :attr:`is_separable` (defaults to True for 1D -> 1D transforms, False
  1070. otherwise)
  1071. - :attr:`has_inverse` (defaults to True if :meth:`inverted` is overridden,
  1072. False otherwise)
  1073. If the transform needs to do something non-standard with
  1074. `matplotlib.path.Path` objects, such as adding curves
  1075. where there were once line segments, it should override:
  1076. - :meth:`transform_path`
  1077. """
  1078. input_dims = None
  1079. """
  1080. The number of input dimensions of this transform.
  1081. Must be overridden (with integers) in the subclass.
  1082. """
  1083. output_dims = None
  1084. """
  1085. The number of output dimensions of this transform.
  1086. Must be overridden (with integers) in the subclass.
  1087. """
  1088. is_separable = False
  1089. """True if this transform is separable in the x- and y- dimensions."""
  1090. has_inverse = False
  1091. """True if this transform has a corresponding inverse transform."""
  1092. def __init_subclass__(cls):
  1093. # 1d transforms are always separable; we assume higher-dimensional ones
  1094. # are not but subclasses can also directly set is_separable -- this is
  1095. # verified by checking whether "is_separable" appears more than once in
  1096. # the class's MRO (it appears once in Transform).
  1097. if (sum("is_separable" in vars(parent) for parent in cls.__mro__) == 1
  1098. and cls.input_dims == cls.output_dims == 1):
  1099. cls.is_separable = True
  1100. # Transform.inverted raises NotImplementedError; we assume that if this
  1101. # is overridden then the transform is invertible but subclass can also
  1102. # directly set has_inverse.
  1103. if (sum("has_inverse" in vars(parent) for parent in cls.__mro__) == 1
  1104. and hasattr(cls, "inverted")
  1105. and cls.inverted is not Transform.inverted):
  1106. cls.has_inverse = True
  1107. def __add__(self, other):
  1108. """
  1109. Compose two transforms together so that *self* is followed by *other*.
  1110. ``A + B`` returns a transform ``C`` so that
  1111. ``C.transform(x) == B.transform(A.transform(x))``.
  1112. """
  1113. return (composite_transform_factory(self, other)
  1114. if isinstance(other, Transform) else
  1115. NotImplemented)
  1116. # Equality is based on object identity for `Transform`s (so we don't
  1117. # override `__eq__`), but some subclasses, such as TransformWrapper &
  1118. # AffineBase, override this behavior.
  1119. def _iter_break_from_left_to_right(self):
  1120. """
  1121. Return an iterator breaking down this transform stack from left to
  1122. right recursively. If self == ((A, N), A) then the result will be an
  1123. iterator which yields I : ((A, N), A), followed by A : (N, A),
  1124. followed by (A, N) : (A), but not ((A, N), A) : I.
  1125. This is equivalent to flattening the stack then yielding
  1126. ``flat_stack[:i], flat_stack[i:]`` where i=0..(n-1).
  1127. """
  1128. yield IdentityTransform(), self
  1129. @property
  1130. def depth(self):
  1131. """
  1132. Return the number of transforms which have been chained
  1133. together to form this Transform instance.
  1134. .. note::
  1135. For the special case of a Composite transform, the maximum depth
  1136. of the two is returned.
  1137. """
  1138. return 1
  1139. def contains_branch(self, other):
  1140. """
  1141. Return whether the given transform is a sub-tree of this transform.
  1142. This routine uses transform equality to identify sub-trees, therefore
  1143. in many situations it is object id which will be used.
  1144. For the case where the given transform represents the whole
  1145. of this transform, returns True.
  1146. """
  1147. if self.depth < other.depth:
  1148. return False
  1149. # check that a subtree is equal to other (starting from self)
  1150. for _, sub_tree in self._iter_break_from_left_to_right():
  1151. if sub_tree == other:
  1152. return True
  1153. return False
  1154. def contains_branch_seperately(self, other_transform):
  1155. """
  1156. Return whether the given branch is a sub-tree of this transform on
  1157. each separate dimension.
  1158. A common use for this method is to identify if a transform is a blended
  1159. transform containing an Axes' data transform. e.g.::
  1160. x_isdata, y_isdata = trans.contains_branch_seperately(ax.transData)
  1161. """
  1162. if self.output_dims != 2:
  1163. raise ValueError('contains_branch_seperately only supports '
  1164. 'transforms with 2 output dimensions')
  1165. # for a non-blended transform each separate dimension is the same, so
  1166. # just return the appropriate shape.
  1167. return (self.contains_branch(other_transform), ) * 2
  1168. def __sub__(self, other):
  1169. """
  1170. Compose *self* with the inverse of *other*, cancelling identical terms
  1171. if any::
  1172. # In general:
  1173. A - B == A + B.inverted()
  1174. # (but see note regarding frozen transforms below).
  1175. # If A "ends with" B (i.e. A == A' + B for some A') we can cancel
  1176. # out B:
  1177. (A' + B) - B == A'
  1178. # Likewise, if B "starts with" A (B = A + B'), we can cancel out A:
  1179. A - (A + B') == B'.inverted() == B'^-1
  1180. Cancellation (rather than naively returning ``A + B.inverted()``) is
  1181. important for multiple reasons:
  1182. - It avoids floating-point inaccuracies when computing the inverse of
  1183. B: ``B - B`` is guaranteed to cancel out exactly (resulting in the
  1184. identity transform), whereas ``B + B.inverted()`` may differ by a
  1185. small epsilon.
  1186. - ``B.inverted()`` always returns a frozen transform: if one computes
  1187. ``A + B + B.inverted()`` and later mutates ``B``, then
  1188. ``B.inverted()`` won't be updated and the last two terms won't cancel
  1189. out anymore; on the other hand, ``A + B - B`` will always be equal to
  1190. ``A`` even if ``B`` is mutated.
  1191. """
  1192. # we only know how to do this operation if other is a Transform.
  1193. if not isinstance(other, Transform):
  1194. return NotImplemented
  1195. for remainder, sub_tree in self._iter_break_from_left_to_right():
  1196. if sub_tree == other:
  1197. return remainder
  1198. for remainder, sub_tree in other._iter_break_from_left_to_right():
  1199. if sub_tree == self:
  1200. if not remainder.has_inverse:
  1201. raise ValueError(
  1202. "The shortcut cannot be computed since 'other' "
  1203. "includes a non-invertible component")
  1204. return remainder.inverted()
  1205. # if we have got this far, then there was no shortcut possible
  1206. if other.has_inverse:
  1207. return self + other.inverted()
  1208. else:
  1209. raise ValueError('It is not possible to compute transA - transB '
  1210. 'since transB cannot be inverted and there is no '
  1211. 'shortcut possible.')
  1212. def __array__(self, *args, **kwargs):
  1213. """Array interface to get at this Transform's affine matrix."""
  1214. return self.get_affine().get_matrix()
  1215. def transform(self, values):
  1216. """
  1217. Apply this transformation on the given array of *values*.
  1218. Parameters
  1219. ----------
  1220. values : array-like
  1221. The input values as an array of length :attr:`input_dims` or
  1222. shape (N, :attr:`input_dims`).
  1223. Returns
  1224. -------
  1225. array
  1226. The output values as an array of length :attr:`output_dims` or
  1227. shape (N, :attr:`output_dims`), depending on the input.
  1228. """
  1229. # Ensure that values is a 2d array (but remember whether
  1230. # we started with a 1d or 2d array).
  1231. values = np.asanyarray(values)
  1232. ndim = values.ndim
  1233. values = values.reshape((-1, self.input_dims))
  1234. # Transform the values
  1235. res = self.transform_affine(self.transform_non_affine(values))
  1236. # Convert the result back to the shape of the input values.
  1237. if ndim == 0:
  1238. assert not np.ma.is_masked(res) # just to be on the safe side
  1239. return res[0, 0]
  1240. if ndim == 1:
  1241. return res.reshape(-1)
  1242. elif ndim == 2:
  1243. return res
  1244. raise ValueError(
  1245. "Input values must have shape (N, {dims}) or ({dims},)"
  1246. .format(dims=self.input_dims))
  1247. def transform_affine(self, values):
  1248. """
  1249. Apply only the affine part of this transformation on the
  1250. given array of values.
  1251. ``transform(values)`` is always equivalent to
  1252. ``transform_affine(transform_non_affine(values))``.
  1253. In non-affine transformations, this is generally a no-op. In
  1254. affine transformations, this is equivalent to
  1255. ``transform(values)``.
  1256. Parameters
  1257. ----------
  1258. values : array
  1259. The input values as an array of length :attr:`input_dims` or
  1260. shape (N, :attr:`input_dims`).
  1261. Returns
  1262. -------
  1263. array
  1264. The output values as an array of length :attr:`output_dims` or
  1265. shape (N, :attr:`output_dims`), depending on the input.
  1266. """
  1267. return self.get_affine().transform(values)
  1268. def transform_non_affine(self, values):
  1269. """
  1270. Apply only the non-affine part of this transformation.
  1271. ``transform(values)`` is always equivalent to
  1272. ``transform_affine(transform_non_affine(values))``.
  1273. In non-affine transformations, this is generally equivalent to
  1274. ``transform(values)``. In affine transformations, this is
  1275. always a no-op.
  1276. Parameters
  1277. ----------
  1278. values : array
  1279. The input values as an array of length :attr:`input_dims` or
  1280. shape (N, :attr:`input_dims`).
  1281. Returns
  1282. -------
  1283. array
  1284. The output values as an array of length :attr:`output_dims` or
  1285. shape (N, :attr:`output_dims`), depending on the input.
  1286. """
  1287. return values
  1288. def transform_bbox(self, bbox):
  1289. """
  1290. Transform the given bounding box.
  1291. For smarter transforms including caching (a common requirement in
  1292. Matplotlib), see `TransformedBbox`.
  1293. """
  1294. return Bbox(self.transform(bbox.get_points()))
  1295. def get_affine(self):
  1296. """Get the affine part of this transform."""
  1297. return IdentityTransform()
  1298. def get_matrix(self):
  1299. """Get the matrix for the affine part of this transform."""
  1300. return self.get_affine().get_matrix()
  1301. def transform_point(self, point):
  1302. """
  1303. Return a transformed point.
  1304. This function is only kept for backcompatibility; the more general
  1305. `.transform` method is capable of transforming both a list of points
  1306. and a single point.
  1307. The point is given as a sequence of length :attr:`input_dims`.
  1308. The transformed point is returned as a sequence of length
  1309. :attr:`output_dims`.
  1310. """
  1311. if len(point) != self.input_dims:
  1312. raise ValueError("The length of 'point' must be 'self.input_dims'")
  1313. return self.transform(point)
  1314. def transform_path(self, path):
  1315. """
  1316. Apply the transform to `.Path` *path*, returning a new `.Path`.
  1317. In some cases, this transform may insert curves into the path
  1318. that began as line segments.
  1319. """
  1320. return self.transform_path_affine(self.transform_path_non_affine(path))
  1321. def transform_path_affine(self, path):
  1322. """
  1323. Apply the affine part of this transform to `.Path` *path*, returning a
  1324. new `.Path`.
  1325. ``transform_path(path)`` is equivalent to
  1326. ``transform_path_affine(transform_path_non_affine(values))``.
  1327. """
  1328. return self.get_affine().transform_path_affine(path)
  1329. def transform_path_non_affine(self, path):
  1330. """
  1331. Apply the non-affine part of this transform to `.Path` *path*,
  1332. returning a new `.Path`.
  1333. ``transform_path(path)`` is equivalent to
  1334. ``transform_path_affine(transform_path_non_affine(values))``.
  1335. """
  1336. x = self.transform_non_affine(path.vertices)
  1337. return Path._fast_from_codes_and_verts(x, path.codes, path)
  1338. def transform_angles(self, angles, pts, radians=False, pushoff=1e-5):
  1339. """
  1340. Transform a set of angles anchored at specific locations.
  1341. Parameters
  1342. ----------
  1343. angles : (N,) array-like
  1344. The angles to transform.
  1345. pts : (N, 2) array-like
  1346. The points where the angles are anchored.
  1347. radians : bool, default: False
  1348. Whether *angles* are radians or degrees.
  1349. pushoff : float
  1350. For each point in *pts* and angle in *angles*, the transformed
  1351. angle is computed by transforming a segment of length *pushoff*
  1352. starting at that point and making that angle relative to the
  1353. horizontal axis, and measuring the angle between the horizontal
  1354. axis and the transformed segment.
  1355. Returns
  1356. -------
  1357. (N,) array
  1358. """
  1359. # Must be 2D
  1360. if self.input_dims != 2 or self.output_dims != 2:
  1361. raise NotImplementedError('Only defined in 2D')
  1362. angles = np.asarray(angles)
  1363. pts = np.asarray(pts)
  1364. _api.check_shape((None, 2), pts=pts)
  1365. _api.check_shape((None,), angles=angles)
  1366. if len(angles) != len(pts):
  1367. raise ValueError("There must be as many 'angles' as 'pts'")
  1368. # Convert to radians if desired
  1369. if not radians:
  1370. angles = np.deg2rad(angles)
  1371. # Move a short distance away
  1372. pts2 = pts + pushoff * np.column_stack([np.cos(angles),
  1373. np.sin(angles)])
  1374. # Transform both sets of points
  1375. tpts = self.transform(pts)
  1376. tpts2 = self.transform(pts2)
  1377. # Calculate transformed angles
  1378. d = tpts2 - tpts
  1379. a = np.arctan2(d[:, 1], d[:, 0])
  1380. # Convert back to degrees if desired
  1381. if not radians:
  1382. a = np.rad2deg(a)
  1383. return a
  1384. def inverted(self):
  1385. """
  1386. Return the corresponding inverse transformation.
  1387. It holds ``x == self.inverted().transform(self.transform(x))``.
  1388. The return value of this method should be treated as
  1389. temporary. An update to *self* does not cause a corresponding
  1390. update to its inverted copy.
  1391. """
  1392. raise NotImplementedError()
  1393. class TransformWrapper(Transform):
  1394. """
  1395. A helper class that holds a single child transform and acts
  1396. equivalently to it.
  1397. This is useful if a node of the transform tree must be replaced at
  1398. run time with a transform of a different type. This class allows
  1399. that replacement to correctly trigger invalidation.
  1400. `TransformWrapper` instances must have the same input and output dimensions
  1401. during their entire lifetime, so the child transform may only be replaced
  1402. with another child transform of the same dimensions.
  1403. """
  1404. pass_through = True
  1405. def __init__(self, child):
  1406. """
  1407. *child*: A `Transform` instance. This child may later
  1408. be replaced with :meth:`set`.
  1409. """
  1410. _api.check_isinstance(Transform, child=child)
  1411. super().__init__()
  1412. self.set(child)
  1413. def __eq__(self, other):
  1414. return self._child.__eq__(other)
  1415. __str__ = _make_str_method("_child")
  1416. def frozen(self):
  1417. # docstring inherited
  1418. return self._child.frozen()
  1419. def set(self, child):
  1420. """
  1421. Replace the current child of this transform with another one.
  1422. The new child must have the same number of input and output
  1423. dimensions as the current child.
  1424. """
  1425. if hasattr(self, "_child"): # Absent during init.
  1426. self.invalidate()
  1427. new_dims = (child.input_dims, child.output_dims)
  1428. old_dims = (self._child.input_dims, self._child.output_dims)
  1429. if new_dims != old_dims:
  1430. raise ValueError(
  1431. f"The input and output dims of the new child {new_dims} "
  1432. f"do not match those of current child {old_dims}")
  1433. self._child._parents.pop(id(self), None)
  1434. self._child = child
  1435. self.set_children(child)
  1436. self.transform = child.transform
  1437. self.transform_affine = child.transform_affine
  1438. self.transform_non_affine = child.transform_non_affine
  1439. self.transform_path = child.transform_path
  1440. self.transform_path_affine = child.transform_path_affine
  1441. self.transform_path_non_affine = child.transform_path_non_affine
  1442. self.get_affine = child.get_affine
  1443. self.inverted = child.inverted
  1444. self.get_matrix = child.get_matrix
  1445. # note we do not wrap other properties here since the transform's
  1446. # child can be changed with WrappedTransform.set and so checking
  1447. # is_affine and other such properties may be dangerous.
  1448. self._invalid = 0
  1449. self.invalidate()
  1450. self._invalid = 0
  1451. input_dims = property(lambda self: self._child.input_dims)
  1452. output_dims = property(lambda self: self._child.output_dims)
  1453. is_affine = property(lambda self: self._child.is_affine)
  1454. is_separable = property(lambda self: self._child.is_separable)
  1455. has_inverse = property(lambda self: self._child.has_inverse)
  1456. class AffineBase(Transform):
  1457. """
  1458. The base class of all affine transformations of any number of dimensions.
  1459. """
  1460. is_affine = True
  1461. def __init__(self, *args, **kwargs):
  1462. super().__init__(*args, **kwargs)
  1463. self._inverted = None
  1464. def __array__(self, *args, **kwargs):
  1465. # optimises the access of the transform matrix vs. the superclass
  1466. return self.get_matrix()
  1467. def __eq__(self, other):
  1468. if getattr(other, "is_affine", False) and hasattr(other, "get_matrix"):
  1469. return (self.get_matrix() == other.get_matrix()).all()
  1470. return NotImplemented
  1471. def transform(self, values):
  1472. # docstring inherited
  1473. return self.transform_affine(values)
  1474. def transform_affine(self, values):
  1475. # docstring inherited
  1476. raise NotImplementedError('Affine subclasses should override this '
  1477. 'method.')
  1478. def transform_non_affine(self, values):
  1479. # docstring inherited
  1480. return values
  1481. def transform_path(self, path):
  1482. # docstring inherited
  1483. return self.transform_path_affine(path)
  1484. def transform_path_affine(self, path):
  1485. # docstring inherited
  1486. return Path(self.transform_affine(path.vertices),
  1487. path.codes, path._interpolation_steps)
  1488. def transform_path_non_affine(self, path):
  1489. # docstring inherited
  1490. return path
  1491. def get_affine(self):
  1492. # docstring inherited
  1493. return self
  1494. class Affine2DBase(AffineBase):
  1495. """
  1496. The base class of all 2D affine transformations.
  1497. 2D affine transformations are performed using a 3x3 numpy array::
  1498. a c e
  1499. b d f
  1500. 0 0 1
  1501. This class provides the read-only interface. For a mutable 2D
  1502. affine transformation, use `Affine2D`.
  1503. Subclasses of this class will generally only need to override a
  1504. constructor and `~.Transform.get_matrix` that generates a custom 3x3 matrix.
  1505. """
  1506. input_dims = 2
  1507. output_dims = 2
  1508. def frozen(self):
  1509. # docstring inherited
  1510. return Affine2D(self.get_matrix().copy())
  1511. @property
  1512. def is_separable(self):
  1513. mtx = self.get_matrix()
  1514. return mtx[0, 1] == mtx[1, 0] == 0.0
  1515. def to_values(self):
  1516. """
  1517. Return the values of the matrix as an ``(a, b, c, d, e, f)`` tuple.
  1518. """
  1519. mtx = self.get_matrix()
  1520. return tuple(mtx[:2].swapaxes(0, 1).flat)
  1521. def transform_affine(self, values):
  1522. mtx = self.get_matrix()
  1523. if isinstance(values, np.ma.MaskedArray):
  1524. tpoints = affine_transform(values.data, mtx)
  1525. return np.ma.MaskedArray(tpoints, mask=np.ma.getmask(values))
  1526. return affine_transform(values, mtx)
  1527. if DEBUG:
  1528. _transform_affine = transform_affine
  1529. def transform_affine(self, values):
  1530. # docstring inherited
  1531. # The major speed trap here is just converting to the
  1532. # points to an array in the first place. If we can use
  1533. # more arrays upstream, that should help here.
  1534. if not isinstance(values, np.ndarray):
  1535. _api.warn_external(
  1536. f'A non-numpy array of type {type(values)} was passed in '
  1537. f'for transformation, which results in poor performance.')
  1538. return self._transform_affine(values)
  1539. def inverted(self):
  1540. # docstring inherited
  1541. if self._inverted is None or self._invalid:
  1542. mtx = self.get_matrix()
  1543. shorthand_name = None
  1544. if self._shorthand_name:
  1545. shorthand_name = '(%s)-1' % self._shorthand_name
  1546. self._inverted = Affine2D(inv(mtx), shorthand_name=shorthand_name)
  1547. self._invalid = 0
  1548. return self._inverted
  1549. class Affine2D(Affine2DBase):
  1550. """
  1551. A mutable 2D affine transformation.
  1552. """
  1553. def __init__(self, matrix=None, **kwargs):
  1554. """
  1555. Initialize an Affine transform from a 3x3 numpy float array::
  1556. a c e
  1557. b d f
  1558. 0 0 1
  1559. If *matrix* is None, initialize with the identity transform.
  1560. """
  1561. super().__init__(**kwargs)
  1562. if matrix is None:
  1563. # A bit faster than np.identity(3).
  1564. matrix = IdentityTransform._mtx
  1565. self._mtx = matrix.copy()
  1566. self._invalid = 0
  1567. _base_str = _make_str_method("_mtx")
  1568. def __str__(self):
  1569. return (self._base_str()
  1570. if (self._mtx != np.diag(np.diag(self._mtx))).any()
  1571. else f"Affine2D().scale({self._mtx[0, 0]}, {self._mtx[1, 1]})"
  1572. if self._mtx[0, 0] != self._mtx[1, 1]
  1573. else f"Affine2D().scale({self._mtx[0, 0]})")
  1574. @staticmethod
  1575. def from_values(a, b, c, d, e, f):
  1576. """
  1577. Create a new Affine2D instance from the given values::
  1578. a c e
  1579. b d f
  1580. 0 0 1
  1581. .
  1582. """
  1583. return Affine2D(
  1584. np.array([a, c, e, b, d, f, 0.0, 0.0, 1.0], float).reshape((3, 3)))
  1585. def get_matrix(self):
  1586. """
  1587. Get the underlying transformation matrix as a 3x3 array::
  1588. a c e
  1589. b d f
  1590. 0 0 1
  1591. .
  1592. """
  1593. if self._invalid:
  1594. self._inverted = None
  1595. self._invalid = 0
  1596. return self._mtx
  1597. def set_matrix(self, mtx):
  1598. """
  1599. Set the underlying transformation matrix from a 3x3 array::
  1600. a c e
  1601. b d f
  1602. 0 0 1
  1603. .
  1604. """
  1605. self._mtx = mtx
  1606. self.invalidate()
  1607. def set(self, other):
  1608. """
  1609. Set this transformation from the frozen copy of another
  1610. `Affine2DBase` object.
  1611. """
  1612. _api.check_isinstance(Affine2DBase, other=other)
  1613. self._mtx = other.get_matrix()
  1614. self.invalidate()
  1615. def clear(self):
  1616. """
  1617. Reset the underlying matrix to the identity transform.
  1618. """
  1619. # A bit faster than np.identity(3).
  1620. self._mtx = IdentityTransform._mtx.copy()
  1621. self.invalidate()
  1622. return self
  1623. def rotate(self, theta):
  1624. """
  1625. Add a rotation (in radians) to this transform in place.
  1626. Returns *self*, so this method can easily be chained with more
  1627. calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
  1628. and :meth:`scale`.
  1629. """
  1630. a = math.cos(theta)
  1631. b = math.sin(theta)
  1632. mtx = self._mtx
  1633. # Operating and assigning one scalar at a time is much faster.
  1634. (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist()
  1635. # mtx = [[a -b 0], [b a 0], [0 0 1]] * mtx
  1636. mtx[0, 0] = a * xx - b * yx
  1637. mtx[0, 1] = a * xy - b * yy
  1638. mtx[0, 2] = a * x0 - b * y0
  1639. mtx[1, 0] = b * xx + a * yx
  1640. mtx[1, 1] = b * xy + a * yy
  1641. mtx[1, 2] = b * x0 + a * y0
  1642. self.invalidate()
  1643. return self
  1644. def rotate_deg(self, degrees):
  1645. """
  1646. Add a rotation (in degrees) to this transform in place.
  1647. Returns *self*, so this method can easily be chained with more
  1648. calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
  1649. and :meth:`scale`.
  1650. """
  1651. return self.rotate(math.radians(degrees))
  1652. def rotate_around(self, x, y, theta):
  1653. """
  1654. Add a rotation (in radians) around the point (x, y) in place.
  1655. Returns *self*, so this method can easily be chained with more
  1656. calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
  1657. and :meth:`scale`.
  1658. """
  1659. return self.translate(-x, -y).rotate(theta).translate(x, y)
  1660. def rotate_deg_around(self, x, y, degrees):
  1661. """
  1662. Add a rotation (in degrees) around the point (x, y) in place.
  1663. Returns *self*, so this method can easily be chained with more
  1664. calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
  1665. and :meth:`scale`.
  1666. """
  1667. # Cast to float to avoid wraparound issues with uint8's
  1668. x, y = float(x), float(y)
  1669. return self.translate(-x, -y).rotate_deg(degrees).translate(x, y)
  1670. def translate(self, tx, ty):
  1671. """
  1672. Add a translation in place.
  1673. Returns *self*, so this method can easily be chained with more
  1674. calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
  1675. and :meth:`scale`.
  1676. """
  1677. self._mtx[0, 2] += tx
  1678. self._mtx[1, 2] += ty
  1679. self.invalidate()
  1680. return self
  1681. def scale(self, sx, sy=None):
  1682. """
  1683. Add a scale in place.
  1684. If *sy* is None, the same scale is applied in both the *x*- and
  1685. *y*-directions.
  1686. Returns *self*, so this method can easily be chained with more
  1687. calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
  1688. and :meth:`scale`.
  1689. """
  1690. if sy is None:
  1691. sy = sx
  1692. # explicit element-wise scaling is fastest
  1693. self._mtx[0, 0] *= sx
  1694. self._mtx[0, 1] *= sx
  1695. self._mtx[0, 2] *= sx
  1696. self._mtx[1, 0] *= sy
  1697. self._mtx[1, 1] *= sy
  1698. self._mtx[1, 2] *= sy
  1699. self.invalidate()
  1700. return self
  1701. def skew(self, xShear, yShear):
  1702. """
  1703. Add a skew in place.
  1704. *xShear* and *yShear* are the shear angles along the *x*- and
  1705. *y*-axes, respectively, in radians.
  1706. Returns *self*, so this method can easily be chained with more
  1707. calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
  1708. and :meth:`scale`.
  1709. """
  1710. rx = math.tan(xShear)
  1711. ry = math.tan(yShear)
  1712. mtx = self._mtx
  1713. # Operating and assigning one scalar at a time is much faster.
  1714. (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist()
  1715. # mtx = [[1 rx 0], [ry 1 0], [0 0 1]] * mtx
  1716. mtx[0, 0] += rx * yx
  1717. mtx[0, 1] += rx * yy
  1718. mtx[0, 2] += rx * y0
  1719. mtx[1, 0] += ry * xx
  1720. mtx[1, 1] += ry * xy
  1721. mtx[1, 2] += ry * x0
  1722. self.invalidate()
  1723. return self
  1724. def skew_deg(self, xShear, yShear):
  1725. """
  1726. Add a skew in place.
  1727. *xShear* and *yShear* are the shear angles along the *x*- and
  1728. *y*-axes, respectively, in degrees.
  1729. Returns *self*, so this method can easily be chained with more
  1730. calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
  1731. and :meth:`scale`.
  1732. """
  1733. return self.skew(math.radians(xShear), math.radians(yShear))
  1734. class IdentityTransform(Affine2DBase):
  1735. """
  1736. A special class that does one thing, the identity transform, in a
  1737. fast way.
  1738. """
  1739. _mtx = np.identity(3)
  1740. def frozen(self):
  1741. # docstring inherited
  1742. return self
  1743. __str__ = _make_str_method()
  1744. def get_matrix(self):
  1745. # docstring inherited
  1746. return self._mtx
  1747. def transform(self, values):
  1748. # docstring inherited
  1749. return np.asanyarray(values)
  1750. def transform_affine(self, values):
  1751. # docstring inherited
  1752. return np.asanyarray(values)
  1753. def transform_non_affine(self, values):
  1754. # docstring inherited
  1755. return np.asanyarray(values)
  1756. def transform_path(self, path):
  1757. # docstring inherited
  1758. return path
  1759. def transform_path_affine(self, path):
  1760. # docstring inherited
  1761. return path
  1762. def transform_path_non_affine(self, path):
  1763. # docstring inherited
  1764. return path
  1765. def get_affine(self):
  1766. # docstring inherited
  1767. return self
  1768. def inverted(self):
  1769. # docstring inherited
  1770. return self
  1771. class _BlendedMixin:
  1772. """Common methods for `BlendedGenericTransform` and `BlendedAffine2D`."""
  1773. def __eq__(self, other):
  1774. if isinstance(other, (BlendedAffine2D, BlendedGenericTransform)):
  1775. return (self._x == other._x) and (self._y == other._y)
  1776. elif self._x == self._y:
  1777. return self._x == other
  1778. else:
  1779. return NotImplemented
  1780. def contains_branch_seperately(self, transform):
  1781. return (self._x.contains_branch(transform),
  1782. self._y.contains_branch(transform))
  1783. __str__ = _make_str_method("_x", "_y")
  1784. class BlendedGenericTransform(_BlendedMixin, Transform):
  1785. """
  1786. A "blended" transform uses one transform for the *x*-direction, and
  1787. another transform for the *y*-direction.
  1788. This "generic" version can handle any given child transform in the
  1789. *x*- and *y*-directions.
  1790. """
  1791. input_dims = 2
  1792. output_dims = 2
  1793. is_separable = True
  1794. pass_through = True
  1795. def __init__(self, x_transform, y_transform, **kwargs):
  1796. """
  1797. Create a new "blended" transform using *x_transform* to transform the
  1798. *x*-axis and *y_transform* to transform the *y*-axis.
  1799. You will generally not call this constructor directly but use the
  1800. `blended_transform_factory` function instead, which can determine
  1801. automatically which kind of blended transform to create.
  1802. """
  1803. Transform.__init__(self, **kwargs)
  1804. self._x = x_transform
  1805. self._y = y_transform
  1806. self.set_children(x_transform, y_transform)
  1807. self._affine = None
  1808. @property
  1809. def depth(self):
  1810. return max(self._x.depth, self._y.depth)
  1811. def contains_branch(self, other):
  1812. # A blended transform cannot possibly contain a branch from two
  1813. # different transforms.
  1814. return False
  1815. is_affine = property(lambda self: self._x.is_affine and self._y.is_affine)
  1816. has_inverse = property(
  1817. lambda self: self._x.has_inverse and self._y.has_inverse)
  1818. def frozen(self):
  1819. # docstring inherited
  1820. return blended_transform_factory(self._x.frozen(), self._y.frozen())
  1821. def transform_non_affine(self, values):
  1822. # docstring inherited
  1823. if self._x.is_affine and self._y.is_affine:
  1824. return values
  1825. x = self._x
  1826. y = self._y
  1827. if x == y and x.input_dims == 2:
  1828. return x.transform_non_affine(values)
  1829. if x.input_dims == 2:
  1830. x_points = x.transform_non_affine(values)[:, 0:1]
  1831. else:
  1832. x_points = x.transform_non_affine(values[:, 0])
  1833. x_points = x_points.reshape((len(x_points), 1))
  1834. if y.input_dims == 2:
  1835. y_points = y.transform_non_affine(values)[:, 1:]
  1836. else:
  1837. y_points = y.transform_non_affine(values[:, 1])
  1838. y_points = y_points.reshape((len(y_points), 1))
  1839. if (isinstance(x_points, np.ma.MaskedArray) or
  1840. isinstance(y_points, np.ma.MaskedArray)):
  1841. return np.ma.concatenate((x_points, y_points), 1)
  1842. else:
  1843. return np.concatenate((x_points, y_points), 1)
  1844. def inverted(self):
  1845. # docstring inherited
  1846. return BlendedGenericTransform(self._x.inverted(), self._y.inverted())
  1847. def get_affine(self):
  1848. # docstring inherited
  1849. if self._invalid or self._affine is None:
  1850. if self._x == self._y:
  1851. self._affine = self._x.get_affine()
  1852. else:
  1853. x_mtx = self._x.get_affine().get_matrix()
  1854. y_mtx = self._y.get_affine().get_matrix()
  1855. # We already know the transforms are separable, so we can skip
  1856. # setting b and c to zero.
  1857. mtx = np.array([x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]])
  1858. self._affine = Affine2D(mtx)
  1859. self._invalid = 0
  1860. return self._affine
  1861. class BlendedAffine2D(_BlendedMixin, Affine2DBase):
  1862. """
  1863. A "blended" transform uses one transform for the *x*-direction, and
  1864. another transform for the *y*-direction.
  1865. This version is an optimization for the case where both child
  1866. transforms are of type `Affine2DBase`.
  1867. """
  1868. is_separable = True
  1869. def __init__(self, x_transform, y_transform, **kwargs):
  1870. """
  1871. Create a new "blended" transform using *x_transform* to transform the
  1872. *x*-axis and *y_transform* to transform the *y*-axis.
  1873. Both *x_transform* and *y_transform* must be 2D affine transforms.
  1874. You will generally not call this constructor directly but use the
  1875. `blended_transform_factory` function instead, which can determine
  1876. automatically which kind of blended transform to create.
  1877. """
  1878. is_affine = x_transform.is_affine and y_transform.is_affine
  1879. is_separable = x_transform.is_separable and y_transform.is_separable
  1880. is_correct = is_affine and is_separable
  1881. if not is_correct:
  1882. raise ValueError("Both *x_transform* and *y_transform* must be 2D "
  1883. "affine transforms")
  1884. Transform.__init__(self, **kwargs)
  1885. self._x = x_transform
  1886. self._y = y_transform
  1887. self.set_children(x_transform, y_transform)
  1888. Affine2DBase.__init__(self)
  1889. self._mtx = None
  1890. def get_matrix(self):
  1891. # docstring inherited
  1892. if self._invalid:
  1893. if self._x == self._y:
  1894. self._mtx = self._x.get_matrix()
  1895. else:
  1896. x_mtx = self._x.get_matrix()
  1897. y_mtx = self._y.get_matrix()
  1898. # We already know the transforms are separable, so we can skip
  1899. # setting b and c to zero.
  1900. self._mtx = np.array([x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]])
  1901. self._inverted = None
  1902. self._invalid = 0
  1903. return self._mtx
  1904. def blended_transform_factory(x_transform, y_transform):
  1905. """
  1906. Create a new "blended" transform using *x_transform* to transform
  1907. the *x*-axis and *y_transform* to transform the *y*-axis.
  1908. A faster version of the blended transform is returned for the case
  1909. where both child transforms are affine.
  1910. """
  1911. if (isinstance(x_transform, Affine2DBase) and
  1912. isinstance(y_transform, Affine2DBase)):
  1913. return BlendedAffine2D(x_transform, y_transform)
  1914. return BlendedGenericTransform(x_transform, y_transform)
  1915. class CompositeGenericTransform(Transform):
  1916. """
  1917. A composite transform formed by applying transform *a* then
  1918. transform *b*.
  1919. This "generic" version can handle any two arbitrary
  1920. transformations.
  1921. """
  1922. pass_through = True
  1923. def __init__(self, a, b, **kwargs):
  1924. """
  1925. Create a new composite transform that is the result of
  1926. applying transform *a* then transform *b*.
  1927. You will generally not call this constructor directly but write ``a +
  1928. b`` instead, which will automatically choose the best kind of composite
  1929. transform instance to create.
  1930. """
  1931. if a.output_dims != b.input_dims:
  1932. raise ValueError("The output dimension of 'a' must be equal to "
  1933. "the input dimensions of 'b'")
  1934. self.input_dims = a.input_dims
  1935. self.output_dims = b.output_dims
  1936. super().__init__(**kwargs)
  1937. self._a = a
  1938. self._b = b
  1939. self.set_children(a, b)
  1940. def frozen(self):
  1941. # docstring inherited
  1942. self._invalid = 0
  1943. frozen = composite_transform_factory(
  1944. self._a.frozen(), self._b.frozen())
  1945. if not isinstance(frozen, CompositeGenericTransform):
  1946. return frozen.frozen()
  1947. return frozen
  1948. def _invalidate_internal(self, level, invalidating_node):
  1949. # When the left child is invalidated at AFFINE_ONLY level and the right child is
  1950. # non-affine, the composite transform is FULLY invalidated.
  1951. if invalidating_node is self._a and not self._b.is_affine:
  1952. level = Transform._INVALID_FULL
  1953. super()._invalidate_internal(level, invalidating_node)
  1954. def __eq__(self, other):
  1955. if isinstance(other, (CompositeGenericTransform, CompositeAffine2D)):
  1956. return self is other or (self._a == other._a
  1957. and self._b == other._b)
  1958. else:
  1959. return False
  1960. def _iter_break_from_left_to_right(self):
  1961. for left, right in self._a._iter_break_from_left_to_right():
  1962. yield left, right + self._b
  1963. for left, right in self._b._iter_break_from_left_to_right():
  1964. yield self._a + left, right
  1965. def contains_branch_seperately(self, other_transform):
  1966. # docstring inherited
  1967. if self.output_dims != 2:
  1968. raise ValueError('contains_branch_seperately only supports '
  1969. 'transforms with 2 output dimensions')
  1970. if self == other_transform:
  1971. return (True, True)
  1972. return self._b.contains_branch_seperately(other_transform)
  1973. depth = property(lambda self: self._a.depth + self._b.depth)
  1974. is_affine = property(lambda self: self._a.is_affine and self._b.is_affine)
  1975. is_separable = property(
  1976. lambda self: self._a.is_separable and self._b.is_separable)
  1977. has_inverse = property(
  1978. lambda self: self._a.has_inverse and self._b.has_inverse)
  1979. __str__ = _make_str_method("_a", "_b")
  1980. def transform_affine(self, values):
  1981. # docstring inherited
  1982. return self.get_affine().transform(values)
  1983. def transform_non_affine(self, values):
  1984. # docstring inherited
  1985. if self._a.is_affine and self._b.is_affine:
  1986. return values
  1987. elif not self._a.is_affine and self._b.is_affine:
  1988. return self._a.transform_non_affine(values)
  1989. else:
  1990. return self._b.transform_non_affine(self._a.transform(values))
  1991. def transform_path_non_affine(self, path):
  1992. # docstring inherited
  1993. if self._a.is_affine and self._b.is_affine:
  1994. return path
  1995. elif not self._a.is_affine and self._b.is_affine:
  1996. return self._a.transform_path_non_affine(path)
  1997. else:
  1998. return self._b.transform_path_non_affine(
  1999. self._a.transform_path(path))
  2000. def get_affine(self):
  2001. # docstring inherited
  2002. if not self._b.is_affine:
  2003. return self._b.get_affine()
  2004. else:
  2005. return Affine2D(np.dot(self._b.get_affine().get_matrix(),
  2006. self._a.get_affine().get_matrix()))
  2007. def inverted(self):
  2008. # docstring inherited
  2009. return CompositeGenericTransform(
  2010. self._b.inverted(), self._a.inverted())
  2011. class CompositeAffine2D(Affine2DBase):
  2012. """
  2013. A composite transform formed by applying transform *a* then transform *b*.
  2014. This version is an optimization that handles the case where both *a*
  2015. and *b* are 2D affines.
  2016. """
  2017. def __init__(self, a, b, **kwargs):
  2018. """
  2019. Create a new composite transform that is the result of
  2020. applying `Affine2DBase` *a* then `Affine2DBase` *b*.
  2021. You will generally not call this constructor directly but write ``a +
  2022. b`` instead, which will automatically choose the best kind of composite
  2023. transform instance to create.
  2024. """
  2025. if not a.is_affine or not b.is_affine:
  2026. raise ValueError("'a' and 'b' must be affine transforms")
  2027. if a.output_dims != b.input_dims:
  2028. raise ValueError("The output dimension of 'a' must be equal to "
  2029. "the input dimensions of 'b'")
  2030. self.input_dims = a.input_dims
  2031. self.output_dims = b.output_dims
  2032. super().__init__(**kwargs)
  2033. self._a = a
  2034. self._b = b
  2035. self.set_children(a, b)
  2036. self._mtx = None
  2037. @property
  2038. def depth(self):
  2039. return self._a.depth + self._b.depth
  2040. def _iter_break_from_left_to_right(self):
  2041. for left, right in self._a._iter_break_from_left_to_right():
  2042. yield left, right + self._b
  2043. for left, right in self._b._iter_break_from_left_to_right():
  2044. yield self._a + left, right
  2045. __str__ = _make_str_method("_a", "_b")
  2046. def get_matrix(self):
  2047. # docstring inherited
  2048. if self._invalid:
  2049. self._mtx = np.dot(
  2050. self._b.get_matrix(),
  2051. self._a.get_matrix())
  2052. self._inverted = None
  2053. self._invalid = 0
  2054. return self._mtx
  2055. def composite_transform_factory(a, b):
  2056. """
  2057. Create a new composite transform that is the result of applying
  2058. transform a then transform b.
  2059. Shortcut versions of the blended transform are provided for the
  2060. case where both child transforms are affine, or one or the other
  2061. is the identity transform.
  2062. Composite transforms may also be created using the '+' operator,
  2063. e.g.::
  2064. c = a + b
  2065. """
  2066. # check to see if any of a or b are IdentityTransforms. We use
  2067. # isinstance here to guarantee that the transforms will *always*
  2068. # be IdentityTransforms. Since TransformWrappers are mutable,
  2069. # use of equality here would be wrong.
  2070. if isinstance(a, IdentityTransform):
  2071. return b
  2072. elif isinstance(b, IdentityTransform):
  2073. return a
  2074. elif isinstance(a, Affine2D) and isinstance(b, Affine2D):
  2075. return CompositeAffine2D(a, b)
  2076. return CompositeGenericTransform(a, b)
  2077. class BboxTransform(Affine2DBase):
  2078. """
  2079. `BboxTransform` linearly transforms points from one `Bbox` to another.
  2080. """
  2081. is_separable = True
  2082. def __init__(self, boxin, boxout, **kwargs):
  2083. """
  2084. Create a new `BboxTransform` that linearly transforms
  2085. points from *boxin* to *boxout*.
  2086. """
  2087. _api.check_isinstance(BboxBase, boxin=boxin, boxout=boxout)
  2088. super().__init__(**kwargs)
  2089. self._boxin = boxin
  2090. self._boxout = boxout
  2091. self.set_children(boxin, boxout)
  2092. self._mtx = None
  2093. self._inverted = None
  2094. __str__ = _make_str_method("_boxin", "_boxout")
  2095. def get_matrix(self):
  2096. # docstring inherited
  2097. if self._invalid:
  2098. inl, inb, inw, inh = self._boxin.bounds
  2099. outl, outb, outw, outh = self._boxout.bounds
  2100. x_scale = outw / inw
  2101. y_scale = outh / inh
  2102. if DEBUG and (x_scale == 0 or y_scale == 0):
  2103. raise ValueError(
  2104. "Transforming from or to a singular bounding box")
  2105. self._mtx = np.array([[x_scale, 0.0, -inl*x_scale+outl],
  2106. [ 0.0, y_scale, -inb*y_scale+outb],
  2107. [ 0.0, 0.0, 1.0]],
  2108. float)
  2109. self._inverted = None
  2110. self._invalid = 0
  2111. return self._mtx
  2112. class BboxTransformTo(Affine2DBase):
  2113. """
  2114. `BboxTransformTo` is a transformation that linearly transforms points from
  2115. the unit bounding box to a given `Bbox`.
  2116. """
  2117. is_separable = True
  2118. def __init__(self, boxout, **kwargs):
  2119. """
  2120. Create a new `BboxTransformTo` that linearly transforms
  2121. points from the unit bounding box to *boxout*.
  2122. """
  2123. _api.check_isinstance(BboxBase, boxout=boxout)
  2124. super().__init__(**kwargs)
  2125. self._boxout = boxout
  2126. self.set_children(boxout)
  2127. self._mtx = None
  2128. self._inverted = None
  2129. __str__ = _make_str_method("_boxout")
  2130. def get_matrix(self):
  2131. # docstring inherited
  2132. if self._invalid:
  2133. outl, outb, outw, outh = self._boxout.bounds
  2134. if DEBUG and (outw == 0 or outh == 0):
  2135. raise ValueError("Transforming to a singular bounding box.")
  2136. self._mtx = np.array([[outw, 0.0, outl],
  2137. [ 0.0, outh, outb],
  2138. [ 0.0, 0.0, 1.0]],
  2139. float)
  2140. self._inverted = None
  2141. self._invalid = 0
  2142. return self._mtx
  2143. @_api.deprecated("3.9")
  2144. class BboxTransformToMaxOnly(BboxTransformTo):
  2145. """
  2146. `BboxTransformToMaxOnly` is a transformation that linearly transforms points from
  2147. the unit bounding box to a given `Bbox` with a fixed upper left of (0, 0).
  2148. """
  2149. def get_matrix(self):
  2150. # docstring inherited
  2151. if self._invalid:
  2152. xmax, ymax = self._boxout.max
  2153. if DEBUG and (xmax == 0 or ymax == 0):
  2154. raise ValueError("Transforming to a singular bounding box.")
  2155. self._mtx = np.array([[xmax, 0.0, 0.0],
  2156. [ 0.0, ymax, 0.0],
  2157. [ 0.0, 0.0, 1.0]],
  2158. float)
  2159. self._inverted = None
  2160. self._invalid = 0
  2161. return self._mtx
  2162. class BboxTransformFrom(Affine2DBase):
  2163. """
  2164. `BboxTransformFrom` linearly transforms points from a given `Bbox` to the
  2165. unit bounding box.
  2166. """
  2167. is_separable = True
  2168. def __init__(self, boxin, **kwargs):
  2169. _api.check_isinstance(BboxBase, boxin=boxin)
  2170. super().__init__(**kwargs)
  2171. self._boxin = boxin
  2172. self.set_children(boxin)
  2173. self._mtx = None
  2174. self._inverted = None
  2175. __str__ = _make_str_method("_boxin")
  2176. def get_matrix(self):
  2177. # docstring inherited
  2178. if self._invalid:
  2179. inl, inb, inw, inh = self._boxin.bounds
  2180. if DEBUG and (inw == 0 or inh == 0):
  2181. raise ValueError("Transforming from a singular bounding box.")
  2182. x_scale = 1.0 / inw
  2183. y_scale = 1.0 / inh
  2184. self._mtx = np.array([[x_scale, 0.0, -inl*x_scale],
  2185. [ 0.0, y_scale, -inb*y_scale],
  2186. [ 0.0, 0.0, 1.0]],
  2187. float)
  2188. self._inverted = None
  2189. self._invalid = 0
  2190. return self._mtx
  2191. class ScaledTranslation(Affine2DBase):
  2192. """
  2193. A transformation that translates by *xt* and *yt*, after *xt* and *yt*
  2194. have been transformed by *scale_trans*.
  2195. """
  2196. def __init__(self, xt, yt, scale_trans, **kwargs):
  2197. super().__init__(**kwargs)
  2198. self._t = (xt, yt)
  2199. self._scale_trans = scale_trans
  2200. self.set_children(scale_trans)
  2201. self._mtx = None
  2202. self._inverted = None
  2203. __str__ = _make_str_method("_t")
  2204. def get_matrix(self):
  2205. # docstring inherited
  2206. if self._invalid:
  2207. # A bit faster than np.identity(3).
  2208. self._mtx = IdentityTransform._mtx.copy()
  2209. self._mtx[:2, 2] = self._scale_trans.transform(self._t)
  2210. self._invalid = 0
  2211. self._inverted = None
  2212. return self._mtx
  2213. class _ScaledRotation(Affine2DBase):
  2214. """
  2215. A transformation that applies rotation by *theta*, after transform by *trans_shift*.
  2216. """
  2217. def __init__(self, theta, trans_shift):
  2218. super().__init__()
  2219. self._theta = theta
  2220. self._trans_shift = trans_shift
  2221. self._mtx = None
  2222. def get_matrix(self):
  2223. if self._invalid:
  2224. transformed_coords = self._trans_shift.transform([[self._theta, 0]])[0]
  2225. adjusted_theta = transformed_coords[0]
  2226. rotation = Affine2D().rotate(adjusted_theta)
  2227. self._mtx = rotation.get_matrix()
  2228. return self._mtx
  2229. class AffineDeltaTransform(Affine2DBase):
  2230. r"""
  2231. A transform wrapper for transforming displacements between pairs of points.
  2232. This class is intended to be used to transform displacements ("position
  2233. deltas") between pairs of points (e.g., as the ``offset_transform``
  2234. of `.Collection`\s): given a transform ``t`` such that ``t =
  2235. AffineDeltaTransform(t) + offset``, ``AffineDeltaTransform``
  2236. satisfies ``AffineDeltaTransform(a - b) == AffineDeltaTransform(a) -
  2237. AffineDeltaTransform(b)``.
  2238. This is implemented by forcing the offset components of the transform
  2239. matrix to zero.
  2240. This class is experimental as of 3.3, and the API may change.
  2241. """
  2242. pass_through = True
  2243. def __init__(self, transform, **kwargs):
  2244. super().__init__(**kwargs)
  2245. self._base_transform = transform
  2246. self.set_children(transform)
  2247. __str__ = _make_str_method("_base_transform")
  2248. def get_matrix(self):
  2249. if self._invalid:
  2250. self._mtx = self._base_transform.get_matrix().copy()
  2251. self._mtx[:2, -1] = 0
  2252. return self._mtx
  2253. class TransformedPath(TransformNode):
  2254. """
  2255. A `TransformedPath` caches a non-affine transformed copy of the
  2256. `~.path.Path`. This cached copy is automatically updated when the
  2257. non-affine part of the transform changes.
  2258. .. note::
  2259. Paths are considered immutable by this class. Any update to the
  2260. path's vertices/codes will not trigger a transform recomputation.
  2261. """
  2262. def __init__(self, path, transform):
  2263. """
  2264. Parameters
  2265. ----------
  2266. path : `~.path.Path`
  2267. transform : `Transform`
  2268. """
  2269. _api.check_isinstance(Transform, transform=transform)
  2270. super().__init__()
  2271. self._path = path
  2272. self._transform = transform
  2273. self.set_children(transform)
  2274. self._transformed_path = None
  2275. self._transformed_points = None
  2276. def _revalidate(self):
  2277. # only recompute if the invalidation includes the non_affine part of
  2278. # the transform
  2279. if (self._invalid == self._INVALID_FULL
  2280. or self._transformed_path is None):
  2281. self._transformed_path = \
  2282. self._transform.transform_path_non_affine(self._path)
  2283. self._transformed_points = \
  2284. Path._fast_from_codes_and_verts(
  2285. self._transform.transform_non_affine(self._path.vertices),
  2286. None, self._path)
  2287. self._invalid = 0
  2288. def get_transformed_points_and_affine(self):
  2289. """
  2290. Return a copy of the child path, with the non-affine part of
  2291. the transform already applied, along with the affine part of
  2292. the path necessary to complete the transformation. Unlike
  2293. :meth:`get_transformed_path_and_affine`, no interpolation will
  2294. be performed.
  2295. """
  2296. self._revalidate()
  2297. return self._transformed_points, self.get_affine()
  2298. def get_transformed_path_and_affine(self):
  2299. """
  2300. Return a copy of the child path, with the non-affine part of
  2301. the transform already applied, along with the affine part of
  2302. the path necessary to complete the transformation.
  2303. """
  2304. self._revalidate()
  2305. return self._transformed_path, self.get_affine()
  2306. def get_fully_transformed_path(self):
  2307. """
  2308. Return a fully-transformed copy of the child path.
  2309. """
  2310. self._revalidate()
  2311. return self._transform.transform_path_affine(self._transformed_path)
  2312. def get_affine(self):
  2313. return self._transform.get_affine()
  2314. class TransformedPatchPath(TransformedPath):
  2315. """
  2316. A `TransformedPatchPath` caches a non-affine transformed copy of the
  2317. `~.patches.Patch`. This cached copy is automatically updated when the
  2318. non-affine part of the transform or the patch changes.
  2319. """
  2320. def __init__(self, patch):
  2321. """
  2322. Parameters
  2323. ----------
  2324. patch : `~.patches.Patch`
  2325. """
  2326. # Defer to TransformedPath.__init__.
  2327. super().__init__(patch.get_path(), patch.get_transform())
  2328. self._patch = patch
  2329. def _revalidate(self):
  2330. patch_path = self._patch.get_path()
  2331. # Force invalidation if the patch path changed; otherwise, let base
  2332. # class check invalidation.
  2333. if patch_path != self._path:
  2334. self._path = patch_path
  2335. self._transformed_path = None
  2336. super()._revalidate()
  2337. def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
  2338. """
  2339. Modify the endpoints of a range as needed to avoid singularities.
  2340. Parameters
  2341. ----------
  2342. vmin, vmax : float
  2343. The initial endpoints.
  2344. expander : float, default: 0.001
  2345. Fractional amount by which *vmin* and *vmax* are expanded if
  2346. the original interval is too small, based on *tiny*.
  2347. tiny : float, default: 1e-15
  2348. Threshold for the ratio of the interval to the maximum absolute
  2349. value of its endpoints. If the interval is smaller than
  2350. this, it will be expanded. This value should be around
  2351. 1e-15 or larger; otherwise the interval will be approaching
  2352. the double precision resolution limit.
  2353. increasing : bool, default: True
  2354. If True, swap *vmin*, *vmax* if *vmin* > *vmax*.
  2355. Returns
  2356. -------
  2357. vmin, vmax : float
  2358. Endpoints, expanded and/or swapped if necessary.
  2359. If either input is inf or NaN, or if both inputs are 0 or very
  2360. close to zero, it returns -*expander*, *expander*.
  2361. """
  2362. if (not np.isfinite(vmin)) or (not np.isfinite(vmax)):
  2363. return -expander, expander
  2364. swapped = False
  2365. if vmax < vmin:
  2366. vmin, vmax = vmax, vmin
  2367. swapped = True
  2368. # Expand vmin, vmax to float: if they were integer types, they can wrap
  2369. # around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow.
  2370. vmin, vmax = map(float, [vmin, vmax])
  2371. maxabsvalue = max(abs(vmin), abs(vmax))
  2372. if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
  2373. vmin = -expander
  2374. vmax = expander
  2375. elif vmax - vmin <= maxabsvalue * tiny:
  2376. if vmax == 0 and vmin == 0:
  2377. vmin = -expander
  2378. vmax = expander
  2379. else:
  2380. vmin -= expander*abs(vmin)
  2381. vmax += expander*abs(vmax)
  2382. if swapped and not increasing:
  2383. vmin, vmax = vmax, vmin
  2384. return vmin, vmax
  2385. def interval_contains(interval, val):
  2386. """
  2387. Check, inclusively, whether an interval includes a given value.
  2388. Parameters
  2389. ----------
  2390. interval : (float, float)
  2391. The endpoints of the interval.
  2392. val : float
  2393. Value to check is within interval.
  2394. Returns
  2395. -------
  2396. bool
  2397. Whether *val* is within the *interval*.
  2398. """
  2399. a, b = interval
  2400. if a > b:
  2401. a, b = b, a
  2402. return a <= val <= b
  2403. def _interval_contains_close(interval, val, rtol=1e-10):
  2404. """
  2405. Check, inclusively, whether an interval includes a given value, with the
  2406. interval expanded by a small tolerance to admit floating point errors.
  2407. Parameters
  2408. ----------
  2409. interval : (float, float)
  2410. The endpoints of the interval.
  2411. val : float
  2412. Value to check is within interval.
  2413. rtol : float, default: 1e-10
  2414. Relative tolerance slippage allowed outside of the interval.
  2415. For an interval ``[a, b]``, values
  2416. ``a - rtol * (b - a) <= val <= b + rtol * (b - a)`` are considered
  2417. inside the interval.
  2418. Returns
  2419. -------
  2420. bool
  2421. Whether *val* is within the *interval* (with tolerance).
  2422. """
  2423. a, b = interval
  2424. if a > b:
  2425. a, b = b, a
  2426. rtol = (b - a) * rtol
  2427. return a - rtol <= val <= b + rtol
  2428. def interval_contains_open(interval, val):
  2429. """
  2430. Check, excluding endpoints, whether an interval includes a given value.
  2431. Parameters
  2432. ----------
  2433. interval : (float, float)
  2434. The endpoints of the interval.
  2435. val : float
  2436. Value to check is within interval.
  2437. Returns
  2438. -------
  2439. bool
  2440. Whether *val* is within the *interval*.
  2441. """
  2442. a, b = interval
  2443. return a < val < b or a > val > b
  2444. def offset_copy(trans, fig=None, x=0.0, y=0.0, units='inches'):
  2445. """
  2446. Return a new transform with an added offset.
  2447. Parameters
  2448. ----------
  2449. trans : `Transform` subclass
  2450. Any transform, to which offset will be applied.
  2451. fig : `~matplotlib.figure.Figure`, default: None
  2452. Current figure. It can be None if *units* are 'dots'.
  2453. x, y : float, default: 0.0
  2454. The offset to apply.
  2455. units : {'inches', 'points', 'dots'}, default: 'inches'
  2456. Units of the offset.
  2457. Returns
  2458. -------
  2459. `Transform` subclass
  2460. Transform with applied offset.
  2461. """
  2462. _api.check_in_list(['dots', 'points', 'inches'], units=units)
  2463. if units == 'dots':
  2464. return trans + Affine2D().translate(x, y)
  2465. if fig is None:
  2466. raise ValueError('For units of inches or points a fig kwarg is needed')
  2467. if units == 'points':
  2468. x /= 72.0
  2469. y /= 72.0
  2470. # Default units are 'inches'
  2471. return trans + ScaledTranslation(x, y, fig.dpi_scale_trans)