transforms.py 95 KB

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