transforms.py 95 KB

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