forked from CDAT/cdat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCanvas.py
More file actions
6069 lines (5336 loc) · 267 KB
/
Canvas.py
File metadata and controls
6069 lines (5336 loc) · 267 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
#!/usr/bin/env python
# Adapted for numpy/ma/cdms2 by convertcdms.py
#
# The VCS Canvas API controls - canvas module
#
###############################################################################
# #
# Module: canvas module #
# #
# Copyright: "See file Legal.htm for copyright information." #
# #
# Authors: PCMDI Software Team #
# Lawrence Livermore National Laboratory: #
# support@pcmdi.llnl.gov #
# #
# Description: PCMDI's VCS Canvas is used to display plots and to create and #
# run animations. It is always visible on the screen in a #
# landscape (width exceeding height), portrait (height exceeding#
# width), or full-screen mode. #
# #
# Version: 4.0 #
# #
###############################################################################
"""Canvas: the class representing a vcs drawing window
Normally, created by vcs.init()
Contains the method plot.
"""
import __main__
import warnings
#import Tkinter
from pauser import pause
import thread
import numpy.ma, MV2
import numpy, cdutil
from queries import *
import boxfill, isofill, isoline, outfill, outline, taylor, meshfill, projection
import vector, continents, line, marker, fillarea
import texttable, textorientation, textcombined, template, colormap
import unified1D
#import colormapgui as _colormapgui
#import canvasgui as _canvasgui
import displayplot
import vtk
from VTKPlots import VTKVCSBackend
from weakref import WeakSet, WeakKeyDictionary
import time
#import animationgui as _animationgui
#import graphicsmethodgui as _graphicsmethodgui
#import templateeditorgui as _templateeditorgui
#import gui_template_editor as _gui_template_editor
#import pagegui as _pagegui
#import projectiongui as _projectiongui
from error import vcsError
import cdms2
import copy
import cdtime,vcs
import os
import sys
import random
import genutil
from cdms2.grid import AbstractRectGrid
import shutil, inspect
import VCS_validation_functions
import AutoAPI
from xmldocs import plot_keywords_doc,graphics_method_core,axesconvert,xaxisconvert,yaxisconvert, plot_1D_input, plot_2D_input, plot_output, plot_2_1D_input, create_GM_input, get_GM_input, boxfill_output, isofill_output, isoline_output, yxvsx_output, xyvsy_output, xvsy_output, scatter_output, outfill_output, outline_output, plot_2_1D_options
# Flag to set if the initial attributes file has aready been read in
called_initial_attributes_flg = 0
gui_canvas_closed = 0
canvas_closed = 0
#import Pmw
import vcsaddons
import vcs.manageElements
import configurator
from projection import round_projections
class SIGNAL(object):
def __init__( self, name = None ):
self._functions = WeakSet()
self._methods = WeakKeyDictionary()
self._name = name
def __call__(self, *args, **kargs):
# Call handler functions
for func in self._functions:
func(*args, **kargs)
# Call handler methods
for obj, funcs in self._methods.items():
for func in funcs:
func(obj, *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
if slot.__self__ not in self._methods:
self._methods[slot.__self__] = set()
self._methods[slot.__self__].add(slot.__func__)
else:
self._functions.add(slot)
def disconnect(self, slot):
if inspect.ismethod(slot):
if slot.__self__ in self._methods:
self._methods[slot.__self__].remove(slot.__func__)
else:
if slot in self._functions:
self._functions.remove(slot)
def clear(self):
self._functions.clear()
self._methods.clear()
def dictionarytovcslist(dictionary,name):
for k in dictionary.keys():
if not isinstance(k,(float,int,long)):
raise Exception,'Error, vcs list must have numbers only as keys'
_vcs.dictionarytovcslist(dictionary,name)
return None
def _determine_arg_list(g_name, actual_args):
"Determine what is in the argument list for plotting graphics methods"
itemplate_name = 2
igraphics_method = 3
igraphics_option = 4
# Note: Set default graphics method to 'default', which is invalid.
# If it is not modified in this routine, it will be filled in later
# in _reconstruct_tv after the grid type is established.
#
## Xtrargs - {} - added by C.Doutriaux, needed for projection object passed
## Need to be passed as keyword later
arglist = [None, None, 'default', 'default', 'default',{}]
arghold = []
argstring=[]
args = actual_args
found_slabs = 0
for i in range(len(args)):
if isinstance(args[i],str):
argstring.append(args[i])
else:
try:
possible_slab = cdms2.asVariable (args[i], 0)
if hasattr( possible_slab, 'iscontiguous' ):
if not possible_slab.iscontiguous():
#this seems to loose the id...
saved_id = possible_slab.id
possible_slab = possible_slab.ascontiguousarray()
possible_slab.id = saved_id
arglist[found_slabs] = possible_slab
if found_slabs == 2:
raise vcsError, "Too many slab arguments."
found_slabs = found_slabs + 1
except cdms2.CDMSError:
arghold.append(args[i])
#
# Now find the template
#
args = arghold
arghold = []
found_template = 0
for i in range(len(args)):
if (istemplate(args[i])):
if found_template:
raise vcsError, 'You can only specify one template object.'
arglist[itemplate_name] = args[i].name
found_template = found_template + 1
else:
arghold.append(args[i])
#
# Now find the graphics method
#
args = arghold
arghold = []
found_graphics_method = 0
for i in range(len(args)):
if (isgraphicsmethod(args[i])):
if found_graphics_method:
raise vcsError,'You can only specify one graphics method.'
arglist[igraphics_method] = graphicsmethodtype(args[i])
arglist[igraphics_option] = args[i].name
found_graphics_method = found_graphics_method + 1
elif (isline(args[i])):
if found_graphics_method:
raise vcsError,'You can only specify one graphics method.'
arglist[igraphics_method] = 'line'
arglist[igraphics_option] = args[i].name
found_graphics_method = found_graphics_method + 1
elif (ismarker(args[i])):
if found_graphics_method:
raise vcsError,'You can only specify one graphics method.'
arglist[igraphics_method] = 'marker'
arglist[igraphics_option] = args[i].name
found_graphics_method = found_graphics_method + 1
elif (isfillarea(args[i])):
if found_graphics_method:
raise vcsError,'You can only specify one graphics method.'
arglist[igraphics_method] = 'fillarea'
arglist[igraphics_option] = args[i].name
found_graphics_method = found_graphics_method + 1
elif (istext(args[i])):
if found_graphics_method:
raise vcsError,'You can only specify one graphics method.'
arglist[igraphics_method] = 'text'
arglist[igraphics_option] = args[i].Tt_name + ':::' + args[i].To_name
found_graphics_method = found_graphics_method + 1
elif (isprojection(args[i])):
arglist[5]['projection']=args[i].name
elif isinstance(args[i],vcsaddons.core.VCSaddon):
if found_graphics_method:
raise vcsError,'You can only specify one graphics method.'
arglist[igraphics_method] = graphicsmethodtype(args[i])
arglist[igraphics_option] = args[i].name
found_graphics_method = found_graphics_method + 1
else:
raise vcsError, "Unknown type %s of argument to plotting command." %\
type(args[i])
if g_name is not None:
arglist[igraphics_method] = g_name
# Now install the string arguments, left to right.
if found_template == 0:
if len(argstring) > 0:
arglist[itemplate_name] = argstring[0]
del argstring[0]
if found_graphics_method == 0 and g_name is None:
if len(argstring) > 0 :
arglist[igraphics_method] = argstring[0]
del argstring[0]
# Check for various errors
if len(argstring) >= 1:
arglist[igraphics_option] = argstring[0]
del argstring[0]
if len(argstring) > 0:
if g_name is None:
raise vcsError, "Error in argument list for vcs plot command."
else:
raise vcsError, "Error in argument list for vcs %s command." % g_name
if isinstance(arglist[igraphics_method],vcsaddons.core.VCSaddon):
if found_slabs!=arglist[igraphics_method].g_nslabs:
raise vcsError, "%s requires %i slab(s)" % (arglist[igraphics_method].g_name,arglist[igraphics_method].g_nslabs)
else:
if arglist[igraphics_method].lower() in ( 'scatter', 'vector', 'xvsy', 'stream', 'glyph', '3d_vector', '3d_dual_scalar' ):
if found_slabs != 2:
raise vcsError, "Graphics method %s requires 2 slabs." % arglist[igraphics_method]
elif arglist[igraphics_method].lower() == 'meshfill':
if found_slabs == 0:
raise vcsError, "Graphics method requires at least 1 slab."
elif found_slabs == 1:
g=arglist[0].getGrid()
if not isinstance(g, (cdms2.gengrid.AbstractGenericGrid,cdms2.hgrid.AbstractCurveGrid,cdms2.grid.TransientRectGrid)):
raise vcsError, "Meshfill requires 2 slab if first slab doesn't have a Rectilinear, Curvilinear or Generic Grid type"
elif ((arglist[igraphics_method] == 'continents') or
(arglist[igraphics_method] == 'line') or
(arglist[igraphics_method] == 'marker') or
(arglist[igraphics_method] == 'fillarea') or
(arglist[igraphics_method] == 'text')):
if found_slabs != 0:
raise vcsError, "Continents or low-level primative methods requires 0 slabs."
elif arglist[igraphics_method].lower()=='default':
pass # Check later
else:
if found_slabs != 1 and not(found_slabs == 2 and arglist[igraphics_method].lower()=="1d"):
raise vcsError, "Graphics method %s requires 1 slab." % arglist[igraphics_method]
if isinstance(arglist[3],str): arglist[3]=arglist[3].lower()
return arglist
def _process_keyword(obj, target, source, keyargs, default=None):
""" Set obj.target from:
- keyargs[source]
- default
- obj.source
in that order."""
arg = keyargs.get(source)
if arg is not None:
setattr(obj, target, arg)
elif default is not None:
setattr(obj, target, default)
elif hasattr(obj, source):
setattr(obj, target, getattr(obj, source))
return arg
def finish_queued_X_server_requests( self ):
""" Wait for the X server to execute all pending events.
If working with C routines, then use BLOCK_X_SERVER
found in the VCS module routine to stop the X server
from continuing. Thus, eliminating the asynchronous
errors.
"""
x_num = self.canvas.xpending()
count = 0
while x_num != 0:
x_num = self.canvas.xpending()
count += 1
# Move on already! The X sever must be completed by this point!
# If count of 1000 is reached, then discard all events from
# this point on in the queue.
if count > 1000:
self.canvas.xsync_discard()
break
class Canvas(object,AutoAPI.AutoAPI):
"""
Function: Canvas # Construct a VCS Canvas class Object
Description of Function:
Construct the VCS Canas object. There can only be at most 8 VCS
Canvases open at any given time.
Example of Use:
a=vcs.Canvas() # This examples constructs a VCS Canvas
"""
#############################################################################
# #
# Set attributes for VCS Canvas Class (i.e., set VCS Canvas Mode). #
# #
#############################################################################
__slots__ = [
'_mode',
'_pause_time',
'_viewport',
'_worldcoordinate',
'_winfo_id',
'_varglist',
'_canvas_gui',
'_animate_info',
'_canvas_template_editor',
'_isplottinggridded',
'_user_actions_names',
'_user_actions',
'_animate',
'_canvas',
'mode',
'pause_time',
'viewport',
'worldcoordinate',
'winfo_id',
'varglist',
'canvas_gui'
'animate_info',
'canvas_template_editor',
'isplottinggridded',
'ratio',
'canvas',
'animate',
'user_actions_names',
'user_actions',
'size',
'canvas_guianimate_info',
]
# def applicationFocusChanged(self, old, current ):
# self.backend.applicationFocusChanged()
def _set_user_actions_names(self,value):
value=VCS_validation_functions.checkListElements(self,'user_actions_names',value,VCS_validation_functions.checkString)
self._user_actions_names = value
while len(self._user_actions)<len(self._user_actions_names):
self._user_actions.append(self._user_actions[-1])
def _get_user_actions_names(self):
return self._user_actions_names
user_actions_names = property(_get_user_actions_names,_set_user_actions_names)
def _set_user_actions(self,value):
value=VCS_validation_functions.checkListElements(self,'user_actions_names',value,VCS_validation_functions.checkCallable)
self._user_actions = value
while len(self._user_actions)<len(self._user_actions_names):
self._user_actions.append(self._user_actions[-1])
def _get_user_actions(self):
return self._user_actions
user_actions = property(_get_user_actions,_set_user_actions)
def _setmode(self,value):
value=VCS_validation_functions.checkInt(self,'mode',value,minvalue=0,maxvalue=1)
self._mode=value
def _getmode(self):
return self._mode
mode = property(_getmode,_setmode)
def _setwinfo_id(self,value):
value=VCS_validation_functions.checkInt(self,'winfo_id',value)
self._winfo_id=value
def _getwinfo_id(self):
return self._winfo_id
winfo_id = property(_getwinfo_id,_setwinfo_id)
def _setvarglist(self,value):
value=VCS_validation_functions.checkListElements(self,'varglist',value,VCS_validation_functions.checkCallable)
self._varglist = value
def _getvarglist(self):
return self._varglist
varglist = property(_getvarglist,_setvarglist)
def _setcanvas_gui(self,value):
self._canvas_gui = value
def _getcanvas_gui(self):
return self._canvas_gui
canvas_gui = property(_getcanvas_gui,_setcanvas_gui)
def _setcanvas(self,value):
raise vcsError, "Error, canvas is not an attribute you can set"
def _getcanvas(self):
return self._canvas
canvas = property(_getcanvas,_setcanvas)
def _setanimate(self,value):
raise vcsError, "Error, animate is not an attribute you can set"
def _getanimate(self):
return self._animate
animate = property(_getanimate,_setanimate)
def _setpausetime(self,value):
value=VCS_validation_functions.checkInt(self,'pause_time',value)
self._pause_time = value
def _getpausetime(self):
return self._pause_time
pause_time = property(_getpausetime,_setpausetime)
def _setviewport(self,value):
if not isinstance(value,list) and not len(value)==4:
raise vcsError, "viewport must be of type list and have four values ranging between [0,1]."
for v in range(4):
if not 0.<=value[v]<=1.:
raise vcsError, "viewport must be of type list and have four values ranging between [0,1]."
self._viewport=value
def _getviewport(self):
return self._viewport
viewport = property(_getviewport,_setviewport)
def _setworldcoordinate(self,value):
if not isinstance(value,list) and not len(value)==4:
raise vcsError, "worldcoordinate must be of type list and have four values ranging between [0,1]."
self._worldcoordinate=value
def _getworldcoordinate(self):
return self._worldcoordinate
worldcoordinate = property(_getworldcoordinate,_setworldcoordinate)
def _setcanvas_template_editor(self,value):
self._canvas_template_editor=value # No check on this!
def _getcanvas_template_editor(self):
return self._canvas_template_editor
canvas_template_editor =property(_getcanvas_template_editor,_setcanvas_template_editor)
def _setisplottinggridded(self,value):
if not isinstance(value,bool):
raise vcsError, "isplottinggridded must be boolean"
self._isplottinggridded=value # No check on this!
def _getisplottinggridded(self):
return self._isplottinggridded
isplottinggridded =property(_getisplottinggridded,_setisplottinggridded)
def _setanimate_info(self,value):
self._animate_info=value # No check on this!
def _getanimate_info(self):
return self._animate_info
animate_info =property(_getanimate_info,_setanimate_info)
def start(self,*args,**kargs):
self.interact(*args,**kargs)
def interact(self,*args,**kargs):
if self.configurator is not None:
self.configurator.show()
self.backend.interact(*args,**kargs)
def _datawc_tv(self, tv, arglist):
"""The graphics method's data world coordinates (i.e., datawc_x1, datawc_x2,
datawc_y1, and datawc_y2) will override the incoming variable's coordinates.
tv equals arglist[0] and assumed to be the first Variable. arglist[1] is
assumed to be the second variable."""
# Determine the type of graphics method
nvar = 1
if arglist[3] == 'boxfill':
gm=self.getboxfill( arglist[4] )
elif arglist[3] == 'isofill':
gm=self.getisofill( arglist[4] )
elif arglist[3] == 'isoline':
gm=self.getisoline( arglist[4] )
elif arglist[3] == 'outfill':
gm=self.getoutfill( arglist[4] )
elif arglist[3] == 'outline':
gm=self.getoutline( arglist[4] )
elif arglist[3] == 'continents':
gm=self.getcontinents( arglist[4] )
elif arglist[3] == 'scatter':
nvar = 2
gm=self.getscatter( arglist[4] )
elif arglist[3] == 'vector':
nvar = 2
gm=self.getvector( arglist[4] )
elif arglist[3] == 'xvsy':
nvar = 2
gm=self.getxvsy( arglist[4] )
elif arglist[3] == 'xyvsy':
gm=self.getxyvsy( arglist[4] )
elif arglist[3] == 'yxvsx':
gm=self.getyxvsx( arglist[4] )
elif arglist[3] == 'taylor':
gm=self.gettaylor( arglist[4] )
elif arglist[3] == 'meshfill':
gm=self.getmeshfill( arglist[4] )
else:
return tv
# Determine if the graphics method needs clipping
f32 = numpy.array((1.e20),numpy.float32)
set_new_x = 0
set_new_y = 0
if (gm.datawc_x1 != f32) and (gm.datawc_x2 != f32): set_new_x = 1
if (gm.datawc_y1 != f32) and (gm.datawc_y2 != f32): set_new_y = 1
try:
if ((set_new_x == 1) and (set_new_y == 0)) or (arglist[3] == 'yxvsx'):
tv = tv( longitude=(gm.datawc_x1, gm.datawc_x2) )
if nvar == 2:
arglist[1] = arglist[1]( longitude=(gm.datawc_x1, gm.datawc_x2) )
elif ((set_new_x == 0) and (set_new_y == 1)) or (arglist[3] == 'xyvsy'):
tv = tv( latitude=(gm.datawc_y1, gm.datawc_y2) )
if nvar == 2:
arglist[1] = arglist[1]( latitude=(gm.datawc_y1, gm.datawc_y2) )
elif (set_new_x == 1) and (set_new_y == 1):
tv = tv( latitude=(gm.datawc_y1, gm.datawc_y2), longitude=(gm.datawc_x1,gm.datawc_x2) )
if nvar == 2:
arglist[1] = arglist[1]( latitude=(gm.datawc_y1, gm.datawc_y2), longitude=(gm.datawc_x1,gm.datawc_x2) )
except:
pass
return tv
def savecontinentstype(self,value):
self._savedcontinentstype = value
def onClosing( self, cell ):
self.backend.onClosing( cell )
def _reconstruct_tv(self, arglist, keyargs):
"""Reconstruct a transient variable from the keyword arguments.
Also select the default graphics method, depending on the grid type
of the reconstructed variable. For meshfill, ravel the last two
dimensions if necessary.
arglist[0] is assumed to be a Variable."""
ARRAY_1 = 0
ARRAY_2 = 1
TEMPLATE = 2
GRAPHICS_METHOD = 3
GRAPHICS_OPTION = 4
origv = arglist[ARRAY_1]
# Create copies of domain and attributes
variable = keyargs.get('variable')
if variable is not None:
origv=MV2.array(variable)
tvdomain = origv.getDomain()
attrs = copy.copy(origv.attributes)
axislist = list(map(lambda x: x[0].clone(), tvdomain))
# Map keywords to dimension indices
try: rank = origv.ndim
except: rank = len( origv.shape )
dimmap = {}
dimmap['x'] = xdim = rank-1
dimmap['y'] = ydim = rank-2
dimmap['z'] = zdim = rank-3
dimmap['t'] = tdim = rank-4
dimmap['w'] = wdim = rank-5
# Process grid keyword
grid = keyargs.get('grid')
if grid is not None and xdim>=0 and ydim>=0:
if grid.getOrder() is None or grid.getOrder()=='yx':
axislist[xdim] = grid.getLongitude().clone()
axislist[ydim] = grid.getLatitude().clone()
else:
axislist[xdim] = grid.getLatitude().clone()
axislist[ydim] = grid.getLongitude().clone()
# Process axis keywords
for c in ['x','y','z','t','w']:
if dimmap[c]<0:
continue
arg = keyargs.get(c+'axis')
if arg is not None:
axislist[dimmap[c]] = arg.clone()
# Process array keywords
for c in ['x','y','z','t','w']:
if dimmap[c]<0:
continue
arg = keyargs.get(c+'array')
if arg is not None:
axis = axislist[dimmap[c]]
axis = cdms2.createAxis(arg,id=axis.id)
axis.setBounds(None)
axislist[dimmap[c]]=axis
# Process bounds keywords
for c in ['x','y']:
if dimmap[c]<0:
continue
arg = keyargs.get(c+'bounds')
if arg is not None:
axis = axislist[dimmap[c]]
axis.setBounds(arg)
# Process axis name keywords
for c in ['x','y','z','t','w']:
if dimmap[c]<0:
continue
arg = keyargs.get(c+'name')
if arg is not None:
axis = axislist[dimmap[c]]
axis.id = axis.name = arg
# Create the internal tv
tv = cdms2.createVariable(origv, copy=0, axes=axislist, attributes=attrs)
grid = tv.getGrid()
isgridded = (grid is not None)
# Set the default graphics method if not already set.
if arglist[GRAPHICS_METHOD] in ['default','boxfill']: # See _determine_arg_list
try:
nomesh=0
m=grid.getMesh()
except:
nomesh=1
if grid is None:
if tv.ndim==1:
arglist[GRAPHICS_METHOD] = 'yxvsx1'
else:
arglist[GRAPHICS_METHOD] = 'boxfill'
elif isinstance(grid, AbstractRectGrid):
arglist[GRAPHICS_METHOD] = 'boxfill'
else:
latbounds, lonbounds = grid.getBounds()
if (latbounds is None) or (lonbounds is None):
if not isinstance(grid,cdms2.hgrid.AbstractCurveGrid):
# Plug in 'points' graphics method here, with:
# arglist[GRAPHICS_METHOD] = 'points'
raise vcsError, "Cell boundary data is missing, cannot plot nonrectangular gridded data."
else:
arglist[GRAPHICS_METHOD] = 'boxfill'
else:
# tv has a nonrectilinear grid with bounds defined,
# so use meshfill. Create another default meshobject to hang
# keywords on, since the true 'default' meshobject
# is immutable.
arglist[GRAPHICS_METHOD] = 'meshfill'
# Get the mesh from the grid.
try:
gridindices = tv.getGridIndices()
except:
gridindices = None
mesh = grid.getMesh(transpose=gridindices)
# mesh array needs to be mutable, so make it a tv.
# Normally this is done up front in _determine_arg_list.
arglist[ARRAY_2] = cdms2.asVariable(mesh, 0)
meshobj = self.createmeshfill()
meshobj.wrap = [0.0, 360.0] # Wraparound
arglist[GRAPHICS_OPTION] = '__d_meshobj'
# IF Meshfill method and no mesh passed then try to get the mesh from the object
if arglist[GRAPHICS_METHOD]=='meshfill' and arglist[ARRAY_2] is None:
# Get the mesh from the grid.
try:
gridindices = tv.getGridIndices()
mesh = grid.getMesh(transpose=gridindices)
except:
gridindices = None
mesh = grid.getMesh()
# mesh array needs to be mutable, so make it a tv.
# Normally this is done up front in _determine_arg_list.
arglist[ARRAY_2] = cdms2.asVariable(mesh, 0)
if arglist[GRAPHICS_OPTION] == 'default':
meshobj = self.createmeshfill()
meshobj.wrap = [0.0, 360.0] # Wraparound
arglist[GRAPHICS_OPTION] = meshobj.name
# Ravel the last two dimensions for meshfill if necessary
## value to know if we're plotting a grided meshfill
self.isplottinggridded=False
#if (arglist[GRAPHICS_METHOD]=='meshfill') and (tv.shape[-1] != arglist[ARRAY_2].shape[-3]):
# tvshape = tv.shape
# if isgridded:
# ny, nx = grid.shape
# if nx*ny==arglist[ARRAY_2].shape[-3]:
# ravelshape = tuple(list(tvshape)[:-2]+[ny*nx])
# xdim=ydim
# self.isplottinggridded=True
# else:
# ny, nx = tvshape[-2:]
# ravelshape = tuple(list(tvshape)[:-2]+[ny*nx])
# else:
# ny, nx = tvshape[-2:]
# ravelshape = tuple(list(tvshape)[:-2]+[ny*nx])
# tv = MV2.reshape(tv, ravelshape)
# xdim=ydim
# self.isplottinggridded=True
# if (tv.shape[-1] != arglist[ARRAY_2].shape[-3]):
# raise vcsError, "Mesh length = %d, does not match variable shape: %s"%(arglist[ARRAY_2].shape[-3], `tvshape`)
#else:
if isgridded and (arglist[GRAPHICS_METHOD]=='meshfill'):
self.isplottinggridded=True
# Process variable attributes
_process_keyword(tv, 'comment1', 'comment1', keyargs)
_process_keyword(tv, 'comment2', 'comment2', keyargs)
_process_keyword(tv, 'comment3', 'comment3', keyargs)
_process_keyword(tv, 'comment4', 'comment4', keyargs)
_process_keyword(tv, 'source', 'file_comment', keyargs)
_process_keyword(tv, 'time', 'hms', keyargs)
_process_keyword(tv, 'title', 'long_name', keyargs)
_process_keyword(tv, 'name', 'name', keyargs, default=tv.id)
time = keyargs.get('time')
if time is not None:
ctime = time.tocomp()
ar.date = str(ctime)
_process_keyword(tv, 'units', 'units', keyargs)
_process_keyword(tv, 'date', 'ymd', keyargs)
# If date has still not been set, try to get it from the first
# time value if present
if not hasattr(tv, 'date') and not hasattr(tv, 'time'):
change_date_time(tv, 0)
# Draw continental outlines if specified.
contout = keyargs.get('continents',None)
if contout is None:
# if xdim>=0 and ydim>=0 and isgridded:
## Charles put back the self.isplottinggridded in addition for meshfill,
if (xdim>=0 and ydim>=0 and tv.getAxis(xdim).isLongitude() and tv.getAxis(ydim).isLatitude()) or (self.isplottinggridded):
contout = 1
else:
contout = 0
if (isinstance(arglist[GRAPHICS_METHOD],str) and (arglist[GRAPHICS_METHOD]) == 'meshfill') or ((xdim>=0 and ydim>=0 and (contout>=1) and (contout<12))):
self.setcontinentstype(contout)
self.savecontinentstype(contout)
else:
self.setcontinentstype(0)
self.savecontinentstype(0)
# Reverse axis direction if necessary
xrev = keyargs.get('xrev',0)
if xrev==1 and xdim>=0:
tv = tv[... , ::-1]
# By default, latitudes on the y-axis are plotted S-N
# levels on the y-axis are plotted with decreasing pressure
if ydim>=0:
yaxis = tv.getAxis(ydim)
yrev = 0
## -- This code forces the latitude axis to alway be shown from -90 (South) to
## 90 (North). This causes a problem when wanting to view polar plots from
## the North. So this feature has been removed.
##
## if yaxis.isLatitude() and yaxis[0]>yaxis[-1]: yrev=1
## if yaxis.isLevel() and yaxis[0]<yaxis[-1]: yrev=1
yrev = keyargs.get('yrev',yrev)
if yrev==1:
## yarray = copy.copy(yaxis[:])
## ybounds = yaxis.getBounds()
## yaxis[:] = yarray[::-1]
## yaxis.setBounds(ybounds[::-1,::-1])
tv = tv[..., ::-1, :].clone()
# -- This s no longer needed since we are making a copy of the data.
# We now apply the axes changes below in __plot. Dean and Charles keep
# an eye opened for the errors concerning datawc in the VCS module.
# tv = self._datawc_tv( tv, arglist )
return tv
#############################################################################
# #
# Print out the object's doc string. #
# #
#############################################################################
def objecthelp(self, *arg):
"""
Function: objecthelp # Print out the object's doc string
Description of Function:
Print out information on the VCS object. See example below on its use.
Example of Use:
a=vcs.init()
ln=a.getline('red') # Get a VCS line object
a.objecthelp(ln) # This will print out information on how to use ln
"""
for x in arg:
print getattr(x, "__doc__", "")
#############################################################################
# #
# Initialize the VCS Canvas and set the Canvas mode to 0. Because the mode #
# is set to 0, the user will have to manually update the VCS Canvas by #
# using the "update" function. #
# #
#############################################################################
def __init__(self, gui = 0, mode = 1, pause_time=0, call_from_gui=0, size=None, backend = "vtk"):
#############################################################################
# #
# The two Tkinter calls were needed for earlier versions of CDAT using #
# tcl/tk 8.3 and Python 2.2. In these earlier version of CDAT, Tkinter must #
# be called before "_vcs.init()", which uses threads. That is, #
# "_vcs.init()" calls "XInitThreads()" which causes Tkinter keyboard events #
# to hang. By calling Tkinter.Tk() first solves the problem. #
# #
# The code must have "XInitThreads()". Without this function, Xlib produces #
# asynchronous errors. This X thread function can be found in the #
# vcsmodule.c file located in the "initialize_X routine. #
# #
# Graphics User Interface Mode: #
# gui = 0|1 if ==1, create the canvas with GUI controls #
# (Default setting is *not* to display GUI controls) #
# #
# Note: #
# For version 4.0, which uses tcl/tk 8.4 and Python 2.3, the below #
# Tkinter.Tk() calls are not necessary. #
# #
# The code will remain here, but commented out in case the bug in #
# tcl/tk reappears. #
# #
#########if (call_from_gui == 0): #########
######### try: #########
######### print ' NO local host' #########
######### rt = Tkinter.Tk() # Use the default DISPLAY and screen #########
######### print ' I have a rt', rt #########
######### except: #########
######### print ' :0.0 local host' #########
######### rt = Tkinter.Tk(":0.0") # Use the localhost:0.0 for the DISPLAY and screen ###
######### rt.withdraw() #########
########### rt.destroy() #########
# #
#############################################################################
self._canvas_id = vcs.next_canvas_id
self.ParameterChanged = SIGNAL( 'ParameterChanged' )
vcs.next_canvas_id+=1
self.colormap = "default"
self.backgroundcolor = 255,255,255
## default size for bg
self.bgX = 814
self.bgY = 606
## displays plotted
self.display_names = []
self.info = AutoAPI.Info(self)
self.info.expose=["plot", "boxfill", "isofill", "isoline", "outfill", "outline", "scatter", "xvsy", "xyvsy", "yxvsx", "createboxfill", "getboxfill", "createisofill", "getisofill", "createisoline", "getisoline", "createyxvsx", "getyxvsx", "createxyvsy", "getxyvsy", "createxvsy", "getxvsy", "createscatter", "getscatter", "createoutfill", "getoutfill", "createoutline", "getoutline"]
ospath = os.environ["PATH"]
found = False
for p in ospath.split(":"):
if p==os.path.join(sys.prefix,"bin"):
found = True
break
if found is False:
os.environ["PATH"]=os.environ["PATH"]+":"+os.path.join(sys.prefix,"bin")
global called_initial_attributes_flg
global gui_canvas_closed
global canvas_closed
## import gui_support
import time
## from tkMessageBox import showerror
is_canvas = len(vcs.return_display_names()[0])
if gui_canvas_closed == 1:
showerror( "Error Message to User", "There can only be one VCS Canvas GUI opened at any given time and the VCS Canvas GUI cannot operate with other VCS Canvases.")
return
self.winfo_id = -99
self.varglist = []
self.canvas_gui= None
self.isplottinggridded=False
self.canvas_guianimate_info=None
# DEAN or CHARLES -- remove the one line below for VCS Canvas GUI to work
#gui = 0
if is_canvas == 0:
if ( (gui == 1) and (gui_canvas_closed == 0) ):
no_root = 0
if (gui_support.root_exists()): no_root = 1
if (no_root == 0):
parent = gui_support.root()
else:
parent = gui_support._root
self.canvas_gui = _canvasgui.CanvasGUI(canvas=self,top_parent=parent)
# Must wait for the window ID to return before moving on...
while self.winfo_id == -99: self.winfo_id = self.canvas_gui.frame.winfo_id()
if size is None:
psize = 1.2941176470588236
elif isinstance(size,(int,float)):
psize = size
elif isinstance(size,str):
if size.lower() in ['letter','usletter']:
psize = size = 1.2941176470588236
elif size.lower() in ['a4',]:
psize = size = 1.4142857142857141
else:
raise Exception, 'Unknown size: %s' % size
else:
raise Exception, 'Unknown size: %s' % size
self.size = psize
self.mode = mode
self._animate_info=[]
self.pause_time = pause_time
self._canvas = vcs
self.viewport =[0,1,0,1]
self.worldcoordinate = [0,1,0,1]
self._dotdir,self._dotdirenv = vcs.getdotdirectory()
if ( (is_canvas == 0) and (gui == 1) and (gui_canvas_closed == 0) ): gui_canvas_closed = 1
self.drawLogo = False
self.enableLogo = True
if backend == "vtk":
self.backend = VTKVCSBackend(self)
elif isinstance(backend,vtk.vtkRenderWindow):
self.backend = VTKVCSBackend(self, renWin = backend)
else:
warnings.warn("Unknown backend type: '%s'\nAssiging 'as is' to backend, no warranty about anything working from this point on" % backend)
self.backend=backend
self._animate = self.backend.Animate( self )
self.configurator = configurator.Configurator(self, show_on_update=(backend != "vtk") )
## Initial.attributes is being called in main.c, so it is not needed here!
## Actually it is for taylordiagram graphic methods....
###########################################################################################
# Okay, then this is redundant since it is done in main.c. When time perments, put the #
# taylordiagram graphic methods attributes in main.c Because this is here we must check #
# to make sure that the initial attributes file is called only once for normalization #
# purposes.... #
###########################################################################################
if called_initial_attributes_flg == 0:
pth = vcs.__path__[0].split(os.path.sep)
pth=pth[:-4] # Maybe need to make sure on none framework config
pth=['/']+pth+['share','vcs', 'initial.attributes']
try:
vcs.scriptrun( os.path.join(*pth))
except:
pass
self._dotdir,self._dotdirenv = vcs.getdotdirectory()
user_init = os.path.join(os.environ['HOME'], self._dotdir, 'initial.attributes')
if os.path.exists(user_init):
vcs.scriptrun(user_init)
else:
shutil.copy2(os.path.join(*pth),user_init)
called_initial_attributes_flg = 1
self.canvas_template_editor=None
self.ratio=0
self._user_actions_names=['Clear Canvas','Close Canvas','Show arguments passsed to user action']
self._user_actions = [self.clear, self.close, self.dummy_user_action]
def processParameterChange( self, args ):
self.ParameterChanged( args )
## Functions to set/querie drawing of UV-CDAT logo
def drawlogoon(self):
"""Turn on drawing of logo on pix"""
self.enableLogo = True
def drawlogooff(self):
"""Turn off drawing of logo on pix"""
self.enableLogo = False
def getdrawlogo(self):
"""Return value of draw logo"""
return self.enableLogo
def initLogoDrawing(self):
self.drawLogo = self.enableLogo
#############################################################################
# #
# Update wrapper function for VCS. #
# #
#############################################################################