forked from matplotlib/matplotlib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransforms.py
More file actions
2059 lines (1686 loc) · 63.9 KB
/
transforms.py
File metadata and controls
2059 lines (1686 loc) · 63.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This module contains a framework for arbitrary transformations.
Transforms are composed into a 'transform tree', made of transforms
whose value depends on other transforms (their children). When the
contents of children change, their parents are automatically updated
to reflect those changes. To do this an "invalidation" method is
used: when children change, all of their ancestors are marked as
"invalid". When the value of a transform is accessed at a later time,
its value is recomputed only if it is invalid, otherwise a cached
value may be used. This prevents unnecessary recomputations of
transforms, and contributes to better interactive performance.
The framework can be used for both affine and non-affine
transformations. However, for speed, we want use the backend
renderers to perform affine transformations whenever possible.
Therefore, it is possible to perform just the affine or non-affine
part of a transformation on a set of data. The affine is always
assumed to occur after the non-affine. For any transform:
full transform == non-affine + affine
2007 Michael Droettboom
"""
import numpy as npy
from matplotlib.numerix import npyma as ma
from matplotlib._path import affine_transform
from numpy.linalg import inv
from weakref import WeakKeyDictionary
import warnings
import cbook
from path import Path
from _path import count_bboxes_overlapping_bbox, update_path_extents
DEBUG = False
if DEBUG:
import warnings
MaskedArray = ma.MaskedArray
class TransformNode(object):
"""
TransformNode is the base class for anything that participates in
the transform tree and needs to invalidate its parents or be
invalidated. It can include classes that are not technically
transforms, such as bounding boxes, since some transforms depend
on bounding boxes to compute their values.
"""
_gid = 0
# Invalidation may affect only the affine part. If the
# invalidation was "affine-only", the _invalid member is set to
# INVALID_AFFINE_ONLY
INVALID_NON_AFFINE = 1
INVALID_AFFINE = 2
INVALID = INVALID_NON_AFFINE | INVALID_AFFINE
# Some metadata about the transform, used to determine whether an
# invalidation is affine-only
is_affine = False
is_bbox = False
# If pass_through is True, all ancestors will always be
# invalidated, even if 'self' is already invalid.
pass_through = False
def __init__(self):
"""
Creates a new TransformNode.
"""
# Parents are stored in a WeakKeyDictionary, so that if the
# parents are deleted, references from the children won't keep
# them alive.
self._parents = WeakKeyDictionary()
# TransformNodes start out as invalid until their values are
# computed for the first time.
self._invalid = 1
def __copy__(self, *args):
raise NotImplementedError(
"TransformNode instances can not be copied. " +
"Consider using frozen() instead.")
__deepcopy__ = __copy__
def invalidate(self):
"""
Invalidate this transform node and all of its parents. Should
be called anytime the transform changes.
"""
# If we are an affine transform being changed, we can set the
# flag to INVALID_AFFINE_ONLY
value = ((self.is_affine or self.is_bbox)
and self.INVALID_AFFINE
or self.INVALID)
# Shortcut: If self is already invalid, that means its parents
# are as well, so we don't need to do anything.
if self._invalid == value or not len(self._parents):
return
# Invalidate all ancestors of self using pseudo-recursion.
parent = None
stack = [self]
while len(stack):
root = stack.pop()
# Stop at subtrees that have already been invalidated
if root._invalid == 0 or root.pass_through:
root._invalid = value
stack.extend(root._parents.keys())
def set_children(self, *children):
"""
Set the children of the transform. Should be called from the
constructor of any transforms that depend on other transforms.
"""
for child in children:
child._parents[self] = None
if DEBUG:
_set_children = set_children
def set_children(self, *children):
self._set_children(*children)
self._children = children
def frozen(self):
"""
Returns a frozen copy of this transform node. The frozen copy
will not update when its children change. Useful for storing
a previously known state of a transform where copy.deepcopy()
might normally be used.
"""
return self
if DEBUG:
def write_graphviz(self, fobj, highlight=[]):
"""
For debugging purposes.
Writes the transform tree rooted at 'self' to a graphviz "dot"
format file. This file can be run through the "dot" utility
to produce a graph of the transform tree.
Affine transforms are marked in blue. Bounding boxes are
marked in yellow.
fobj: A Python file-like object
"""
seen = cbook.set()
def recurse(root):
if root in seen:
return
seen.add(root)
props = {}
label = root.__class__.__name__
if root._invalid:
label = '[%s]' % label
if root in highlight:
props['style'] = 'bold'
if root.is_affine:
props['shape'] = 'parallelogram'
if root.is_bbox:
props['shape'] = 'box'
props['label'] = '"%s"' % label
props = ' '.join(['%s=%s' % (key, val) for key, val in props.items()])
fobj.write('%s [%s];\n' %
(hash(root), props))
if hasattr(root, '_children'):
for child in root._children:
name = '?'
for key, val in root.__dict__.items():
if val is child:
name = key
break
fobj.write('%s -> %s [label="%s", fontsize=10];\n' % (
hash(root),
hash(child),
name))
recurse(child)
fobj.write("digraph G {\n")
recurse(self)
fobj.write("}\n")
else:
def write_graphviz(self, fobj, highlight=[]):
return
class BboxBase(TransformNode):
"""
This is the base class of all bounding boxes, and provides
read-only access to its data.
"""
is_bbox = True
#* Redundant: Removed for performance
#
# def __init__(self):
# TransformNode.__init__(self)
if DEBUG:
def _check(points):
if ma.isMaskedArray(points):
warnings.warn("Bbox bounds are a masked array.")
if (points[1,0] - points[0,0] == 0 or
points[1,1] - points[0,1] == 0):
warnings.warn("Singular Bbox.")
_check = staticmethod(_check)
def frozen(self):
return Bbox(self.get_points().copy())
frozen.__doc__ = TransformNode.__doc__
def __array__(self, *args, **kwargs):
return self.get_points()
def is_unit(self):
return list(self.get_points().flatten()) == [0., 0., 1., 1.]
def _get_x0(self):
return self.get_points()[0, 0]
x0 = property(_get_x0)
def _get_y0(self):
return self.get_points()[0, 1]
y0 = property(_get_y0)
def _get_x1(self):
return self.get_points()[1, 0]
x1 = property(_get_x1)
def _get_y1(self):
return self.get_points()[1, 1]
y1 = property(_get_y1)
def _get_p0(self):
return self.get_points()[0]
p0 = property(_get_p0)
def _get_p1(self):
return self.get_points()[1]
p1 = property(_get_p1)
def _get_xmin(self):
return min(self.get_points()[:, 0])
xmin = property(_get_xmin)
def _get_ymin(self):
return min(self.get_points()[:, 1])
ymin = property(_get_ymin)
def _get_xmax(self):
return max(self.get_points()[:, 0])
xmax = property(_get_xmax)
def _get_ymax(self):
return max(self.get_points()[:, 1])
ymax = property(_get_ymax)
def _get_min(self):
return [min(self.get_points()[:, 0]),
min(self.get_points()[:, 1])]
min = property(_get_min)
def _get_max(self):
return [max(self.get_points()[:, 0]),
max(self.get_points()[:, 1])]
max = property(_get_max)
def _get_intervalx(self):
return self.get_points()[:, 0]
intervalx = property(_get_intervalx)
def _get_intervaly(self):
return self.get_points()[:, 1]
intervaly = property(_get_intervaly)
def _get_width(self):
points = self.get_points()
return points[1, 0] - points[0, 0]
width = property(_get_width)
def _get_height(self):
points = self.get_points()
return points[1, 1] - points[0, 1]
height = property(_get_height)
def _get_size(self):
points = self.get_points()
return points[1] - points[0]
size = property(_get_size)
def _get_bounds(self):
x0, y0, x1, y1 = self.get_points().flatten()
return (x0, y0, x1 - x0, y1 - y0)
bounds = property(_get_bounds)
def _get_extents(self):
return self.get_points().flatten().copy()
extents = property(_get_extents)
def get_points(self):
return NotImplementedError()
def containsx(self, x):
x0, x1 = self.intervalx
return ((x0 < x1
and (x >= x0 and x <= x1))
or (x >= x1 and x <= x0))
def containsy(self, y):
y0, y1 = self.intervaly
return ((y0 < y1
and (y >= y0 and y <= y1))
or (y >= y1 and y <= y0))
def contains(self, x, y):
return self.containsx(x) and self.containsy(y)
def overlaps(self, other):
ax1, ay1, ax2, ay2 = self._get_extents()
bx1, by1, bx2, by2 = other._get_extents()
if ax2 < ax1:
ax2, ax1 = ax1, ax2
if ay2 < ay1:
ay2, ay1 = ay1, ay2
if bx2 < bx1:
bx2, bx1 = bx1, bx2
if by2 < by1:
by2, by1 = by1, by2
return not ((bx2 < ax1) or
(by2 < ay1) or
(bx1 > ax2) or
(by1 > ay2))
def fully_containsx(self, x):
x0, x1 = self.intervalx
return ((x0 < x1
and (x > x0 and x < x1))
or (x > x1 and x < x0))
def fully_containsy(self, y):
y0, y1 = self.intervaly
return ((y0 < y1
and (x > y0 and x < y1))
or (x > y1 and x < y0))
def fully_contains(self, x, y):
return self.fully_containsx(x) \
and self.fully_containsy(y)
def fully_overlaps(self, other):
ax1, ay1, ax2, ay2 = self._get_extents()
bx1, by1, bx2, by2 = other._get_extents()
if ax2 < ax1:
ax2, ax1 = ax1, ax2
if ay2 < ay1:
ay2, ay1 = ay1, ay2
if bx2 < bx1:
bx2, bx1 = bx1, bx2
if by2 < by1:
by2, by1 = by1, by2
return not ((bx2 <= ax1) or
(by2 <= ay1) or
(bx1 >= ax2) or
(by1 >= ay2))
def transformed(self, transform):
"""
Return a new Bbox object, transformed by the given transform.
"""
return Bbox(transform.transform(self.get_points()))
def inverse_transformed(self, transform):
"""
Return a new Bbox object, transformed by the inverse of the
given transform.
"""
return Bbox(transform.inverted().transform(self.get_points()))
coefs = {'C': (0.5, 0.5),
'SW': (0,0),
'S': (0.5, 0),
'SE': (1.0, 0),
'E': (1.0, 0.5),
'NE': (1.0, 1.0),
'N': (0.5, 1.0),
'NW': (0, 1.0),
'W': (0, 0.5)}
def anchored(self, c, container = None):
"""
Return a copy of the Bbox, shifted to position c within a
container.
c: may be either a) a sequence (cx, cy) where cx, cy range
from 0 to 1, where 0 is left or bottom and 1 is right or top;
or b) a string: C for centered, S for bottom-center, SE for
bottom-left, E for left, etc.
Optional arg container is the box within which the BBox
is positioned; it defaults to the initial BBox.
"""
if container is None:
container = self
l, b, w, h = container.bounds
if isinstance(c, str):
cx, cy = self.coefs[c]
else:
cx, cy = c
L, B, W, H = self.bounds
return Bbox(self._points +
[(l + cx * (w-W)) - L,
(b + cy * (h-H)) - B])
def shrunk(self, mx, my):
"""
Return a copy of the Bbox, shurnk by the factor mx in the x
direction and the factor my in the y direction. The lower
left corner of the box remains unchanged. Normally mx and my
will be <= 1, but this is not enforced.
"""
w, h = self.size
return Bbox([self._points[0],
self._points[0] + [mx * w, my * h]])
def shrunk_to_aspect(self, box_aspect, container = None, fig_aspect = 1.0):
"""
Return a copy of the Bbox, shrunk so that it is as large as it
can be while having the desired aspect ratio, box_aspect. If
the box coordinates are relative--that is, fractions of a
larger box such as a figure--then the physical aspect ratio of
that figure is specified with fig_aspect, so that box_aspect
can also be given as a ratio of the absolute dimensions, not
the relative dimensions.
"""
assert box_aspect > 0 and fig_aspect > 0
if container is None:
container = self
w, h = container.size
H = w * box_aspect/fig_aspect
if H <= h:
W = w
else:
W = h * fig_aspect/box_aspect
H = h
return Bbox([self._points[0],
self._points[0] + (W, H)])
def splitx(self, *args):
"""
e.g., bbox.splitx(f1, f2, ...)
Returns a list of new BBoxes formed by
splitting the original one with vertical lines
at fractional positions f1, f2, ...
"""
boxes = []
xf = [0] + list(args) + [1]
x0, y0, x1, y1 = self._get_extents()
w = x1 - x0
for xf0, xf1 in zip(xf[:-1], xf[1:]):
boxes.append(Bbox([[x0 + xf0 * w, y0], [x0 + xf1 * w, y1]]))
return boxes
def splity(self, *args):
"""
e.g., bbox.splitx(f1, f2, ...)
Returns a list of new PBoxes formed by
splitting the original one with horizontal lines
at fractional positions f1, f2, ...
"""
boxes = []
yf = [0] + list(args) + [1]
x0, y0, x1, y1 = self._get_extents()
h = y1 - y0
for yf0, yf1 in zip(yf[:-1], yf[1:]):
boxes.append(Bbox([[x0, y0 + yf0 * h], [x1, y0 + yf1 * h]]))
return boxes
def count_contains(self, vertices):
"""
Count the number of vertices contained in the Bbox.
vertices is a Nx2 numpy array.
"""
if len(vertices) == 0:
return 0
vertices = npy.asarray(vertices)
x0, y0, x1, y1 = self._get_extents()
dx0 = npy.sign(vertices[:, 0] - x0)
dy0 = npy.sign(vertices[:, 1] - y0)
dx1 = npy.sign(vertices[:, 0] - x1)
dy1 = npy.sign(vertices[:, 1] - y1)
inside = (abs(dx0 + dx1) + abs(dy0 + dy1)) <= 2
return N.sum(inside)
def count_overlaps(self, bboxes):
"""
Count the number of bounding boxes that overlap this one.
bboxes is a sequence of Bbox objects
"""
return count_bboxes_overlapping_bbox(self, bboxes)
def expanded(self, sw, sh):
"""
Return a new Bbox which is this Bbox expanded around its
center by the given factors sw and sh.
"""
width = self.width
height = self.height
deltaw = (sw * width - width) / 2.0
deltah = (sh * height - height) / 2.0
a = npy.array([[-deltaw, -deltah], [deltaw, deltah]])
return Bbox(self._points + a)
def padded(self, p):
"""
Return a new Bbox that is padded on all four sides by the
given value.
"""
points = self._points
return Bbox(points + [[-p, -p], [p, p]])
def translated(self, tx, ty):
"""
Return a copy of the Bbox, translated by tx and ty.
"""
return Bbox(self._points + (tx, ty))
def corners(self):
"""
Return an array of points which are the four corners of this
rectangle.
"""
l, b, r, t = self.get_points().flatten()
return npy.array([[l, b], [l, t], [r, b], [r, t]])
def rotated(self, radians):
"""
Return a new bounding box that bounds a rotated version of this
bounding box. The new bounding box is still aligned with the
axes, of course.
"""
corners = self.corners()
corners_rotated = Affine2D().rotate(radians).transform(corners)
bbox = Bbox.unit()
bbox.update_from_data_xy(corners_rotated, ignore=True)
return bbox
#@staticmethod
def union(bboxes):
"""
Return a Bbox that contains all of the given bboxes.
"""
assert(len(bboxes))
if len(bboxes) == 1:
return bboxes[0]
x0 = npy.inf
y0 = npy.inf
x1 = -npy.inf
y1 = -npy.inf
for bbox in bboxes:
points = bbox.get_points()
xs = points[:, 0]
ys = points[:, 1]
x0 = min(x0, npy.min(xs))
y0 = min(y0, npy.min(ys))
x1 = max(x1, npy.max(xs))
y1 = max(y1, npy.max(ys))
return Bbox.from_extents(x0, y0, x1, y1)
union = staticmethod(union)
class Bbox(BboxBase):
def __init__(self, points):
"""
Create a new bounding box.
points: a 2x2 numpy array of the form [[x0, y0], [x1, y1]]
If you need to create Bbox from another form of data, consider the
class methods unit, from_bounds and from_extents.
"""
BboxBase.__init__(self)
self._points = npy.asarray(points, npy.float_)
self._minpos = npy.array([0.0000001, 0.0000001])
self._ignore = True
if DEBUG:
___init__ = __init__
def __init__(self, points):
self._check(points)
self.___init__(points)
def invalidate(self):
self._check(self._points)
TransformNode.invalidate(self)
_unit_values = npy.array([[0.0, 0.0], [1.0, 1.0]], npy.float_)
#@staticmethod
def unit():
"""
Create a new unit BBox from (0, 0) to (1, 1).
"""
return Bbox(Bbox._unit_values.copy())
unit = staticmethod(unit)
#@staticmethod
def from_bounds(x0, y0, width, height):
"""
Create a new Bbox from x0, y0, width and height.
width and height may be negative.
"""
return Bbox.from_extents(x0, y0, x0 + width, y0 + height)
from_bounds = staticmethod(from_bounds)
#@staticmethod
def from_extents(*args):
"""
Create a new Bbox from left, bottom, right and top.
The y-axis increases upwards.
"""
points = npy.array(args, dtype=npy.float_).reshape(2, 2)
return Bbox(points)
from_extents = staticmethod(from_extents)
def __repr__(self):
return 'Bbox(%s)' % repr(self._points)
__str__ = __repr__
def ignore(self, value):
"""
Set whether the existing bounds of the box should be ignored
by subsequent calls to update_from_data or
update_from_data_xy.
value: When True, subsequent calls to update_from_data will
ignore the existing bounds of the Bbox.
When False, subsequent calls to update_from_data will
include the existing bounds of the Bbox.
"""
self._ignore = value
def update_from_data(self, x, y, ignore=None):
"""
Update the bounds of the Bbox based on the passed in data.
x: a numpy array of x-values
y: a numpy array of y-values
ignore:
when True, ignore the existing bounds of the Bbox.
when False, include the existing bounds of the Bbox.
when None, use the last value passed to Bbox.ignore().
"""
warnings.warn("update_from_data requires a memory copy -- please replace with update_from_data_xy")
xy = npy.hstack((x.reshape((len(x), 1)), y.reshape((len(y), 1))))
return self.update_from_data_xy(xy, ignore)
def update_from_data_xy(self, xy, ignore=None):
"""
Update the bounds of the Bbox based on the passed in data.
xy: a numpy array of 2D points
ignore:
when True, ignore the existing bounds of the Bbox.
when False, include the existing bounds of the Bbox.
when None, use the last value passed to Bbox.ignore().
"""
if ignore is None:
ignore = self._ignore
if len(xy) == 0:
return
points, minpos, changed = update_path_extents(
Path(xy), None, self._points, self._minpos, ignore)
if changed:
self._points = points
self._minpos = minpos
self.invalidate()
def _set_x0(self, val):
self._points[0, 0] = val
self.invalidate()
x0 = property(BboxBase._get_x0, _set_x0)
def _set_y0(self, val):
self._points[0, 1] = val
self.invalidate()
y0 = property(BboxBase._get_y0, _set_y0)
def _set_x1(self, val):
self._points[1, 0] = val
self.invalidate()
x1 = property(BboxBase._get_x1, _set_x1)
def _set_y1(self, val):
self._points[1, 1] = val
self.invalidate()
y1 = property(BboxBase._get_y1, _set_y1)
def _set_p0(self, val):
self._points[0] = val
self.invalidate()
p0 = property(BboxBase._get_p0, _set_p0)
def _set_p1(self, val):
self._points[1] = val
self.invalidate()
p1 = property(BboxBase._get_p1, _set_p1)
def _set_intervalx(self, interval):
self._points[:, 0] = interval
self.invalidate()
intervalx = property(BboxBase._get_intervalx, _set_intervalx)
def _set_intervaly(self, interval):
self._points[:, 1] = interval
self.invalidate()
intervaly = property(BboxBase._get_intervaly, _set_intervaly)
def _set_bounds(self, bounds):
l, b, w, h = bounds
points = npy.array([[l, b], [l+w, b+h]], npy.float_)
if npy.any(self._points != points):
self._points = points
self.invalidate()
bounds = property(BboxBase._get_bounds, _set_bounds)
def _get_minpos(self):
return self._minpos
minpos = property(_get_minpos)
def _get_minposx(self):
return self._minpos[0]
minposx = property(_get_minposx)
def _get_minposy(self):
return self._minpos[1]
minposy = property(_get_minposy)
def get_points(self):
"""
Set the points of the bounding box directly as a numpy array
of the form: [[x0, y0], [x1, y1]].
"""
self._invalid = 0
return self._points
def set_points(self, points):
"""
Set the points of the bounding box directly from a numpy array
of the form: [[x0, y0], [x1, y1]]. No error checking
is performed, as this method is mainly for internal use.
"""
if npy.any(self._points != points):
self._points = points
self.invalidate()
def set(self, other):
"""
Set this bounding box from the "frozen" bounds of another Bbox.
"""
if npy.any(self._points != other.get_points()):
self._points = other.get_points()
self.invalidate()
class TransformedBbox(BboxBase):
"""
A Bbox that is automatically transformed by a given Transform. When
either the child bbox or transform changes, the bounds of this bbox
will update accordingly.
"""
def __init__(self, bbox, transform):
"""
bbox: a child bbox
transform: a 2D transform
"""
assert bbox.is_bbox
assert isinstance(transform, Transform)
assert transform.input_dims == 2
assert transform.output_dims == 2
BboxBase.__init__(self)
self._bbox = bbox
self._transform = transform
self.set_children(bbox, transform)
self._points = None
def __repr__(self):
return "TransformedBbox(%s, %s)" % (self._bbox, self._transform)
__str__ = __repr__
def get_points(self):
if self._invalid:
points = self._transform.transform(self._bbox.get_points())
if ma.isMaskedArray(points):
points.putmask(0.0)
points = npy.asarray(points)
self._points = points
self._invalid = 0
return self._points
if DEBUG:
_get_points = get_points
def get_points(self):
points = self._get_points()
self._check(points)
return points
class Transform(TransformNode):
"""
The base class of all TransformNodes that actually perform a
transformation.
All non-affine transformations should be subclass this class. New
affine transformations should subclass Affine2D.
Subclasses of this class should override the following members (at
minimum):
input_dims
output_dims
transform
is_separable
has_inverse
inverted (if has_inverse will return True)
If the transform needs to do something non-standard with Paths,
such as adding curves where there were once line segments, it
should override:
transform_path
"""
# The number of input and output dimensions for this transform.
# These must be overridden (with integers) in the subclass.
input_dims = None
output_dims = None
# True if this transform as a corresponding inverse transform.
has_inverse = False
# True if this transform is separable in the x- and y- dimensions.
is_separable = False
#* Redundant: Removed for performance
#
# def __init__(self):
# TransformNode.__init__(self)
def __add__(self, other):
"""
Composes two transforms together such that self is followed by other.
"""
if isinstance(other, Transform):
return composite_transform_factory(self, other)
raise TypeError(
"Can not add Transform to object of type '%s'" % type(other))
def __radd__(self, other):
if isinstance(other, Transform):
return composite_transform_factory(other, self)
raise TypeError(
"Can not add Transform to object of type '%s'" % type(other))
def __array__(self, *args, **kwargs):
"""
Used by C/C++ -based backends to get at the array matrix data.
"""
return self.frozen().__array__()
def transform(self, values):
"""
Performs the transformation on the given array of values.
Accepts a numpy array of shape (N x self.input_dims) and
returns a numpy array of shape (N x self.output_dims).
"""
raise NotImplementedError()
def transform_affine(self, values):
"""
Performs only the affine part of this transformation on the
given array of values.
transform(values) is equivalent to
transform_affine(transform_non_affine(values)).
In non-affine transformations, this is generally a no-op. In
affine transformations, this is equivalent to
transform(values).
Accepts a numpy array of shape (N x self.input_dims) and
returns a numpy array of shape (N x self.output_dims).
"""
return values
def transform_non_affine(self, values):
"""
Performs only the non-affine part of the transformation.
transform(values) is equivalent to
transform_affine(transform_non_affine(values)).
In non-affine transformations, this is generally equivalent to
transform(values). In affine transformations, this is a
no-op.
Accepts a numpy array of shape (N x self.input_dims) and
returns a numpy array of shape (N x self.output_dims).
"""
return self.transform(points)
def get_affine(self):
"""
Get the affine part of this transform.
"""
return IdentityTransform()
def transform_point(self, point):
"""
A convenience function that returns the transformed copy of a
single point.
The point is given as a sequence of length self.input_dims.
The transformed point is returned as a sequence of length
self.output_dims.
"""
assert len(point) == 2
return self.transform(npy.asarray([point]))[0]
def transform_path(self, path):
"""
Returns a transformed copy of path.
path: a Path instance.
In some cases, this transform may insert curves into the path
that began as line segments.
"""
return Path(self.transform(path.vertices), path.codes)
def transform_path_affine(self, path):
"""
Returns a copy of path, transformed only by the affine part of
this transform.
path: a Path instance
transform_path(path) is equivalent to
transform_path_affine(transform_path_non_affine(values)).
"""
return path
def transform_path_non_affine(self, path):
"""
Returns a copy of path, transformed only by the non-affine
part of this transform.
path: a Path instance
transform_path(path) is equivalent to
transform_path_affine(transform_path_non_affine(values)).
"""
return Path(self.transform_non_affine(path.vertices), path.codes)
def inverted(self):
"""
Return the corresponding inverse transformation.
The return value of this method should be treated as
temporary. An update to 'self' does not cause a corresponding
update to its inverted copy.
x === self.inverted().transform(self.transform(x))
"""
raise NotImplementedError()
class TransformWrapper(Transform):