source: TI03-DataExtractor/branches/old_stuff/visualisor.py @ 793

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI03-DataExtractor/branches/old_stuff/visualisor.py@793
Revision 793, 11.8 KB checked in by astephen, 13 years ago (diff)

Put all the old code in the old_stuff branch.

  • Property svn:executable set to *
Line 
1#!/usr/local/cdat/bin/python
2
3"""
4visualisor2.py
5==========
6
7Main module for the vis package.
8
9This module holds the main function that is used
10to control a user options and visualisation.
11
12Version history
13===============
14
15Version 1.0:  - 11/06/2004
16              - Ag Stephens, British Atmospheric Data Centre.
17              - First version.
18
19"""
20
21# Import required modules
22import string
23import sys
24# Add your location path for the dx module
25sys.path.append("/usr/local")
26sys.path.insert(0, "/usr/local/badcdat/lib")
27sys.path.insert(0, "/usr/local/badcdat/lib/python")
28
29import os
30os.environ["HOME"]="/home/tornado/internal/badc"
31
32import time
33import cgi
34import commands
35
36# Set up cgi error reporting to screen
37import cgitb
38cgitb.enable()
39
40# Set global variables
41filebase="/var/www/html/nctemp/vis."
42wwwfilebase="/nctemp/vis."
43extMap={"GIF":"gif", "PNG":"png", "JPEG":"jpg", "Postscript":"ps", "CGM":"cgm"}
44
45def exitNicely(message):
46    pass
47
48
49def displayError(error):
50    print "<HTML><HEAD><HEAD><BODY><H2>ERROR:</H2><B>%s</B></BODY></HTML>" % error
51         
52
53def getBADCTemplate(canvas, data):
54    if not data.getLevel():
55      template=canvas.gettemplate('BADC_ERA40_NOLEV')
56    else:
57      template=canvas.gettemplate('BADC_ERA40')
58    return template
59
60def getBADCMolwd(canvas,data):
61    if not data.getLevel():
62      template=canvas.gettemplate('BADC_ERA40_NL_m')
63    else:
64      template=canvas.gettemplate('BADC_ERA40_molwd')
65    return template
66
67def plotProjection(canvas,data, projection):
68# Run VCS script that contains the appropriate VCS templates,
69# graphics methods, and color maps
70
71    #canvas.scriptrun( '/opt/ukmo/utils/supported/linux_only/cdat/bin/ASD.scr' )
72    canvas.setcolormap('ASD')
73    canvas.mode = 0
74
75# Create a dictionary that will contain the defined
76
77# The equivalent slicing of the slab can be done with longitude
78# and latitude coordinate values, but the 'by' or stride functionality
79# is omitted when using coordinate values. For example:
80#
81# no10u=fid2( 'no10u', slice(0, 1, 1), latitude = (-90, 90), longitude = (0, 359), squeeze = 0, order = '012' )
82
83# Squeeze the slab
84    data = data.subRegion( squeeze=1 )
85
86# Alter the Plot's Appearance
87   
88    templ = canvas.gettemplate('molwd')
89    templ.xlabel1.priority=1
90    templ.xlabel2.priority=0
91    templ.xtic1.priority=1
92    templ.xtic2.priority=0
93    templ.xmintic1.priority=0
94    templ.xmintic2.priority=0
95    templ.ylabel1.priority=1
96    templ.ylabel2.priority=0
97    templ.ytic1.priority=1
98    templ.ytic2.priority=0
99    templ.ymintic1.priority=0
100    templ.ymintic2.priority=0
101    templ.legend.x1=0.074999999999999997
102    templ.legend.x2=0.92700000000000005
103    templ.legend.y1=0.14000000000000001
104    templ.legend.y2=0.17000000000000001
105    templ.data.x1=0.074999999999999997
106    templ.data.x2=0.92700000000000005
107    templ.data.y1=0.28199999999999997
108    templ.data.y2=0.84999999999999998
109    templ.source.y=0.93999999999999995
110    templ.dataname.y=0.91000000000000003
111    templ.title.y=0.91000000000000003
112    templ.units.y=0.91000000000000003
113    templ.comment1.y=0.91000000000000003
114    templ.comment2.y=0.91000000000000003
115    templ.comment3.y=0.91000000000000003
116    templ.comment4.y=0.085000000000000006
117    templ.crdate.y=0.91000000000000003
118    templ.crtime.y=0.91000000000000003
119    templ.xlabel1.y=0.26199999999999996
120    templ.ylabel1.x=0.064000000000000001
121    templ.xlabel2.y=0.87
122    templ.ylabel2.x=0.93800000000000006
123    templ.xtic1.y1=0.28199999999999997
124    templ.xtic1.y2=0.26999999999999996
125    templ.ytic1.x1=0.074999999999999997
126    templ.ytic1.x2=0.065000000000000002
127    templ.xtic2.y1=0.84999999999999998
128    templ.xtic2.y2=0.86199999999999999
129    templ.ytic2.x1=0.92700000000000005
130    templ.ytic2.x2=0.93700000000000006
131    templ.xname.x=0.50952000000000008
132    templ.xname.y=0.23199999999999998
133    templ.yname.x=0.009999999999999995
134    templ.yname.y=0.56600000000000006
135
136# Set Boxfill Method Attributes
137    g_method = canvas.getboxfill('ASD')
138    g_method.projection = projection
139    g_method.legend={0.0: '0', 16.0: '16', 4.0: '4', 8.0: '8', -20.0: '-20', 12.0: '12', -16.0: '-16', 24.0: '24', -12.0: '-12', -8.0: '-8', 20.0: '20', -4.0: '-4'}
140
141# View Annotated Plot or Not
142
143    templ = canvas.gettemplate('ASD')
144    templ.source.priority=1
145    templ.dataname.priority=1
146    templ.title.priority=1
147    templ.units.priority=1
148    templ.crdate.priority=1
149    templ.crtime.priority=1
150    templ.xvalue.priority=1
151    templ.yvalue.priority=1
152    templ.zvalue.priority=1
153    templ.tvalue.priority=1
154    templ.mean.priority=1
155    templ.min.priority=1
156    templ.max.priority=1
157    templ.file.priority=1
158    templ.comment1.priority=1
159    templ.comment2.priority=1
160    templ.comment3.priority=1
161    templ.comment4.priority=1
162
163# Clear the VCS Canvas
164    canvas.clear( )
165
166# Plot Slab
167    if projection=="linear":
168        canvas.plot(data)
169    else:
170        canvas.plot( data, 'molwd', 'Boxfill', 'ASD', comment1='',comment2='',file_comment='', name=data.id, long_name=data.name, units="", xname='longitude', yname='latitude', continents=None, yrev=0, bg=0 )
171    return
172
173def  cdatPlot(file):
174    import cdms
175    f=cdms.open(file)
176    var=f(f.variables.keys()[0])
177    import vcs
178    canvas=vcs.init()
179    canvas.plot(var, bg=1)
180    canvas.gif(outfile)
181    return wwwoutfile
182
183
184def main(args):
185
186    if args==None:
187        args={}
188        form=cgi.FieldStorage()
189       
190        for key in form.keys():
191            args[key]=form.getvalue(key)
192
193#    print "Content-Type: text/html\n\n"
194#    print args
195
196    # args now holds the input arguments (from CGI or command line)
197       
198
199    print http_header   
200    print header
201    print '<form action="visualisor.py" method="GET">'
202
203    if args.has_key("fileURI"):
204        print """<P><B>Data file:</B>   %s&nbsp;&nbsp;&nbsp;
205        <B>[ <A HREF="%s">Download</A> ]</B>""" % (args["fileURI"], args["fileURI"])
206    else:
207        print '<P><B>Data file:</B>  <input type="text" name="fileURI" size="80">'
208
209    if args.has_key("type"):
210        for key in ("Type", "Format", "Projection"):
211            print "<BR><B>%s:</B>    %s" % (key, args[key.lower()])
212        # Then do plot
213        print "<P>Plotting your data...<P>"
214        sys.stdout.flush()
215        file=args["fileURI"]
216        import cdms
217        f=cdms.open(file)
218        vars=f.variables.keys()
219        for var in vars:
220            if var[:7]!="bounds_" and var not in ("latitude", "longitude", "level", "time"):
221                varname=var
222                break
223        data=f(varname)
224        import vcs
225        canvas=vcs.init()
226        outfile=filebase+extMap[args["format"]]
227        wwwoutfile=wwwfilebase+extMap[args["format"]]
228        if os.path.isfile(outfile): os.unlink(outfile)
229
230
231        if args["type"]=="Animation":
232            time_axis = data.getTime()
233            lev_axis = data.getLevel()
234            lat_axis = data.getLatitude()
235            lon_axis = data.getLongitude()
236
237            loop_num=1
238            if not time_axis==None:
239               loop_flg = 'time'
240               loop_num = len(time_axis)
241            if loop_num==1 and not lev_axis==None:
242               loop_num = len(lev_axis)
243               loop_flg = 'level'
244            if loop_num==1 and not lat_axis==None:
245               loop_num=len(lat_axis)
246               loop_flag='lat'
247            if loop_num==1 and not lon_axis==None:
248               loop_num=len(lon_axis)
249               loop_flag='lon'
250
251            for i in range(loop_num):
252                canvas.clear()
253                if loop_flg == 'time':
254                    template=getBADCTemplate(canvas, data)
255                    canvas.plot( data( time=slice(i,i+1) ), template, bg=1, file_comment="Data source: BADC")
256                elif loop_flg=="level":
257                    template=getBADCTemplate(canvas, data)
258                    canvas.plot( data( level=slice(i,i+1) ), template, bg=1, file_comment="Data source: BADC")
259                canvas.gif(outfile)
260        else:
261          if args["projection"]=="Standard":
262            plotProjection(canvas, data, "linear")
263            #template=getBADCTemplate(canvas, data)
264            #canvas.plot(data, template, bg=1)
265          elif args["projection"]=="Mollweide":
266            #template=getBADCMolwd(canvas, data)
267            plotProjection(canvas, data, "mollweide")
268          elif args["projection"]=="Polar (Northern Hemisphere)":
269            data=data(latitude=(90,0))
270            plotProjection(canvas, data, "polar")
271          elif args["projection"]=="Polar (Southern Hemisphere)":
272            data=data(latitude=(-90,0))
273            plotProjection(canvas, data, "polar")
274          elif args["projection"]=="Robinson":
275            plotProjection(canvas, data, "robinson")
276 
277
278        #canvas.plot(data, template, bg=1)
279
280        if args["format"]=="GIF":
281            canvas.gif(outfile)
282        elif args["format"]=="Postscript":
283            canvas.postscript(outfile)
284        elif args["format"]=="CGM":
285            canvas.cgm(outfile)
286
287        print "<P>Request processed...<P>"
288        if args["format"]=="GIF":  print """<IMG SRC="%s" BORDER="1">""" % wwwoutfile
289        print """<P><A HREF="%s">Click here to download plot in %s format</A>""" % (wwwoutfile, args["format"])
290        print """<P><B><A HREF="%s">Click here to download data file.</A></B><P>""" % args["fileURI"]
291    else:
292        print """
293<table width="100%" height="39"><tbody><tr class="tablerow"><td height="35">OUTPUT
294        SELECTIONS
295  <p><b><font face="Arial">Type:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
296  <select size="1" name="type" onChange="alter2()">
297    <option selected>Plot</option>
298    <option>Animation</option>
299  </select></font></b></p>
300  <p><b><font face="Arial">Format:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
301  <select size="1" name="format">
302    <option selected>GIF</option>
303    <option>Postscript</option>
304    <option>CGM</option>
305  </select></font></b></p>
306  <p><b><font face="Arial">Projection:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
307  <select size="1" name="projection" onChange="alter3()">
308    <option selected>Standard</option>
309    <option>Mollweide</option>
310    <option>Polar (Northern Hemisphere)</option>
311    <option>Polar (Southern Hemisphere)</option>
312    <option>Robinson</option>
313  </select></font></b></p>"""
314        if args.has_key("fileURI"):  print '<input type="hidden" name="fileURI" value="%s">' % args["fileURI"]
315        print """<p><input type="submit" value="Submit"><input type="reset" value="Reset"></p>
316   </form>
317</table>
318"""
319
320    print footer
321    return
322   
323
324http_header="Content-Type: text/html\n\n"
325
326header="""<HTML>
327<HEAD>
328<TITLE>BADC Data Visualisor</TITLE>
329
330<link href="/dx_extra/styles/home.css" rel="stylesheet" type="text/css">
331
332<SCRIPT language="Javascript">
333
334</SCRIPT>
335
336</HEAD>
337<BODY text="#000000" bgcolor="#ffffff" link="#191970" vlink="#551A8A" alink="FE0000" topmargin="10" leftmargin="10" marginwidth="10" marginheight="10" >
338
339<table border="1" cellpadding="0" cellspacing="0" width="100%">
340   <tr>
341        <td height="81">
342          <table width="100%" height="117%" border="0" cellpadding="2" cellspacing="1">
343        <tr align="center">
344             
345          <td width="10%" height="100%" align="left" valign="middle"><img src="/graphics/logos/badc-logo-60.png">
346          </td>
347                          <td width="78%" valign="middle" ><strong><font color="#CC3333" size="+2" face="Courier New,
348Courier, mono">BADC Data Visualisor</font></strong></td>
349                         
350          <td width="12%" height="100%" align="left" valign="top"><img src="/graphics/logos/ncas_new_logo.jpg">
351          </td>
352                        </tr>
353         </table>
354   </td></tr>
355</table>
356
357"""
358
359footer="""<P><HR ALIGN="CENTER">
360<P>Contact <A HREF="mailto:badc@rl.ac.uk">BADC Support</A> if you have any problems with this service.
361<P>
362</BODY>
363</HTML>
364"""
365
366
367       
368if __name__=="__main__":
369    args={}
370   
371    if len(sys.argv)>1:   # use command line args to test
372        for arg in sys.argv[1:]:
373            (key, value)=arg.split("=")
374            args[key]=value
375    else:
376        args=None
377
378    main(args)
Note: See TracBrowser for help on using the repository browser.