Changeset 2250 in lmdz_wrf for trunk/tools/drawing_tools.py


Ignore:
Timestamp:
Nov 27, 2018, 7:49:55 PM (6 years ago)
Author:
lfita
Message:

Adding:

  • `draw_river_pattern: Function to plot rivers' patterns from ORCHIDEE's routing scheme file ('routing.nc' and 'river_desc.nc')
  • Fixing other issues
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/drawing_tools.py

    r2248 r2250  
    189189# plot_lines: Function to plot a collection of lines
    190190# plot_multiWindRose: Function to plot multi wind roses (from where the dinw blows)
     191# plot_river_pattern: Function to plot ORCHIDEE's pattern or rivers (following trip
     192#    variable from 'routing.nc' and river description following 'river_desc.nc')
    191193# plot_SkewT: Function to plot a SkewT-logP diagram using matplotlib's API example
    192194# plot_stations_map: Function to plot a map with a series of stations
     
    18221824def legend_values(legstring, char):
    18231825    """ Function to determine the values for the legend
    1824       legstring= char separated list of [locleg][char][fontsize]:
     1826      legstring= [char] separated list of [locleg][char][fontsize][char][ncol]:
    18251827          [locleg]: location of the legend (0, automatic)
    18261828            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     
    75847586  stn, stlon, stlat, drawcountry, drawbasinid, colordescid, coloriver, colornoriver, \
    75857587  colorst, stsize, graphtit, mapv, kfig, figname):
    7586     """ Function to plot vectors
     7588    """ Function to plot ORCHIDEE's pattern of one river (following trip variable from
     7589        'routing.nc' and river description following 'river_desc.nc')
    75877590      xvals= values for the x-axis
    75887591      yvals= values for the y-axis
     
    75907593      veccolor= basin id
    75917594      descid= description id
    7592 , desclon, desclat,
     7595      desclon= longitude of description
     7596      desclat= latitude of description
     7597      stn= name of the stations
     7598      stlon= longitude of the stations
     7599      stlat= latitude of the stations
    75937600      mapv= map characteristics: [proj],[res]
    75947601        see full documentation: http://matplotlib.org/basemap/
     
    76047611      drawcountry= whether country lines should be plotted or not
    76057612      drawbasinid= whether basins id should be plotted or not
     7613      colordescid= color map for the id of the rivers
     7614      coloriver= color for the non-selected rivers in the plot
     7615      colornoriver= color for the non-river paths values
     7616      colorst= color for the stations
     7617      stsize= color for the size of the labels of the stations
    76067618      graphtit= title of the graph ('|', for spaces)
    76077619      kfig= kind of figure
     
    77947806
    77957807    return
     7808
     7809def plot_multi_river_pattern(xvals, yvals, fvals, veccolor, descids, desclon,        \
     7810  desclat, stn, stlon, stlat, drawcountry, drawbasinid, colordescid, coloriver,      \
     7811  colornoriver, pathwidth, colorst, stsize, graphtit, mapv, kfig, riverns):
     7812    """ Function to plot ORCHIDEE's pattern or multiple rivers (following trip variable from
     7813        'routing.nc' and river description following 'river_desc.nc')
     7814      xvals= values for the x-axis
     7815      yvals= values for the y-axis
     7816      fvals= values for the flow (1-8: N, NE, E, ..., NW; 97: sub-basin; 98: small to sea; 99: large to sea)
     7817      veccolor= basin id
     7818      descids= dictionary with the description of each river
     7819      desclon= longitude of description
     7820      desclat= latitude of description
     7821      stn= name of the stations
     7822      stlon= longitude of the stations
     7823      stlat= latitude of the stations
     7824      mapv= map characteristics: [proj],[res]
     7825        see full documentation: http://matplotlib.org/basemap/
     7826        [proj]: projection
     7827          * 'cyl', cilindric
     7828          * 'lcc', lambert conformal
     7829        [res]: resolution:
     7830          * 'c', crude
     7831          * 'l', low
     7832          * 'i', intermediate
     7833          * 'h', high
     7834          * 'f', full
     7835      drawcountry= whether country lines should be plotted or not
     7836      drawbasinid= whether basins id should be plotted or not
     7837      colordescid= color map for the id of the rivers
     7838      coloriver= color for the non-selected rivers in the plot
     7839      colornoriver= color for the non-river paths values
     7840      pathwidth= width of the line with the river paths
     7841      colorst= color for the stations
     7842      stsize= color for the size of the labels of the stations
     7843      graphtit= title of the graph ('|', for spaces)
     7844      kfig= kind of figure
     7845      riverns= list with the name of the rivers to be plotted
     7846    """
     7847    fname = 'plot_multi_river_pattern'
     7848
     7849    figname = 'multi_river_pattern'
     7850
     7851    dx=xvals.shape[1]
     7852    dy=xvals.shape[0]
     7853    xmin = np.min(xvals)
     7854    xmax = np.max(xvals)
     7855    ymin = np.min(yvals)
     7856    ymax = np.max(yvals)
     7857
     7858# flow direction
     7859
     7860    plt.rc('text', usetex=True)
     7861
     7862    ddx = np.abs(xvals[dy/2+1,dx/2] - xvals[dy/2,dx/2])
     7863    ddy = np.abs(yvals[dy/2,dx/2+1] - yvals[dy/2,dx/2])
     7864    fontcharac = {'family': 'serif', 'weight': 'normal', 'size': 3}
     7865
     7866    xlabpos = []
     7867    ylabpos = []
     7868    labels = []
     7869    labcol = []
     7870    flow = []
     7871    flowvals = []
     7872    xtrack = []
     7873    ytrack = []
     7874    colortrack = []
     7875    trackid = []
     7876    stnlL = []
     7877    stlonlL = []
     7878    stlatlL = []
     7879
     7880# Setting up colors for each label
     7881#   From: http://stackoverflow.com/questions/15235630/matplotlib-pick-up-one-color-associated-to-one-value-in-a-colorbar
     7882    my_cmap = plt.cm.get_cmap(colordescid)
     7883    vcolmin = np.min(descids.values())
     7884    vcolmax = np.max(descids.values())
     7885
     7886    norm = mpl.colors.Normalize(vcolmin, vcolmax)
     7887
     7888# Vector angles
     7889    lengthtrac = np.float(xvals[0,1] - xvals[0,0])
     7890    lengthtrac2 = lengthtrac*np.sqrt(2.)
     7891
     7892    print '  ' + fname + ': getting colors for the river-paths ...'
     7893    for j in range(0,dy):
     7894        for i in range(0,dx):
     7895            if veccolor[j,i] != '--':
     7896#                ibeg = xvals[j,i]-lengthtrac/2.
     7897#                jbeg = yvals[j,i]-lengthtrac/2.
     7898                ibeg = xvals[j,i]
     7899                jbeg = yvals[j,i]
     7900                labels.append(int(veccolor[j,i]))
     7901                flowvals.append(fvals[j,i])
     7902                angle = (fvals[j,i] - 1)*np.pi/4
     7903                if gen.searchInlist([2,4,6,8], fvals[j,i]):
     7904                    iend = ibeg + lengthtrac2*np.sin(angle)
     7905                    jend = jbeg + lengthtrac2*np.cos(angle)
     7906                elif gen.searchInlist([1,3,5,7], fvals[j,i]):
     7907                    iend = ibeg + lengthtrac*np.sin(angle)
     7908                    jend = jbeg + lengthtrac*np.cos(angle)
     7909                else:
     7910                    ibeg = xvals[j,i]
     7911                    jbeg = yvals[j,i]
     7912                    iend = None
     7913                    jend = None
     7914
     7915                xlabpos.append(ibeg)
     7916                ylabpos.append(jbeg)
     7917                xtrack.append(ibeg)
     7918                xtrack.append(iend)
     7919                xtrack.append(None)
     7920                ytrack.append(jbeg)
     7921                ytrack.append(jend)
     7922                ytrack.append(None)
     7923                if len(desclon.shape) == 2:
     7924                    difflonlat = np.sqrt((desclon-xvals[j,i])**2 + (desclat-yvals[j,i])**2)
     7925                    mindiffLl = np.min(difflonlat)
     7926                    ilatlon = gen.index_mat(difflonlat, mindiffLl)
     7927                else:
     7928                    ilatlon = np.zeros((2), dtype=int)
     7929                    difflon = np.abs(desclon - xvals[j,i])
     7930                    mindiffl = np.min(difflon)
     7931                    ilatlon[1] = gen.index_vec(difflon,mindiffl)
     7932                    difflat = np.abs(desclat - yvals[j,i])
     7933                    mindiffL = np.min(difflat)
     7934                    ilatlon[0] = gen.index_vec(difflat,mindiffL)
     7935
     7936                if not gen.searchInlist(descids.values(), veccolor[j,i]):
     7937                    labcol.append(colornoriver)
     7938                    colortrack.append(colornoriver)
     7939#                        print 'Lluis: veccol:', veccolor[j,i], 'mindiffl', mindiffl,'mindiffL:',mindiffL
     7940                else:
     7941#                        print 'Lluis right! mindiffl', mindiffl,'mindiffL:',mindiffL
     7942                    labcol.append(coloriver)
     7943                    colortrack.append(my_cmap(norm(veccolor[j,i])))
     7944
     7945                trackid.append(veccolor[j,i])
     7946
     7947    totvals = len(flowvals)
     7948
     7949    if not mapv is None:
     7950        lon00 = np.where(xvals[:] < 0., 360. + xvals[:], xvals[:])
     7951        lat00 = yvals[:]
     7952
     7953        map_proj=mapv.split(',')[0]
     7954        map_res=mapv.split(',')[1]
     7955
     7956        nlon = np.min(xvals)
     7957        xlon = np.max(xvals)
     7958        nlat = np.min(yvals)
     7959        xlat = np.max(yvals)
     7960
     7961        lon2 = xvals[dy/2,dx/2]
     7962        lat2 = yvals[dy/2,dx/2]
     7963
     7964        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
     7965          xlon, ',', xlat
     7966
     7967        if map_proj == 'cyl':
     7968            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
     7969              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
     7970        elif map_proj == 'lcc':
     7971            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
     7972              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
     7973        else:
     7974            print errormsg
     7975            print '  ' + fname + ": projection '" + map_proj + "' not ready!!"
     7976            print '    projections available: cyl, lcc'
     7977            quit(-1)
     7978
     7979        m.drawcoastlines()
     7980        drawcountry = True
     7981        if drawcountry: m.drawcountries()
     7982
     7983        meridians = gen.pretty_int(nlon,xlon,5)
     7984        m.drawmeridians(meridians,labels=[True,False,False,True],color="black")
     7985
     7986        parallels = gen.pretty_int(nlat,xlat,5)
     7987        m.drawparallels(parallels,labels=[False,True,True,False],color="black")
     7988
     7989    Npaths = len(xlabpos)
     7990    print '  ' + fname + ' plotting ', Npaths ,'river-paths ...'
     7991    j = 0
     7992    for i in range(Npaths):
     7993        gen.percendone(i,Npaths,5.,'  ' + fname + ': drawn')
     7994        plt.plot(xtrack[j:j+2], ytrack[j:j+2], color=colortrack[i],                  \
     7995          linewidth=pathwidth)
     7996        j = j + 3
     7997
     7998# Sea-flow
     7999    for i in range(len(xlabpos)):
     8000        if flowvals[i] == 97:
     8001            plt.plot(xlabpos[i], ylabpos[i], 'x', color=colortrack[i],               \
     8002              markersize=lengthtrac2)
     8003        elif flowvals[i] == 98:
     8004            plt.plot(xlabpos[i], ylabpos[i], '*', color=colortrack[i],               \
     8005              markersize=lengthtrac2)
     8006        elif flowvals[i] == 99:
     8007            plt.plot(xlabpos[i], ylabpos[i], 'h', color=colortrack[i],               \
     8008              markersize=lengthtrac2)
     8009
     8010    plt.xlim(xmin,xmax)
     8011    plt.ylim(ymin,ymax)
     8012
     8013    if drawbasinid:
     8014        print '  ' + fname + ' drawing basins ids ...'
     8015        idlabelled = []
     8016        for i in range(len(xlabpos)):
     8017            if not gen.searchInlist(idlabelled, labels[i]):
     8018                plt.text(xlabpos[i]+0.05*lengthtrac, ylabpos[i]+0.05*lengthtrac,     \
     8019                  labels[i], color=labcol[i], fontdict=fontcharac)
     8020                idlabelled.append(labels[i])
     8021               
     8022#            plt.text(xlabpos[i]+0.1*lengthtrac, ylabpos[i]+0.1*lengthtrac, trackid[i],   \
     8023#              color=colortrack[i], fontdict=fontcharac)
     8024#            plt.text(xlabpos[i]+0.1*lengthtrac, ylabpos[i]+0.1*lengthtrac, str(flowvals[i]),   \
     8025#              color=colortrack[i], fontdict=fontcharac)
     8026
     8027    if stn is not None:
     8028        for ist in range(len(stlon)):
     8029            if stlon[ist] > xmin and stlon[ist] < xmax and stlat[ist] > ymin and     \
     8030              stlat[ist] < ymax:
     8031                stname = '*'
     8032                for ic in range(len(stn[ist,:])):
     8033                    stname  = stname + stn[ist,ic]
     8034#            plt.annotate(stname, xy=(stlon[ist],stlat[ist]), color=colorst, )
     8035                plt.text(stlon[ist], stlat[ist], stname, color=colorst, fontsize=stsize)
     8036
     8037#    cbar = plt.colorbar()
     8038    plt.title(graphtit.replace('&','\&'))
     8039
     8040    output_kind(kfig, figname, True)
     8041
     8042    return
     8043
    77968044
    77978045def var_3desc(ovar):
Note: See TracChangeset for help on using the changeset viewer.