-
-
Notifications
You must be signed in to change notification settings - Fork 8.3k
Expand file tree
/
Copy pathmpl1.py
More file actions
1468 lines (1087 loc) · 42.8 KB
/
mpl1.py
File metadata and controls
1468 lines (1087 loc) · 42.8 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
"""
Install instructions for traits 2.0
# blow away old enthought
rm -rf ~/dev/lib/python2.4/site-packages/enthought.*
# get easy_install, if necessary
wget http://peak.telecommunity.com/dist/ez_setup.py
sudo python sez_setup.py
sudo rm -rf /usr/local/lib/python2.5/site-packages/enthought*
sudo easy_install \
-f http://code.enthought.com/enstaller/eggs/source/unstable \
"enthought.resource <3.0a" "enthought.traits < 3.0a"
"""
# see install instructions for enthrought traits2 in mtraits
import enthought.traits.api as traits
from enthought.traits.api import HasTraits, Instance, Trait, Float, Int, \
Array, Tuple
from enthought.traits.trait_numeric import TraitArray
from matplotlib import agg
from matplotlib import colors as mcolors
from matplotlib import cbook
import numpy as npy
is_string_like = cbook.is_string_like
## begin core infrastructure
class Affine(HasTraits):
"""
An affine 3x3 matrix that supports matrix multiplication with
other Affine instances or numpy arrays.
a = Affine()
a.translate = 10,20
a.scale = 20, 40
Be careful not to do *inplace* operations on the array components
or the update callbacks will not be triggered, eg DO NOT
a.translate += 10, 20
rather DO
a.translate_delta(10, 20)
Multiplication works as expected:
a1 = Affine()
a1.scale = 10, 20
a2 = Affine()
a2.scale = 4, 5
print a1*a2
x = numpy.random(3, 10)
print a1*x
All of the translate, scale, xlim, ylim and vec6 properties are
simply views into the data matrix, and are updated by reference
"""
# connect to the data_modified event if you want a callback
data = Array('d', (3,3))
translate = traits.Property(Array('d', (2,)))
scale = traits.Property(Array('d', (2,)))
vec6 = traits.Property(Array('d', (6,)))
xlim = traits.Property(Array('d', (2,)))
ylim = traits.Property(Array('d', (2,)))
#data_modified = traits.Event
def _data_default(self):
return npy.array([[1,0,0],[0,1,0],[0,0,1]], npy.float_)
def _get_xlim(self):
sx, b, tx = self.data[0]
return self._get_lim(sx, tx)
def _set_xlim(self, xlim):
xmin, xmax = xlim
oldsx, oldb, oldtx = self.data[0]
sx = 1./(xmax-xmin)
tx = -xmin*sx
forward = oldsx!=sx or oldtx!=tx
if forward:
old = self.data.copy()
self.data[0][0] = sx
self.data[0][-1] = tx
self._data_changed(old, self.data)
def _get_ylim(self):
c, sy, ty = self.data[1]
return self._get_lim(sy, ty)
def _set_ylim(self, ylim):
ymin, ymax = ylim
oldc, oldsy, oldty = self.data[1]
sy = 1./(ymax-ymin)
ty = -ymin*sy
forward = oldsy!=sy or oldty!=ty
if forward:
old = self.data.copy()
self.data[1][1] = sy
self.data[1][-1] = ty
self._data_changed(old, self.data)
def _get_translate(self):
return [self.data[0][-1], self.data[1][-1]]
def _set_translate(self, s):
oldtx = self.data[0][-1]
oldty = self.data[1][-1]
tx, ty = s
forward = tx!=oldtx or ty!=oldty
if forward:
old = self.data.copy()
self.data[0][-1] = tx
self.data[1][-1] = ty
self._data_changed(old, self.data)
def _get_scale(self):
return [self.data[0][0], self.data[1][1]]
def _set_scale(self, s):
oldsx = self.data[0][0]
oldsy = self.data[1][1]
sx, sy = s
forward = sx!=oldsx or sy!=oldsy
if forward:
old = self.data.copy()
self.data[0][0] = sx
self.data[1][1] = sy
self._data_changed(old, self.data)
def _get_vec6(self):
a,b,tx = self.data[0]
c,d,ty = self.data[1]
return [a,b,c,d,tx,ty]
def _set_vec6(self, v):
a,b,c,d,tx,ty = v
olda, oldb, oldtx = self.data[0]
oldc, oldd, oldty = self.data[1]
forward = a!=olda or b!=oldb or c!=oldc or d!=oldd or tx!=oldtx or ty!=oldty
if forward:
old = self.data.copy()
self.data[0] = a,b,tx
self.data[1] = c,d,ty
self._data_changed(old, self.data)
def _get_lim(self, s, t):
lmin = -t/s
lmax = 1./s + lmin
return lmin, lmax
def _data_changed(self, old, new):
# Make it known if the translate changed
oldtx, oldty = old[0][-1], old[1][-1]
tx, ty = new[0][-1], new[1][-1]
oldsx, oldsy = old[0][0], old[1][1]
sx, sy = new[0][0], new[1][1]
oldb, oldc = old[0][1], old[1][0]
b, c = new[0][1], new[1][0]
tchanged = False
schanged = False
vchanged = False
tchanged = oldtx!=tx or oldty!=ty
schanged = oldsx!=sx or oldsy!=sy
vchanged = tchanged or schanged or b!=oldb or c!=oldc
xchanged = oldtx!=tx or oldsx!=sx
ychanged = oldty!=ty or oldsy!=sy
if tchanged:
self.trait_property_changed('translate', [oldtx, oldty], [tx, ty])
if schanged:
self.trait_property_changed('scale', [oldsx, oldsy], [sx, sy])
if xchanged:
oldxmin, oldxmax = self._get_lim(oldsx, oldtx)
xmin, xmax = self._get_lim(sx, tx)
self.trait_property_changed('xlim', [oldxmin, oldxmax], [xmin, xmax])
if ychanged:
oldymin, oldymax = self._get_lim(oldsy, oldty)
ymin, ymax = self._get_lim(sy, ty)
self.trait_property_changed('ylim', [oldymin, oldymax], [ymin, ymax])
if vchanged:
self.trait_property_changed(
'vec6',
[oldsx, oldb, oldc, oldsy, oldtx, oldty],
[sx, b, c, sy, tx, ty])
if tchanged or schanged or vchanged:
#self._data_modified = True
self.trait_property_changed('data_modified', old, new)
def follow(self, othervec6):
self.vec6 = othervec6
def __mul__(self, other):
if isinstance(other, Affine):
new = Affine()
new.data = npy.dot(self.data, other.data)
return new
elif isinstance(other, npy.ndarray):
return npy.dot(self.data, other)
raise TypeError('Do not know how to multiply Affine by %s'%type(other))
def __repr__(self):
return 'AFFINE: %s'%', '.join([str(val) for val in self.vec6])
#return 'AFFINE:\n%s'%self.data
class Box(HasTraits):
# left, bottom, width, height
bounds = traits.Array('d', (4,))
left = traits.Property(Float)
bottom = traits.Property(Float)
width = traits.Property(Float)
height = traits.Property(Float)
right = traits.Property(Float) # read only
top = traits.Property(Float) # read only
def _bounds_default(self):
return [0.0, 0.0, 1.0, 1.0]
def _get_left(self):
return self.bounds[0]
def _set_left(self, left):
oldbounds = self.bounds[:]
self.bounds[0] = left
self.trait_property_changed('bounds', oldbounds, self.bounds)
def _get_bottom(self):
return self.bounds[1]
def _set_bottom(self, bottom):
oldbounds = self.bounds[:]
self.bounds[1] = bottom
self.trait_property_changed('bounds', oldbounds, self.bounds)
def _get_width(self):
return self.bounds[2]
def _set_width(self, width):
oldbounds = self.bounds[:]
self.bounds[2] = width
self.trait_property_changed('bounds', oldbounds, self.bounds)
def _get_height(self):
return self.bounds[2]
def _set_height(self, height):
oldbounds = self.bounds[:]
self.bounds[2] = height
self.trait_property_changed('bounds', oldbounds, self.bounds)
def _get_right(self):
return self.left + self.width
def _get_top(self):
return self.bottom + self.height
def _bounds_changed(self, old, new):
pass
## begin custom trait handlers
class TraitVertexArray(TraitArray):
def __init__ ( self, typecode = None, shape = None, coerce = False ):
TraitArray.__init__(self, typecode, shape, coerce)
def validate(self, object, name, value):
orig = value
value = TraitArray.validate(self, object, name, value)
if len(value.shape)!=2 or value.shape[1]!=2:
return self.error(object, name, orig)
return value
def info(self):
return 'an Nx2 array of doubles which are x,y vertices'
VertexArray = Trait(npy.array([[0,0], [1,1]], npy.float_),
TraitVertexArray('d'))
class ColorHandler(traits.TraitHandler):
"""
This is a clever little traits mechanism -- users can specify the
color as any mpl color, and the traited object will keep the
original color, but will add a new attribute with a '_' postfix
which is the color rgba tuple.
Eg
class C(HasTraits):
facecolor = Trait('black', ColorHandler())
c = C()
c.facecolor = 'red'
print c.facecolor # prints red
print c.facecolor_ # print (1,0,0,1)
"""
is_mapped = True
def post_setattr(self, object, name, value):
object.__dict__[ name + '_' ] = self.mapped_value( value )
def mapped_value(self, value ):
if value is None: return None
if is_string_like(value): value = value.lower()
return mcolors.colorConverter.to_rgba(value)
def validate(self, object, name, value):
try:
self.mapped_value(value)
except ValueError:
return self.error(object, name, value)
else:
return value
def info(self):
return """\
any valid matplotlib color, eg an abbreviation like 'r' for red, a full
name like 'orange', a hex color like '#efefef', a grayscale intensity
like '0.5', or an RGBA tuple (1,0,0,1)"""
class MTraitsNamespace:
DPI = Float(72.)
Alpha = traits.Range(0., 1., 0.)
Affine = Trait(Affine())
AntiAliased = traits.true
Color = Trait('black', ColorHandler())
DPI = Float(72.)
Interval = Array('d', (2,), npy.array([0.0, 1.0], npy.float_))
LineStyle = Trait('-', '--', '-.', ':', 'steps', None)
LineWidth = Float(1.0)
Marker = Trait(None, '.', ',', 'o', '^', 'v', '<', '>', 's',
'+', 'x', 'd', 'D', '|', '_', 'h', 'H',
'p', '1', '2', '3', '4')
MarkerSize = Float(6)
Visible = traits.true
mtraits = MTraitsNamespace()
def Alias(name):
return Property(lambda obj: getattr(obj, name),
lambda obj, val: setattr(obj, name, val))
class IDGenerator:
def __init__(self):
self._id = 0
def __call__(self):
_id = self._id
self._id += 1
return _id
## begin backend API
# PATH CODES
STOP = 0
MOVETO = 1
LINETO = 2
CURVE3 = 3
CURVE4 = 4
CURVEN = 5
CATROM = 6
UBSPLINE = 7
CLOSEPOLY = 0x0F
class PathPrimitive(HasTraits):
"""
The path is an object that talks to the backends, and is an
intermediary between the high level path artists like Line and
Polygon, and the backend renderer
"""
color = mtraits.Color('black')
facecolor = mtraits.Color('blue')
alpha = mtraits.Alpha(1.0)
linewidth = mtraits.LineWidth(1.0)
antialiased = mtraits.AntiAliased
pathdata =Tuple(Array('b'), VertexArray)
affine = Instance(Affine, ())
def _pathdata_default(self):
return (npy.array([0,0], dtype=npy.uint8),
npy.array([[0,0],[0,0]], npy.float_))
class MarkerPrimitive(HasTraits):
locs = Array('d')
path = Instance(PathPrimitive, ()) # marker path in points
affine = Instance(Affine, ()) # transformation for the verts
def _locs_default(self):
return npy.array([[0,0],[0,0]], npy.float_)
class Renderer(HasTraits):
dpi = mtraits.DPI
size = traits.Tuple(Int(600), Int(400))
adisplay = Instance(Affine, ())
pathd = traits.Dict(Int, PathPrimitive)
markerd = traits.Dict(Int, MarkerPrimitive)
def __init__(self, size=(600,400)):
self.pathd = dict()
self.markerd = dict()
self._size_changed(None, size)
def _size_changed(self, old, new):
width, height = new
# almost all renderers assume 0,0 is left, upper, so we'll flip y here by default
self.adisplay.translate = 0, height
self.adisplay.scale = width, -height
def render_path(self, pathid):
pass
def new_path_primitive(self):
"""
return a PathPrimitive (or derived); these instances will be
added and removed later through add_path and remove path
"""
return PathPrimitive()
def new_marker_primitive(self):
"""
return a MarkerPrimitive (or derived); these instances will be
added and removed later through add_maker and remove_marker
"""
return MarkerPrimitive()
## begin backend agg
class PathPrimitiveAgg(PathPrimitive):
def __init__(self):
self._pathdata_changed(None, self.pathdata)
self._facecolor_changed(None, self.facecolor)
self._color_changed(None, self.color)
@staticmethod
def make_agg_path(pathdata):
agg_path = agg.path_storage()
codes, xy = pathdata
Ncodes = len(codes)
for i in range(Ncodes):
x, y = xy[i]
code = codes[i]
#XXX handle other path codes here
if code==MOVETO:
agg_path.move_to(x, y)
elif code==LINETO:
agg_path.line_to(x, y)
elif code==CLOSEPOLY:
agg_path.close_polygon()
return agg_path
def _pathdata_changed(self, olddata, newdata):
self.agg_path = PathPrimitiveAgg.make_agg_path(newdata)
def _facecolor_changed(self, oldcolor, newcolor):
self.agg_facecolor = self.color_to_rgba8(self.facecolor_)
def _color_changed(self, oldcolor, newcolor):
#print 'stroke color changed', newcolor
c = self.color_to_rgba8(self.color_)
self.agg_color = c
def color_to_rgba8(self, color):
if color is None: return None
rgba = [int(255*c) for c in color]
return agg.rgba8(*rgba)
class MarkerPrimitiveAgg(MarkerPrimitive):
path = Instance(PathPrimitiveAgg, ())
class RendererAgg(Renderer):
gray = agg.rgba8(128,128,128,255)
white = agg.rgba8(255,255,255,255)
blue = agg.rgba8(0,0,255,255)
black = agg.rgba8(0,0,0,0)
pathd = traits.Dict(Int, PathPrimitiveAgg)
markerd = traits.Dict(Int, MarkerPrimitiveAgg)
def _size_changed(self, old, new):
Renderer._size_changed(self, old, new)
width, height = self.size
stride = width*4
self.buf = buf = agg.buffer(width, height, stride)
self.rbuf = rbuf = agg.rendering_buffer()
rbuf.attachb(buf)
self.pf = pf = agg.pixel_format_rgba(rbuf)
self.rbase = rbase = agg.renderer_base_rgba(pf)
rbase.clear_rgba8(self.white)
# the antialiased renderers
self.renderer = agg.renderer_scanline_aa_solid_rgba(rbase);
self.rasterizer = agg.rasterizer_scanline_aa()
self.scanline = agg.scanline_p8()
self.trans = None
# the aliased renderers
self.rendererbin = agg.renderer_scanline_bin_solid_rgba(rbase);
self.scanlinebin = agg.scanline_bin()
def new_path_primitive(self):
'return a PathPrimitive (or derived)'
return PathPrimitiveAgg()
def new_marker_primitive(self):
'return a MarkerPrimitive (or derived)'
return MarkerPrimitiveAgg()
def render_path(self, pathid):
path = self.pathd[pathid]
if path.antialiased:
renderer = self.renderer
scanline = self.scanline
render_scanlines = agg.render_scanlines_rgba
else:
renderer = self.rendererbin
scanline = self.scanlinebin
render_scanlines = agg.render_scanlines_bin_rgba
affine = self.adisplay * path.affine
#print 'display affine:\n', self.adisplay
#print 'path affine:\n', path.affine
#print 'product affine:\n', affine
aggaffine = agg.trans_affine(*affine.vec6)
transpath = agg.conv_transform_path(path.agg_path, aggaffine)
if path.facecolor is not None:
#print 'render path', path.facecolor, path.agg_facecolor
self.rasterizer.add_path(transpath)
renderer.color_rgba8( path.agg_facecolor )
render_scanlines(self.rasterizer, scanline, renderer);
if path.color is not None:
stroke = agg.conv_stroke_transpath(transpath)
stroke.width(path.linewidth)
self.rasterizer.add_path(stroke)
renderer.color_rgba8( path.agg_color )
render_scanlines(self.rasterizer, scanline, renderer);
def render_marker(self, markerid):
marker = self.markerd[markerid]
path = marker.path
if path.antialiased:
renderer = self.renderer
scanline = self.scanline
render_scanlines = agg.render_scanlines_rgba
else:
renderer = self.rendererbin
scanline = self.scanlinebin
render_scanlines = agg.render_scanlines_bin_rgba
affinelocs = self.adisplay * marker.affine
Nmarkers = marker.locs.shape[0]
Locs = npy.ones((3, Nmarkers))
Locs[0] = marker.locs[:,0]
Locs[1] = marker.locs[:,1]
Locs = affinelocs * Locs
dpiscale = self.dpi/72. # for some reason this is broken
# this will need to be highly optimized and hooked into some
# extension code using cached marker rasters as we now do in
# _backend_agg
pathcodes, pathxy = marker.path.pathdata
pathx = dpiscale*pathxy[:,0]
pathy = dpiscale*pathxy[:,1]
Npath = len(pathcodes)
XY = npy.ones((Npath, 2))
for xv,yv,tmp in Locs.T:
XY[:,0] = (pathx + xv).astype(int) + 0.5
XY[:,1] = (pathy + yv).astype(int) + 0.5
pathdata = pathcodes, XY
aggpath = PathPrimitiveAgg.make_agg_path(pathdata)
if path.facecolor is not None:
self.rasterizer.add_path(aggpath)
renderer.color_rgba8( path.agg_facecolor )
render_scanlines(self.rasterizer, scanline, renderer);
if path.color is not None:
stroke = agg.conv_stroke_path(aggpath)
stroke.width(path.linewidth)
self.rasterizer.add_path(stroke)
renderer.color_rgba8( path.agg_color )
render_scanlines(self.rasterizer, scanline, renderer);
def show(self):
# we'll cheat a little and use pylab for display
X = npy.fromstring(self.buf.to_string(), npy.uint8)
width, height = self.size
X.shape = height, width, 4
if 1:
import pylab
fig = pylab.figure()
ax = fig.add_axes([0,0,1,1], xticks=[], yticks=[],
frameon=False, aspect='auto')
ax.imshow(X, aspect='auto')
pylab.show()
class Func(HasTraits):
def __call__(self, X):
'transform the numpy array with shape N,2'
return X
def invert(self, x, y):
'invert the point x, y'
return x, y
def point(self, x, y):
'transform the point x, y'
return x, y
class Identity(Func):
def __call__(self, X):
'transform the numpy array with shape N,2'
return X
def invert(self, x, y):
'invert the point x, y'
return x, y
def point(self, x, y):
'transform the point x, y'
return x, y
class Polar(Func):
def __call__(self, X):
'transform the numpy array with shape N,2'
r = X[:,0]
theta = X[:,1]
x = r*npy.cos(theta)
y = r*npy.sin(theta)
return npy.array([x,y]).T
def invert(self, x, y):
'invert the point x, y'
raise NotImplementedError
def point(self, x, y):
'transform the point x, y'
raise NotImplementedError
mtraits.Model = Instance(Func, ())
## begin Artist layer
# coordinates:
#
# artist model : a possibly nonlinear transformation (Func instance)
# to a separable cartesian coordinate, eg for polar is takes r,
# theta -> r*cos(theta), r*sin(theta)
#
# AxesCoords.adata : an affine 3x3 matrix that takes model output and
# transforms it to axes 0,1. We are kind of stuck with the
# mpl/matlab convention that 0,0 is the bottom left of the axes,
# even though it contradicts pretty much every GUI layout in the
# world
#
# AxesCoords.aview: an affine 3x3 that transforms an axesview into figure
# 0,1
#
# Renderer.adisplay : takes an affine 3x3 and puts figure view into display. 0,
# 0 is left, top, which is the typical coordinate system of most
# graphics formats
primitiveID = IDGenerator()
artistID = IDGenerator()
class Artist(HasTraits):
zorder = Float(1.0)
alpha = mtraits.Alpha()
visible = mtraits.Visible()
adata = Instance(Affine, ()) # the data affine
aview = Instance(Affine, ()) # the view affine
affine = Instance(Affine, ()) # the product of the data and view affine
renderer = Trait(None, Renderer)
# every artist defines a string which is the name of the attr that
# containers should put it into when added. Eg, an Axes is an
# Aritst container, and when you place a Line in to an Axes, the
# Axes will store a reference to it in the sequence ax.lines where
# Line.sequence = 'lines'
sequence = 'artists'
def __init__(self):
self.artistid = artistID()
# track affine as the product of the view and the data affines
# -- this should be a property, but I had trouble making a
# property on my custom class affine so this is a workaround
def product(ignore):
# modify in place
self.affine.follow((self.aview * self.adata).vec6)
product(None) # force an affine product updated
self.adata.on_trait_change(product, 'vec6')
self.aview.on_trait_change(product, 'vec6')
def _get_affine(self):
return self.aview * self.adata
def draw(self):
pass
class ArtistContainer(Artist):
artistd = traits.Dict(Int, Artist)
sequence = 'containers'
def __init__(self):
Artist.__init__(self)
self.artistd = dict()
def add_artist(self, artist, followdata=True, followview=True):
# this is a very interesting change from matplotlib -- every
# artist acts as a container that can hold other artists, and
# respects zorder drawing internally. This makes zordering
# much more flexibel
self.artistd[artist.artistid] = artist
self.__dict__.setdefault(artist.sequence, []).append(artist)
artist.renderer = self.renderer
self.sync_trait('renderer', artist, mutual=False)
artist.followdata = followdata
artist.followview = followview
if followdata:
# set the data affines to be the same
artist.adata.follow(self.adata.vec6)
self.adata.on_trait_change(artist.adata.follow, 'vec6')
if followview:
# set the view affines to be the same
artist.aview.follow(self.aview.vec6)
self.aview.on_trait_change(artist.aview.follow, 'vec6')
def remove_artist(self, artist):
if artist.followview:
self.aview.on_trait_change(artist.aview.follow, 'vec6', remove=True)
del artist.followview
if artist.followdata:
self.adata.on_trait_change(artist.adata.follow, 'vec6', remove=True)
del artist.followdata
self.sync_trait('renderer', artist, remove=True)
del self.artistd[artist.artistid]
self.__dict__[artist.sequence].remove(artist)
def draw(self):
if self.renderer is None or not self.visible: return
dsu = [(artist.zorder, artist.artistid, artist) for artist in self.artistd.values()]
dsu.sort()
for zorder, artistid, artist in dsu:
#print 'artist draw', self, artist, zorder
artist.draw()
class Path(Artist):
"""
An interface class between the higher level artists and the path
primitive that needs to talk to the renderers
"""
_path = traits.Instance(PathPrimitive, ())
antialiased = mtraits.AntiAliased()
color = mtraits.Color('blue')
facecolor = mtraits.Color('yellow')
linestyle = mtraits.LineStyle('-')
linewidth = mtraits.LineWidth(1.0)
model = mtraits.Model
pathdata = traits.Tuple(Array('b'), VertexArray)
sequence = 'paths'
zorder = Float(1.0)
# why have an extra layer separating the PathPrimitive from the
# Path artist? The reasons are severalfold, but it is still not
# clear if this is the better solution. Doing it this way enables
# the backends to create their own derived primitves (eg
# RendererAgg creates PathPrimitiveAgg, and in that class sets up
# trait listeners to create agg colors and agg paths when the
# PathPrimitive traits change. Another reason is that it allows
# us to handle nonlinear transformation (the "model") at the top
# layer w/o making the backends understand them. The current
# design is create a mapping between backend primitives and
# primitive artists (Path, Text, Image, etc...) and all of the
# higher level Artists (Line, Polygon, Axis) will use the
# primitive artitsts. So only a few artists will need to know how
# to talk to the backend. The alternative is to make the backends
# track and understand the primitive artists themselves.
def __init__(self):
"""
The model is a function taking Nx2->Nx2. This is where the
nonlinear transformation can be used
"""
Artist.__init__(self)
self._pathid = primitiveID()
def _pathdata_default(self):
return (npy.array([0,0], dtype=npy.uint8),
npy.array([[0,0],[0,0]], npy.float_))
def _update_path(self):
'sync the Path traits with the path primitive'
self.sync_trait('linewidth', self._path, mutual=False)
self.sync_trait('color', self._path, mutual=False)
self.sync_trait('facecolor', self._path, mutual=False)
self.sync_trait('antialiased', self._path, mutual=False)
# sync up the path affine
self._path.affine.follow(self.affine.vec6)
self.affine.on_trait_change(self._path.affine.follow, 'vec6')
self._update_pathdata()
def _update_pathdata(self):
#print 'PATH: update pathdata'
codes, xy = self.pathdata
#print ' PATH: shapes', codes.shape, xy.shape
if self.model is not None:
xy = self.model(xy)
pathdata = codes, xy
self._path.pathdata = pathdata
def draw(self):
if self.renderer is None or not self.visible: return
Artist.draw(self)
self.renderer.render_path(self._pathid)
def _renderer_changed(self, old, new):
if old is not None:
del old.pathd[self._pathid]
if new is None: return
#print 'PATH renderer_changed; updating'
self._path = renderer.new_path_primitive()
new.pathd[self._pathid] = self._path
self._update_path()
def _model_changed(self, old, new):
self._update_pathdata()
def _pathdata_changed(self, old, new):
#print 'PATH: pathdata changed'
self._update_pathdata()
class Marker(Artist):
"""
An interface class between the higher level artists and the marker
primitive that needs to talk to the renderers
"""
_marker = traits.Instance(MarkerPrimitive, ())
locs = Array('d')
path = Instance(Path, ())
model = mtraits.Model
sequence = 'markers'
size = Float(1.0) # size of the marker in points
def __init__(self):
"""
The model is a function taking Nx2->Nx2. This is where the
nonlinear transformation can be used
"""
Artist.__init__(self)
self._markerid = primitiveID()
def _locs_default(self):
return npy.array([[0,1],[0,1]], npy.float_)
def _path_default(self):
bounds = npy.array([-0.5, -0.5, 1, 1])*self.size
return Rectangle().set(bounds=bounds)
def _path_changed(self, old, new):
if self.renderer is None:
# we can't sync up to the underlying path yet
return
print 'MARKER _path_changed', self.path._path.pathdata, self._marker.path.pathdata
old.sync_trait('_path', self._marker, 'path', remove=True)
new.sync_trait('_path', self._marker, 'path', mutual=False)
def _update_marker(self):
'sync the Marker traits with the marker primitive'