Changeset 793


Ignore:
Timestamp:
Sep 21, 2012, 5:11:37 PM (12 years ago)
Author:
aslmd
Message:

UTIL PYTHON : a working version of MCD python on an Apache server thanks to F. Guyon and L. Fairhead. plus added specific functions in mcd.py to make plots without using GUI, it was necessary to rewrite some stuff to avoid calling to matplotlib.pyplot.

Location:
trunk/UTIL/PYTHON/mcd
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/UTIL/PYTHON/mcd/gale.py

    r761 r793  
    11#! /usr/bin/env python
     2
     3#import sys
     4#
     5#class NullDevice():
     6#    def write(self, s):
     7#        pass
     8#
     9#original_stdout = sys.stdout  # keep a reference to STDOUT
     10#
     11#sys.stdout = NullDevice()  # redirect the real STDOUT
     12#sys.stderr = NullDevice()  # redirect the real STDOUT
    213
    314from mcd import mcd
     
    1829#gale.printextvar("rho")
    1930
    20 #gale.seasonal()
    21 #gale.plot1d(["tsurf","u","v"])
     31gale.seasonal()
     32gale.plot1d(["tsurf","u","v"])
     33
     34import matplotlib.pyplot as mpl
     35mpl.savefig("temp.png",dpi=85,bbox_inches='tight',pad_inches=0.25)
     36
    2237
    2338#gale.xdate = 270.
     
    2540#gale.plot1d(["u","v"])
    2641
    27 #gale.latlon()
    28 #gale.map2d("tsurf")
     42gale.latlon()
     43gale.map2d("tsurf")
    2944
    3045import matplotlib.pyplot as mpl
    31 mpl.show()
     46#mpl.show()
     47mpl.savefig("img/temp.png",dpi=110,bbox_inches='tight',pad_inches=0.4)
  • trunk/UTIL/PYTHON/mcd/mcd.py

    r761 r793  
    1212import myplot
    1313
    14 class mcd:
    15 
     14
     15class mcd():
     16 
    1617    def __repr__(self):
    1718    # print out a help string when help is invoked on the object
     
    2728        ## 0. general stuff
    2829        self.name      = "MCD v4.3 output"
    29         self.dset      = '/home/aymeric/Science/MCD_v4.3/data/'
     30        #self.dset      = '/home/aymeric/Science/MCD_v4.3/data/'
     31        self.dset      = '/home/marshttp/MCD_v4.3/data/'
    3032        ## 1. spatio-temporal coordinates
    3133        self.lat       = 0.
     
    303305      for i in range(len(tabtodo)): mpl.subplot(subv,subh,i+1).grid(True, linestyle=':', color='grey') ; self.makeplot1d(tabtodo[i],vertplot)
    304306
     307    def htmlplot1d(self,tabtodo,vertplot=0,figname="temp.png"):
     308    ### complete 1D figure with possible multiplots
     309    ### added in 09/2012 for online MCD
     310    ### see http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
     311      from matplotlib.figure import Figure
     312      from matplotlib.backends.backend_agg import FigureCanvasAgg
     313      if isinstance(tabtodo,np.str): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
     314      if isinstance(tabtodo,np.int): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
     315      fig = Figure(figsize=(8,8)) ; subv,subh = myplot.definesubplot( len(tabtodo) , fig )
     316      for i in range(len(tabtodo)):
     317        yeah = fig.add_subplot(subv,subh,i+1) #.grid(True, linestyle=':', color='grey')
     318        choice = tabtodo[i]
     319        (field, fieldlab) = self.definefield(choice)
     320        if vertplot != 1:  absc = self.xcoord ; ordo = field ; ordolab = fieldlab ; absclab = self.xlabel
     321        else:              ordo = self.xcoord ; absc = field ; absclab = fieldlab ; ordolab = self.xlabel
     322        yeah.plot(absc,ordo,'-bo') #; mpl.xticks(query.xcoord)
     323        ax = fig.gca() ; ax.set_ylabel(ordolab) ; ax.set_xlabel(absclab)
     324      fig.text(0.5, 0.01, "Mars Climate Database (c) LMD/OU/IAA/ESA/CNES", ha='center')
     325      canvas = FigureCanvasAgg(fig)
     326      # The size * the dpi gives the final image size
     327      #   a4"x4" image * 80 dpi ==> 320x320 pixel image
     328      canvas.print_figure(figname, dpi=80)
     329
    305330###################
    306331### 2D analysis ###
     
    346371      if isinstance(tabtodo,np.str): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
    347372      if isinstance(tabtodo,np.int): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
    348       fig = mpl.figure() ; subv,subh = myplot.definesubplot( len(tabtodo) , fig )
     373      fig = mpl.figure()
     374      subv,subh = myplot.definesubplot( len(tabtodo) , fig )
    349375      for i in range(len(tabtodo)): mpl.subplot(subv,subh,i+1) ; self.makemap2d(tabtodo[i],incwind=incwind,fixedlt=fixedlt)
    350376
     377    def htmlmap2d(self,tabtodo,incwind=False,fixedlt=False,figname="temp.png"):
     378    ### complete 2D figure with possible multiplots
     379    ### added in 09/2012 for online MCD
     380    ### see http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
     381      from matplotlib.figure import Figure
     382      from matplotlib.backends.backend_agg import FigureCanvasAgg
     383      from matplotlib.cm import get_cmap
     384      if isinstance(tabtodo,np.str): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
     385      if isinstance(tabtodo,np.int): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
     386      fig = Figure(figsize=(8,8)) ; subv,subh = myplot.definesubplot( len(tabtodo) , fig )
     387
     388      ### topocontours
     389      fieldc = self.getextvar(self.convertlab("topo"))
     390
     391      for i in range(len(tabtodo)):
     392        yeah = fig.add_subplot(subv,subh,i+1)
     393        choice = tabtodo[i]
     394        self.latlon(fixedlt=fixedlt) ## a map is implicitely a lat-lon plot. otherwise it is a plot (cf. makeplot2d)
     395        (field, fieldlab) = self.definefield(choice)
     396        if incwind: (windx, fieldlabwx) = self.definefield("u") ; (windy, fieldlabwy) = self.definefield("v")
     397
     398        proj="cyl" ; colorb="jet" ; ndiv=20 ; zeback="molabw" ; trans=1.0 #0.6
     399        title="" ; vecx=None ; vecy=None ; stride=2
     400        lon = self.xcoord
     401        lat = self.ycoord
     402
     403        ### get lon and lat in 2D version. get lat/lon intervals
     404        #numdim = len(np.array(lon).shape)
     405        #if numdim == 2:     [lon2d,lat2d] = [lon,lat]
     406        #elif numdim == 1:   [lon2d,lat2d] = np.meshgrid(lon,lat)
     407        #else:               errormess("lon and lat arrays must be 1D or 2D")
     408        #[wlon,wlat] = myplot.latinterv()
     409        ### define projection and background. define x and y given the projection
     410        #m = basemap.Basemap(projection='moll') marche pas
     411        #m = myplot.define_proj(proj,wlon,wlat,back=zeback,blat=None,blon=None)
     412        #x, y = m(lon2d, lat2d)
     413        ### TEMP
     414        x = lon ; y = lat
     415        ## define field. bound field.
     416        what_I_plot = np.transpose(field)
     417        zevmin, zevmax = myplot.calculate_bounds(what_I_plot)  ## vmin=min(what_I_plot_frame), vmax=max(what_I_plot_frame))
     418        what_I_plot = myplot.bounds(what_I_plot,zevmin,zevmax)
     419        ## define contour field levels. define color palette
     420        ticks = ndiv + 1
     421        zelevels = np.linspace(zevmin,zevmax,ticks)
     422        palette = get_cmap(name=colorb)
     423        ## contours topo
     424        zelevc = np.linspace(-8000.,20000.,20)
     425        yeah.contour( x, y, np.transpose(fieldc), zelevc, colors='black',linewidths = 0.4)
     426        # contour field
     427        c = yeah.contourf( x, y, what_I_plot, zelevels, cmap = palette, alpha = trans )
     428        Figure.colorbar(fig,c,orientation='vertical',format="%.1e")
     429        ax = fig.gca() ; ax.set_title(fieldlab) ; ax.set_ylabel("Latitude") ; ax.set_xlabel("Longitude")
     430        ax.set_xticks(np.arange(-180,181,45)) ; ax.set_xbound(lower=-180, upper=180)
     431        ax.set_yticks(np.arange(-90,91,30)) ; ax.set_ybound(lower=-90, upper=90)
     432        if incwind:
     433          [x2d,y2d] = np.meshgrid(x,y)
     434          yeah.quiver(x2d,y2d,np.transpose(windx),np.transpose(windy))
     435      fig.text(0.5, 0.01, "Mars Climate Database (c) LMD/OU/IAA/ESA/CNES", ha='center')
     436      canvas = FigureCanvasAgg(fig)
     437      # The size * the dpi gives the final image size
     438      #   a4"x4" image * 80 dpi ==> 320x320 pixel image
     439      canvas.print_figure(figname, dpi=80)
     440
     441
    351442    ### TODO: makeplot2d, plot2d, passer plot settings
    352443
  • trunk/UTIL/PYTHON/mcd/proto/cgi-bin/mcdcgi.py

    r761 r793  
    1 #!/home/aymeric/Software/epd-7.0-2-rh5-x86/bin/python
     1#!/usr/bin/python
     2###!/home/aymeric/Software/epd-7.0-2-rh5-x86/bin/python
     3####!/home/marshttp/EPD/epd-7.0-2-rh5-x86_64/bin/python
    24### here the version used to f2py the MCD Fortran routines
    35
     
    911### (see mcdtest.py for examples of use)       ###
    1012##################################################
     13### ajouts et corrections par Franck Guyon 09/2012
    1114
    1215import cgi, cgitb
    1316import numpy as np
    14 from mcd import mcd
     17#from mcd import mcd
     18from modules import *
     19from modules import mcd
     20
    1521import cStringIO
    1622import os as daos
    1723import matplotlib.pyplot as mpl
    18 import Image
     24from PIL import Image
    1925
    2026# for debugging in web browser
     
    2531
    2632# create a MCD object
    27 query = mcd()
     33#query = mcd()
     34query=mcd.mcd() #FG: import from module mcd
    2835
    2936# Get data from user-defined fields and define free dimensions
     37# FG: add tests if var==None to have values in local without forms ones
    3038getlat = form.getvalue("latitude")
     39if getlat == None: getlat = 1
     40
    3141if getlat == "all":  islatfree = 1 ; query.lat = -9999.
    3242else:                islatfree = 0 ; query.lat = float(getlat)
    3343getlon = form.getvalue("longitude")
     44if getlon == None: getlon = 1
    3445if getlon == "all":  islonfree = 1 ; query.lon = -9999.
    3546else:                islonfree = 0 ; query.lon = float(getlon)
     47
    3648getloct = form.getvalue("localtime")
     49
     50if getloct == None: getloct = 1
    3751if getloct == "all": isloctfree = 1 ; query.loct = -9999.
    3852else:                isloctfree = 0 ; query.loct = float(getloct)
     53
    3954getalt = form.getvalue("altitude")
     55if getalt == None: getalt = 1
    4056if getalt == "all":  isaltfree = 1 ; query.xz = -9999.
    4157else:                isaltfree = 0 ; query.xz = float(getalt)
     58
    4259sumfree = islatfree + islonfree + isloctfree + isaltfree
    4360if sumfree > 2: exit() ## only 1D or 2D plots for the moment
    44 query.xdate = float(form.getvalue("ls"))
    45 query.hrkey = int(form.getvalue("hrkey"))
    46 query.dust = int(form.getvalue("dust"))
     61
     62try: query.xdate = float(form.getvalue("ls"))
     63except: query.xdate = float(1)
     64try: query.hrkey = int(form.getvalue("hrkey"))
     65except: query.hrkey = int(1)
     66try: query.dust = int(form.getvalue("dust"))
     67except: query.dust  = int(1)
    4768#        self.zkey      = 3  # specify that xz is the altitude above surface (m)
    4869#        self.perturkey = 0  #integer perturkey ! perturbation type (0: none)
     
    5576var3 = form.getvalue("var3")
    5677var4 = form.getvalue("var4")
    57 vartoplot = [var1]
     78
     79# fg: vartoplot is not None without form values
     80# vartoplot = [var1]
     81# fg: init var as with form values
     82if var1 == None: var1="t"
     83if var2 == None: var2="p"
     84
     85vartoplot = []
     86if var1 != "none": vartoplot = np.append(vartoplot,var1)
    5887if var2 != "none": vartoplot = np.append(vartoplot,var2)
    59 if var3 != "none": vartoplot = np.append(vartoplot,var3)
    60 if var4 != "none": vartoplot = np.append(vartoplot,var4)
     88if var3 != "none" and var3 != None: vartoplot = np.append(vartoplot,var3)
     89if var4 != "none" and var4 != None: vartoplot = np.append(vartoplot,var4)
     90
    6191iswind = form.getvalue("iswind")
    6292if iswind == "on": iswindlog = True
     
    6898# reference name (to test which figures are already in the database)
    6999reference = str(islatfree)+str(islonfree)+str(isloctfree)+str(isaltfree)+query.getnameset()+str(var1)+str(var2)+str(var3)+str(var4)+str(iswind)+str(isfixedlt)
    70 figname = 'img/'+reference+'.jpg'
     100figname = '../img/'+reference+'.png'
     101
    71102testexist = daos.path.isfile(figname)
    72103
     
    85116
    86117    ### generic building of figure
    87     #query.plot1d(["t","p","u","v"],vertplot=isaltfree)
    88     query.plot1d(vartoplot,vertplot=isaltfree)
    89     mpl.savefig("img/temp.png",dpi=85,bbox_inches='tight',pad_inches=0.25)
    90     Image.open("img/temp.png").save(figname,'JPEG')
     118    query.htmlplot1d(vartoplot,vertplot=isaltfree,figname=figname)
     119    #mpl.savefig("img/temp.png",dpi=85,bbox_inches='tight',pad_inches=0.25)
     120    #Image.open("../img/temp.png").save(figname,'JPEG')
    91121
    92122  ### 2D plots
     
    104134
    105135## This is quite common
    106 print "Content-type:text/html\r\n\r\n"
    107 print "<html>"
    108 print "<head>"
    109 print "<title>MCD. Simple Python interface</title>"
    110 print "</head>"
    111 print "<body>"
     136print "Content-type:text/html\n"
     137print "  "  #Apache needs a space after content-type
     138
     139#entete="""<?xml version="1.0" encoding="UTF-8"?>
     140#<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd">
     141#<html xmlns="http://www.w3.org/1999/xhtml"> """
     142
     143header="""<html><head><title>Mars Climate Database: The Web Interface</title></head><body>"""
     144
     145print header
    112146
    113147## Now the part which differs
    114148if sumfree == 0:        query.update() ; query.htmlprinttabextvar(vartoplot)  #query.printmeanvar()
    115 elif sumfree >= 1:      print "<img src='../"+figname+"'><br />"
    116 else:                   exit()
     149elif sumfree >= 1:      print "<img src='"+figname+"'><br />"
     150else:                   print "<h1>ERROR : sumfree is not or badly defined ...</h1></body></html>"
     151
    117152
    118153## This is quite common
    119 #print "Based on the <a href='http://www-mars.lmd.jussieu.fr'>Mars Climate Database</a> (c) LMD/OU/IAA/ESA/CNES.<br />"
    120 print "<hr>"
    121 print "<a href='../index.html'>Click here to start a new query</a>."
    122 #query.printset()
    123 print "<hr>"
    124 print "</body>"
    125 print "</html>"
     154bottom = "<hr><a href='../index.html'>Click here to start a new query</a>.<hr></body></html>"
     155print bottom
    126156
    127157##write to file object
  • trunk/UTIL/PYTHON/mcd/proto/index.html

    r781 r793  
    1515<!-- aussi possible: get a la place de post. pour avoir un beau lien -->
    1616
     17<!--<form name="calendar" action="/marscgi-bin/mcdcgi.py" method="post"> <!--target="_new">-->
    1718<form name="calendar" action="./cgi-bin/mcdcgi.py" method="post"> <!--target="_new">-->
    1819
     
    315316<td align="center">
    316317<input type="submit" value="SUBMIT" style="font-weight:bold"/>
     318<input type="button" value="RESET" style="font-weight:bold" onClick="DefaultDateValues();DefaultTimeValues();Convert2Ls();PlaceValues(0.,0.);DefaultSpaceTime()"/><br />
    317319</td>
    318320<td align="center">
Note: See TracChangeset for help on using the changeset viewer.