Changeset 826 in lmdz_wrf for trunk/tools


Ignore:
Timestamp:
Jun 14, 2016, 7:24:36 PM (9 years ago)
Author:
lfita
Message:

Almost working `draw_subbasin'

Location:
trunk/tools
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/drawing.py

    r801 r826  
    3131## e.g. # drawing.py -o draw_river_desc -f diver_desc.nc -S 'Y|lat|lat|-1,X|lon|lon|-1:red,green:Blues:cyl,l:ORCDHIEE rivers:pdf:0:or_rivers -v Amazon
    3232## e.g. # drawing.py -o draw_vertical_levels -f wrfout_d01_2001-11-11_00:00:00 -S 'true:false:wrfout!vertical!levels!(standard!40):png:4' -v WRFz
     33## e.g. $ drawing.py -o draw_subbasin -f Caceres_subbasin.nc -S 'Caceres:None:cyl,l:True:Caceres:pdf:0:Caceres_subbasin'
    3334
    3435main = 'drawing.py'
     
    4344  'draw_lines', 'draw_lines_time', 'draw_Neighbourghood_evol',                       \
    4445  'draw_points', 'draw_points_lonlat',                                               \
    45   'draw_ptZvals', 'draw_river_desc', 'draw_timeSeries',                              \
     46  'draw_ptZvals', 'draw_river_desc', 'draw_subbasin', 'draw_timeSeries',             \
    4647  'draw_topo_geogrid',                                                               \
    4748  'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories',          \
     
    39843985    return
    39853986
     3987def draw_subbasin(ncfile, values):
     3988    """ Function to plot subbasin from 'routnig.nc' ORCDHIEE
     3989      ncfile= file to use produced with nc_var.py#subbasin function
     3990      values= [subasiname]:[rangecolors]:[mapv]:[drawsubid]:[gtit]:[figkind]:[legloc]:[figurename]
     3991        [subasiname]= name of the subbasin ('!' for spaces)
     3992        [rcolor]= '@', list of 'r|g|b' 1-based colors (as much as first level sub-flow). 'None' for automatic
     3993        [mapv]= map characteristics: [proj],[res]
     3994          see full documentation: http://matplotlib.org/basemap/
     3995          [proj]: projection
     3996            * 'cyl', cilindric
     3997            * 'lcc', lambert conformal
     3998          [res]: resolution:
     3999            * 'c', crude
     4000            * 'l', low
     4001            * 'i', intermediate
     4002            * 'h', high
     4003            * 'f', full
     4004        [drawsubid]= wehther sub-flow ids should be plot or not
     4005        [graphtit]= title of the graph ('|', for spaces)
     4006        [lloc]= location of the legend (0, automatic)
     4007          1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     4008          5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     4009          9: 'upper center', 10: 'center'      kfig= kind of figure
     4010        [figname]= name of the figure
     4011    """
     4012    fname = 'draw_subbasin'
     4013
     4014    if values == 'h':
     4015        print fname + '_____________________________________________________________'
     4016        print draw_subbasin.__doc__
     4017        quit()
     4018
     4019    expectargs = '[subasiname]:[rangecolors]:[mapv]:[drawsubid]:[gtit]:[figkind]:' + \
     4020      '[legloc]:[figurename]'
     4021 
     4022    drw.check_arguments(fname,values,expectargs,':')
     4023
     4024    subbasiname = values.split(':')[0].replace('!',' ')
     4025    rangecolors = values.split(':')[1]
     4026    mapv = values.split(':')[2]
     4027    drawsubid = gen.Str_Bool(values.split(':')[3])
     4028    gtit = values.split(':')[4].replace('!',' ')
     4029    figkind = values.split(':')[5]
     4030    legloc = int(values.split(':')[6])
     4031    figurename = values.split(':')[7]
     4032
     4033    if not os.path.isfile(ncfile):
     4034        print errormsg
     4035        print '  ' + fname + ': file "' + ncfile + '" does not exist !!'
     4036        quit(-1)   
     4037
     4038    objf = NetCDFFile(ncfile, 'r')
     4039
     4040    searchvars = ['lon', 'lat', 'lonsubflow', 'latsubflow', 'outsubflow']
     4041    for searchvar in searchvars:
     4042        if not gen.searchInlist(objf.variables,searchvar):
     4043            print errormsg
     4044            print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
     4045              "variable '" + searchvar + "' !!"
     4046            quit(-1)
     4047   
     4048# lon,lat
     4049    olon = objf.variables['lon']
     4050    olat = objf.variables['lat']
     4051    lon = olon[:]
     4052    lat = olat[:]
     4053
     4054# sub-flow names
     4055    osubnames = objf.variables['subflow']
     4056    subnames = drw.get_str_nc(osubnames, osubnames.shape[1])
     4057
     4058# sub-flow lat, lon
     4059    latlonsub = {}
     4060    outflowsub = {}
     4061    osublon = objf.variables['lonsubflow']
     4062    osublat = objf.variables['latsubflow']
     4063    oNsubflow = objf.variables['Nsubflow']
     4064    ooutsubflow = objf.variables['outsubflow']
     4065    Nsubflow = oNsubflow[:]
     4066    isub = 0
     4067    for Ssub in subnames:
     4068        sublatlon = []
     4069        suboutflow = []
     4070        for igrid in range(Nsubflow[isub]):
     4071            sublatlon.append([osublat[isub,igrid], osublon[isub,igrid]])
     4072            suboutflow.append(ooutsubflow[isub,igrid])
     4073        latlonsub[Ssub] = sublatlon
     4074        outflowsub[Ssub] = suboutflow
     4075        isub = isub + 1
     4076
     4077# colors
     4078    if rangecolors == 'None':
     4079        rangecols = None
     4080    else:
     4081        cols = rangecolors.split('@')
     4082        Ncols = len(cols)
     4083        rangecols = []
     4084        for icol in range(Ncols):
     4085            cval = cols[icol].split('|')
     4086            rangecols.append([np.float(cval[0]),np.float(cval[1]),np.float(cval[2])])
     4087
     4088    drw.plot_subbasin(subbasiname, lon, lat, subnames, latlonsub, outflowsub,        \
     4089      rangecols, mapv, drawsubid, gtit, figkind, legloc, figurename)
     4090
     4091    objf.close()
     4092
     4093    return
     4094
    39864095#quit()
    39874096
     
    40704179elif oper == 'draw_river_desc':
    40714180    draw_river_desc(opts.ncfile, opts.values, opts.varname)
     4181elif oper == 'draw_subbasin':
     4182    draw_subbasin(opts.ncfile, opts.values)
    40724183elif oper == 'draw_timeSeries':
    40734184    draw_timeSeries(opts.ncfile, opts.values, opts.varname)
  • trunk/tools/drawing_tools.py

    r808 r826  
    278278
    279279    return varvalues, dimnslice
     280
     281def get_str_nc(varo, Lchar):
     282    """ Function to get string values in a netCDF variable as a chains of 1char values
     283    varo= netCDF variable object
     284    Lchar = length of the string in the netCDF file
     285    """
     286    fname = 'get_str_nc'
     287
     288    Nvalues = varo.shape[0]
     289
     290    strings = []
     291
     292    for ival in range(Nvalues):
     293        stringv = varo[ival,:]
     294        string = str('')
     295        for ich in range(Lchar):
     296            charval = str(stringv[ich:ich+1]).replace('[','').replace(']','').replace("'","")
     297            if charval == '--' or len(charval) == 0:
     298                break
     299            else:
     300                if ich == 0:
     301                    string = charval
     302                else:
     303                    string = string + charval
     304
     305        strings.append(string.strip())
     306
     307    return strings
    280308
    281309def interpolate_locs(locs,coords,kinterp):
     
    68256853    return
    68266854
    6827 
    68286855def plot_vertical_lev(vertz, vertp, zlog, dzlog, plog, dplog, gtit, kfig, lloc):
    68296856    """ plotting vertical levels distribution
     
    69136940    return
    69146941
     6942def plot_subbasin(subname, lons, lats, rsf, rLlf, rof, rcolors, mapv, drawsubid,     \
     6943  graphtit, kfig, lloc, figname):
     6944    """ Function to plot rivers from 'river_desc.nc' ORCDHIEE
     6945      subname= name of the subbasin
     6946      lons= values for the x-axis
     6947      lats= values for the y-axis
     6948      rsf= list of the name of the sub-flows to plot
     6949      rLlf= dictionary with the lat,lon of the subflows
     6950      rof= dictionary with the outflows of the subflows
     6951      rcolors= base of colors of the lines for the subflows (first level)
     6952      mapv= map characteristics: [proj],[res]
     6953        see full documentation: http://matplotlib.org/basemap/
     6954        [proj]: projection
     6955          * 'cyl', cilindric
     6956          * 'lcc', lambert conformal
     6957        [res]: resolution:
     6958          * 'c', crude
     6959          * 'l', low
     6960          * 'i', intermediate
     6961          * 'h', high
     6962          * 'f', full
     6963      drawsubid= wehther sub-flow ids should be plot or not
     6964      graphtit= title of the graph ('|', for spaces)
     6965      lloc= location of the legend (0, automatic)
     6966        1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     6967        5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     6968        9: 'upper center', 10: 'center'      kfig= kind of figure
     6969      figname= name of the figure
     6970    """
     6971    fname = 'plot_subbasin'
     6972
     6973    dx=lons.shape[1]
     6974    dy=lats.shape[0]
     6975
     6976    lengthtrac = np.float(lons[0,1] - lons[0,0])
     6977    lengthtrac2 = lengthtrac*np.sqrt(2.)
     6978
     6979    ddx = np.abs(lons[dy/2+1,dx/2] - lons[dy/2,dx/2])
     6980    ddy = np.abs(lats[dy/2,dx/2+1] - lats[dy/2,dx/2])
     6981    fontcharac = {'family': 'serif', 'weight': 'normal', 'size': 3}
     6982
     6983    print '  ' + fname + ' Lluis; rsf:', rsf, type(rsf)
     6984    subhr = gen.chainSnumHierarchy(rsf)
     6985
     6986# Getting colors
     6987    Nsubs = len(rsf)
     6988    maxNgrids = -1
     6989   
     6990    collev = {}
     6991    if rcolors is None:
     6992# 1st level colors from colorsauto
     6993        for isub in range(subhr.xlevs[1]):
     6994            collev[gen.num_chainSnum(isub+1)] = gen.colhex_dec(colorsauto[isub])
     6995    else:
     6996        if len(rcolors) != subhr.Llev1:
     6997            print errormsg
     6998            print '  ' + fname + ': number of first subbasins:', subhr.Llev1,        \
     6999              'and number of provided colors:', len(rcolors), 'differ !!'
     7000            print '    provided colors:', rcolors
     7001            quit(-1)
     7002        for isub in range(subhr.xlevs[1]):
     7003            collev[gen.num_chainSnum(isub+1)] = rcolors[isub]
     7004
     7005    print ' Lluis collev:', collev
     7006
     7007# All the colors should finish white...
     7008    endcol = [1., 1., 1.]
     7009    colorsub = {}
     7010    xlabpos = []
     7011    ylabpos = []
     7012    xtrack = []
     7013    ytrack = []
     7014    colortrack = []
     7015    outflows = []
     7016
     7017    for isub in rsf:
     7018        levs = gen.num_split(isub)
     7019        Nlevs = len(levs)
     7020        begcol = collev[levs[0]]
     7021        for ilev in range(2,Nlevs):
     7022# We do not want a last white value...
     7023            if Nlevs < subhr.Nlevs:
     7024                maxNcol = subhr.xlevs[ilev]
     7025            else:
     7026                maxNcol = subhr.xlevs[ilev]+1
     7027            colors = gen.color_deg([begcol, endcol], maxNcol, 'std')
     7028            begcol = colors[1:4,gen.chainSnum_num(levs[ilev])-1]
     7029
     7030#        colorsub[isub] = gen.coldec_hex(begcolors)
     7031        colorsub[isub] = tuple(begcol)
     7032        Llfs = rLlf[isub]
     7033        outfs = rof[isub]
     7034        print '  Lluis; ' + fname + ': isub:', isub,' outfs:', outfs
     7035        for igrid in range(len(outfs)):
     7036            Llf = Llfs[igrid]
     7037            ibeg = Llf[1]
     7038            jbeg = Llf[0]
     7039            outflows.append(outfs[igrid])
     7040            angle = (outfs[igrid] - 1)*np.pi/4
     7041            if gen.searchInlist([2,4,6,8], outfs[igrid]):
     7042                iend = ibeg + lengthtrac2*np.sin(angle)
     7043                jend = jbeg + lengthtrac2*np.cos(angle)
     7044            elif gen.searchInlist([1,3,5,7], outfs[igrid]):
     7045                iend = ibeg + lengthtrac*np.sin(angle)
     7046                jend = jbeg + lengthtrac*np.cos(angle)
     7047            else:
     7048                ibeg = xvals[j,i]
     7049                jbeg = yvals[j,i]
     7050                iend = None
     7051                jend = None
     7052
     7053            xtrack.append(ibeg)
     7054            xtrack.append(iend)
     7055            xtrack.append(None)
     7056            ytrack.append(jbeg)
     7057            ytrack.append(jend)
     7058            ytrack.append(None)
     7059            colortrack.append(colorsub[isub])
     7060        xlabpos.append(ibeg)
     7061        ylabpos.append(jbeg)
     7062
     7063    plt.rc('text', usetex=True)
     7064
     7065    latlonss = rLlf.values()
     7066    nlon = np.min(latlonss[1])
     7067    xlon = np.max(latlonss[1])
     7068    nlat = np.min(latlonss[0])
     7069    xlat = np.max(latlonss[0])
     7070
     7071    dlon = xlon - nlon
     7072    dlat = xlat - nlat
     7073
     7074# Making bigger the area to map
     7075    nlon = nlon-dlon*0.1
     7076    xlon = xlon+dlon*0.1
     7077    nlat = nlat-dlat*0.1
     7078    xlat = xlat+dlat*0.1
     7079
     7080    plt.xlim(nlon,xlon)
     7081    plt.ylim(nlat,xlat)
     7082
     7083    if not mapv is None:
     7084        lon00 = np.where(lons[:] < 0., 360. + lons[:], lons[:])
     7085        lat00 = lats[:]
     7086
     7087        map_proj=mapv.split(',')[0]
     7088        map_res=mapv.split(',')[1]
     7089
     7090        lon2 = (nlon + xlon)/2.
     7091        lat2 = (nlat + xlat)/2.
     7092
     7093        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
     7094          xlon, ',', xlat
     7095
     7096        if map_proj == 'cyl':
     7097            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
     7098              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
     7099        elif map_proj == 'lcc':
     7100            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
     7101              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
     7102        else:
     7103            print errormsg
     7104            print '  ' + fname + ": projection '" + map_proj + "' not ready!!"
     7105            print '    projections available: cyl, lcc'
     7106            quit(-1)
     7107
     7108        m.drawcoastlines()
     7109
     7110        meridians = pretty_int(nlon,xlon,5)
     7111        m.drawmeridians(meridians,labels=[True,False,False,True],color="black")
     7112
     7113        parallels = pretty_int(nlat,xlat,5)
     7114        m.drawparallels(parallels,labels=[False,True,True,False],color="black")
     7115
     7116        plt.xlabel('W-E')
     7117        plt.ylabel('S-N')
     7118
     7119    j = 0
     7120    for i in range(len(rsf)):
     7121        plt.plot(xtrack[j:j+2], ytrack[j:j+2], color=colortrack[i])
     7122        j = j + 3
     7123
     7124    print 'Lluis : xtrack shape', len(xtrack)/3, 'xlabpos:', len(xlabpos)
     7125
     7126# Sea-flow
     7127    for i in range(len(outflows)):
     7128        if outflows[i] == 97:
     7129            plt.plot(xlabpos[i], ylabpos[i], 'x', color=colorsub[i])
     7130        elif outflows[i] == 98:
     7131            plt.plot(xlabpos[i], ylabpos[i], '*', color=colorsub[i])
     7132        elif outflows[i] == 99:
     7133            plt.plot(xlabpos[i], ylabpos[i], 'h', color=colorsub[i])
     7134
     7135    if drawsubid:
     7136        for i in range(len(xlabpos)):
     7137            print ' Lluis:', rsf[i], ':', colorsub[rsf[i]]
     7138            plt.text(xlabpos[i]+0.05*lengthtrac, ylabpos[i]+0.05*lengthtrac, rsf[i], \
     7139              color=colorsub[rsf[i]], fontdict=fontcharac)
     7140
     7141    plt.title(graphtit)
     7142    output_kind(kfig, figname, True)
     7143
     7144    return
     7145
  • trunk/tools/generic_tools.py

    r825 r826  
    1919
    2020####### Content
     21# chainSnumHierarchy: Class to provide the structure of a `ChainStrNum' hierarchy
    2122# chainSnum_levnext: Function to provide the next value for a given level from a chainStrnum hirerarchy of numbers
    2223# chainSnum_num: Function to pass a `ChainStrNum' string to a number
     24# coldec_hex: Function to pas a decimal ([r,g,b]; [0.,1.]) color to hexadecimal (#[RR][GG][BB], 00-64, 0A-FF)
     25# colhex_dec: Function to pas a hexadecimal (#[RR][GG][BB]; 00-64, 0A-FF) color to decimal ([0.,1.])
     26# color_deg: Function to generate a degradation of colors in rgb base
    2327# contflow: Function to bring back the increment in j,i grid points according to a trip: (inflow directions)
    2428# dictionary_key: Function to provide the first key in a dictionay with a given value
     
    66616665def chainSnum_num(cSnum):
    66626666    """ Function to pass a `ChainStrNum' string to number
    6663         `ChainStrNum:' hirerarchy classification where each levels is a significant number within a string:
     6667        `ChainStrNum:' hierarchy classification where each levels is a significant number within a string:
    66646668            1 lev.: [n]
    66656669            2 lev.: [n][m]
     
    67256729      prevlev: parent level of the desired level
    67266730      ChainStrNums: list of strings as `ChainStrNum'
    6727         `ChainStrNum:' hyerarchic classification where each levels is a significant number within a string:
     6731        `ChainStrNum:' hierarchyc classification where each levels is a significant number within a string:
    67286732            1 lev.: [n]
    67296733            2 lev.: [n][m]
     
    67796783
    67806784    return parentlev + newchainSnum
     6785
     6786class chainSnumHierarchy(object):
     6787    """ Function to provide the structure of a `ChainStrNum' hierarchy
     6788      ChainStrNums: list of strings as `ChainStrNum'
     6789        Nlevs: number of levels
     6790        levs: all the strings
     6791        xlevs: list with the maximum number of each level
     6792        Llev[N]: numbers of values in level N (up to 10 levels)
     6793        xlev[N]: maximun numbers of a level N (up to 10 levels)
     6794        Slev[N]: strings of level N (up to 10 levels)
     6795        Nlev[N]: numbers of level N (up to 10 levels)
     6796
     6797        # methods
     6798        levincr([ChainStrNum]): method to increase `ChainStrNum' level
     6799
     6800        `ChainStrNum:' hierarchyc classification where each levels is a significant number within a string:
     6801            1 lev.: [n]
     6802            2 lev.: [n][m]
     6803            3 lev.: [n][m][l]
     6804            ...
     6805          NOTE: when a given level has more than 9 values in a given potency of 10, then 'a' is attached in the front: 'a'[i]
     6806          NOTE: when a given level has more than 19 values in a given potency of 10, then 'b' is attached in the front: 'b'[i]
     6807          NOTE: when a given level has more than 29 values in a given potency of 10, then 'c' is attached in the front: 'c'[i]
     6808          (...)
     6809          NOTE: when a given level has more than 89 values in a given potency of 10, then 'i' is attached in the front: 'i'[i]
     6810          NOTE: 'o' is for that potencies of 10 without value
     6811    """
     6812    fname = 'chainSnumHierarchy'
     6813
     6814    def __init__(self,ChainStrNums):
     6815        self.Nchars = len(ChainStrNums)
     6816        self.Nlevs = 0
     6817        self.levs = []
     6818        self.xlevs = []
     6819        self.Llev1 = None
     6820        self.Llev2 = None
     6821        self.Llev3 = None
     6822        self.Llev4 = None
     6823        self.Llev5 = None
     6824        self.Llev6 = None
     6825        self.Llev7 = None
     6826        self.Llev8 = None
     6827        self.Llev9 = None
     6828        self.Llev10 = None
     6829        self.xlev1 = None
     6830        self.xlev2 = None
     6831        self.xlev3 = None
     6832        self.xlev4 = None
     6833        self.xlev5 = None
     6834        self.xlev6 = None
     6835        self.xlev7 = None
     6836        self.xlev8 = None
     6837        self.xlev9 = None
     6838        self.xlev10 = None
     6839        self.Slev1 = []
     6840        self.Slev2 = []
     6841        self.Slev3 = []
     6842        self.Slev4 = []
     6843        self.Slev5 = []
     6844        self.Slev6 = []
     6845        self.Slev7 = []
     6846        self.Slev8 = []
     6847        self.Slev9 = []
     6848        self.Slev10 = []
     6849        self.Nlev1 = []
     6850        self.Nlev2 = []
     6851        self.Nlev3 = []
     6852        self.Nlev4 = []
     6853        self.Nlev5 = []
     6854        self.Nlev6 = []
     6855        self.Nlev7 = []
     6856        self.Nlev8 = []
     6857        self.Nlev9 = []
     6858        self.Nlev10 = []
     6859
     6860        levsNvals = np.zeros((11,self.Nchars), dtype=int)
     6861        ilevvals = np.zeros((11), dtype=int)
     6862        xtrmlevs = []
     6863
     6864        Svals1 = []
     6865        Svals2 = []
     6866        Svals3 = []
     6867        Svals4 = []
     6868        Svals5 = []
     6869        Svals6 = []
     6870        Svals7 = []
     6871        Svals8 = []
     6872        Svals9 = []
     6873        Svals10 = []
     6874        for istr in ChainStrNums:
     6875            levs = num_split(istr)
     6876            Nlevs = len(levs)
     6877            if Nlevs > self.Nlevs: self.Nlevs = Nlevs
     6878            if Nlevs > 10:
     6879                print errormsg
     6880                print '  ' + fname + ': too levels:', Nlevs, " in StringNum '" +     \
     6881                  istr + "' !!"
     6882                print '    increase in the code the number of levels in the class'
     6883                quit(-1)
     6884            ilevvals[Nlevs] = ilevvals[Nlevs] + 1
     6885            if Nlevs == 1: Svals1.append(istr)
     6886            if Nlevs == 2: Svals2.append(istr)
     6887            if Nlevs == 3: Svals3.append(istr)
     6888            if Nlevs == 4: Svals4.append(istr)
     6889            if Nlevs == 5: Svals5.append(istr)
     6890            if Nlevs == 6: Svals6.append(istr)
     6891            if Nlevs == 7: Svals7.append(istr)
     6892            if Nlevs == 8: Svals8.append(istr)
     6893            if Nlevs == 9: Svals9.append(istr)
     6894            if Nlevs == 10: Svals10.append(istr)
     6895
     6896            levsNvals[Nlevs,ilevvals[Nlevs]] = chainSnum_num(levs[Nlevs-1])
     6897
     6898        valslist = ChainStrNums.sort()
     6899        self.levs = valslist
     6900        # 1st lev
     6901        self.Llev1 = ilevvals[1]
     6902        Svlist = Svals1
     6903        Nvlist = list(levsNvals[1,1:self.Llev1+1])
     6904        self.xlev1 = np.max(Nvlist)
     6905        xtrmlevs.append(self.xlev1)
     6906        Svlist.sort()
     6907        Nvlist.sort()
     6908        self.Slev1 = Svlist
     6909        self.Nlev1 = Nvlist
     6910        # 2nd lev
     6911        if self.Nlevs > 1:
     6912            self.Llev2 = ilevvals[2]
     6913            Svlist = Svals2
     6914            Nvlist = list(levsNvals[2,1:self.Llev2+1])
     6915            self.xlev2 = np.max(Nvlist)
     6916            xtrmlevs.append(self.xlev2)
     6917            Svlist.sort()
     6918            Nvlist.sort()
     6919            self.Slev2 = Svlist
     6920            self.Nlev2 = Nvlist
     6921        # 3rd lev
     6922        if self.Nlevs > 2:
     6923            self.Llev3 = ilevvals[3]
     6924            Svlist = Svals3
     6925            Nvlist = list(levsNvals[3,1:self.Llev3+1])
     6926            self.xlev3 = np.max(Nvlist)
     6927            xtrmlevs.append(self.xlev3)
     6928            Svlist.sort()
     6929            Nvlist.sort()
     6930            self.Slev3 = Svlist
     6931            self.Nlev3 = Nvlist
     6932        # 4th lev
     6933        if self.Nlevs > 3:
     6934            self.Llev4 = ilevvals[4]
     6935            Svlist = Svals4
     6936            Nvlist = list(levsNvals[4,1:self.Llev4+1])
     6937            self.xlev4 = np.max(Nvlist)
     6938            xtrmlevs.append(self.xlev4)
     6939            Svlist.sort()
     6940            Nvlist.sort()
     6941            self.Slev4 = Svlist
     6942            self.Nlev4 = Nvlist
     6943        # 5th lev
     6944        if self.Nlevs > 4:
     6945            self.Llev5 = ilevvals[5]
     6946            Svlist = Svals5
     6947            Nvlist = list(levsNvals[5,1:self.Llev5+1])
     6948            self.xlev5 = np.max(Nvlist)
     6949            xtrmlevs.append(self.xlev5)
     6950            Svlist.sort()
     6951            Nvlist.sort()
     6952            self.Slev5 = Svlist
     6953            self.Nlev5 = Nvlist
     6954        # 6th lev
     6955        if self.Nlevs > 5:
     6956            self.Llev6 = ilevvals[6]
     6957            Svlist = Svals6
     6958            Nvlist = list(levsNvals[6,1:self.Llev6+1])
     6959            self.xlev6 = np.max(Nvlist)
     6960            xtrmlevs.append(self.xlev6)
     6961            Svlist.sort()
     6962            Nvlist.sort()
     6963            self.Slev6 = Svlist
     6964            self.Nlev6 = Nvlist
     6965        # 7th lev
     6966        if self.Nlevs > 6:
     6967            self.Llev7 = ilevvals[7]
     6968            Svlist = Svals7
     6969            Nvlist = list(levsNvals[7,1:self.Llev7+1])
     6970            self.xlev7 = np.max(Nvlist)
     6971            xtrmlevs.append(self.xlev7)
     6972            Svlist.sort()
     6973            Nvlist.sort()
     6974            self.Slev7 = Svlist
     6975            self.Nlev7 = Nvlist
     6976        # 8th lev
     6977        if self.Nlevs > 7:
     6978            self.Llev8 = ilevvals[8]
     6979            Svlist = Svals8
     6980            Nvlist = list(levsNvals[8,1:self.Llev8+1])
     6981            self.xlev8 = np.max(Nvlist)
     6982            xtrmlevs.append(self.xlev8)
     6983            Svlist.sort()
     6984            Nvlist.sort()
     6985            self.Slev8 = Svlist
     6986            self.Nlev8 = Nvlist
     6987        # 9th lev
     6988        if self.Nlevs > 9:
     6989            self.Llev9 = ilevvals[9]
     6990            Svlist = Svals9
     6991            Nvlist = list(levsNvals[9,1:self.Llev9+1])
     6992            self.xlev9 = np.max(Nvlist)
     6993            xtrmlevs.append(self.xlev9)
     6994            Svlist.sort()
     6995            Nvlist.sort()
     6996            self.Slev9 = Svlist
     6997            self.Nlev9 = Nvlist
     6998        # 10th lev
     6999        if self.Nlevs > 9:
     7000            self.Llev10 = ilevvals[10]
     7001            Svlist = Svals10
     7002            Nvlist = list(levsNvals[10,1:self.Llev10+1])
     7003            self.xlev10 = np.max(Nvlist)
     7004            xtrmlevs.append(self.xlev10)
     7005            Svlist.sort()
     7006            Nvlist.sort()
     7007            self.Slev10 = Svlist
     7008            self.Nlev10 = Nvlist
     7009        self.xlevs = xtrmlevs
     7010
     7011    def levincr(self,plev):
     7012        """ Method to increase a given plevel level
     7013        levincr(self,plev):
     7014        >>> ChainStrNums = ['1', '2', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a0', '111', '112', '113', '121', '122' ]
     7015        >>> CSN_hyr = chainSnumHierarchy(ChainStrNums)
     7016        >>> CSN_hyr.levincr('11')
     7017        114
     7018        """
     7019        return chainSnum_levnext(plev, ChainStrNums)
     7020
     7021#ChainStrNums = ['1', '2', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a0', '111', '112', '113', '121', '122' ]
     7022#CSN_hyr = chainSnumHierarchy(ChainStrNums)
     7023
     7024#print CSN_hyr.levincr.__doc__
     7025#quit()
    67817026
    67827027def subbasin_point(trips, pt):
     
    69517196#
    69527197#print 'Total sub-basin:', np.sum(masksubbasin)
     7198
     7199def color_deg(colors, Nsteps, typedeg, values=None):
     7200    """ Function to generate a degradation of colors in rgb base
     7201      colors= list of colors to use [r,g,b] r,g,b <= 1.
     7202      Nsteps= number of steps (NOTE: final number of colors might differ from this value)
     7203      typedeg= type of degradate
     7204        'std': simple linear degradation between equi-spaced colors
     7205        'vals': change of colors at a given value (it requires [values])
     7206      values= list of values to use as reference (when applicable)
     7207      provides: [colordeg], [Ncolors]
     7208        [colordeg] = (4, [Ncolors]) matrix with
     7209          [0,:]= assigned value to the color (for 'std': counter)
     7210          [1:4,:]= r,g,b color
     7211    >>> color_deg([ [1.,0.,0.], [0.,1.,0.], [0.,0.,1.] ], 10, 'std')
     7212    [[ 0.     0.125  0.25   0.375  0.5    0.625  0.75   0.875  1.    ]
     7213     [ 1.     0.75   0.5    0.25   0.     0.     0.     0.     0.    ]
     7214     [ 0.     0.25   0.5    0.75   1.     0.75   0.5    0.25   0.    ]
     7215     [ 0.     0.     0.     0.     0.     0.25   0.5    0.75   1.    ]]
     7216    defcolors = color_deg([ [1.,0.,0.], [0.,1.,0.], [0.,0.,1.]], 12, 'vals', [-3., 0., 3.])
     7217    [[-3.  -2.4 -1.8 -1.2 -0.6  0.   0.6  1.2  1.8  2.4  3. ]
     7218     [ 1.   0.8  0.6  0.4  0.2  0.   0.   0.   0.   0.   0. ]
     7219     [ 0.   0.2  0.4  0.6  0.8  1.   0.8  0.6  0.4  0.2  0. ]
     7220     [ 0.   0.   0.   0.   0.   0.   0.2  0.4  0.6  0.8  1. ]]
     7221    """
     7222    fname = 'color_deg'
     7223
     7224    colordeg = np.zeros((4,Nsteps), dtype=np.float)
     7225    Ncols = len(colors)
     7226    cols = np.zeros((3,Ncols), dtype=np.float)
     7227    for icol in range(Ncols):
     7228        cols[:,icol] = np.array(colors[icol])
     7229   
     7230    if typedeg == 'std':
     7231        Nstepcols = np.int(Nsteps*1. / (Ncols-1.))
     7232        iicol = 0
     7233        for icol in range(Ncols-1):
     7234            dcolors = (cols[:,icol+1]- cols[:,icol])/(Nstepcols-1.)
     7235# To avoid repetition of the color
     7236            if icol == 0:
     7237                ibeg = 0
     7238            else:
     7239                ibeg = 1
     7240            for i in range(ibeg,Nstepcols):
     7241                colordeg[0,iicol] = iicol*1.
     7242                colordeg[1:4,iicol] = cols[:,icol] + dcolors*i
     7243                iicol = iicol + 1
     7244        Nfincol = iicol-1
     7245        colordeg[0,:] = colordeg[0,:]/(Nfincol*1.)
     7246
     7247    elif typedeg == 'vals':
     7248        if values is None:
     7249            print errormsg
     7250            print '  ' + fname + ": type '" + typedeg + "' require values !!"
     7251            quit(-1)
     7252        Nvals = len(values)
     7253        if Nvals != Ncols:
     7254            print errormsg
     7255            print '  ' + fname + ': different number of values:', Nvals,             \
     7256              'and colors:', Ncols, '!!'
     7257            print '    provided values:', values
     7258            print '    provided colors:', cols
     7259            quit(-1)
     7260        TOTrange = values[Nvals-1] - values[0]
     7261        iicol = 0
     7262        for icol in range(Ncols-1):
     7263            pairange = values[icol+1] - values[icol]
     7264            drange = pairange / TOTrange
     7265            Nstepcols = np.int(Nsteps*drange)
     7266            dcolors = (cols[:,icol+1]-cols[:,icol])/(Nstepcols-1.)
     7267# To avoid repetition of the color
     7268            if icol == 0:
     7269                ibeg = 0
     7270            else:
     7271                ibeg = 1
     7272            for i in range(ibeg,Nstepcols):
     7273                colordeg[0,iicol] = values[icol]+i*pairange/(Nstepcols-1)
     7274                colordeg[1:4,iicol] = cols[:,icol] + dcolors*i
     7275                iicol = iicol + 1
     7276        Nfincol = iicol - 1
     7277    else:
     7278        print errormsg
     7279        print '  ' + fname + ": degradation type '" + typedeg + "' not ready !!"
     7280        quit(-1)
     7281
     7282    degcolor = np.zeros((4,Nfincol), dtype=np.float)
     7283    degcolor = colordeg[:,0:Nfincol+1]
     7284
     7285    return degcolor
     7286
     7287def colhex_dec(col):
     7288    """ Function to pas a hexadecimal (#[RR][GG][BB]; 00-64, 0A-FF) color to decimal ([0.,1.])
     7289      col= '#'[RR][GG][BB] hexadecimal color string
     7290      >>>colhex_dec('#000000')
     7291      [0.0, 0.0, 0.0]
     7292      >>>colhex_dec('#00FF00')
     7293      [0.0, 1.0, 0.0]
     7294      >>>colhex_dec('#3264EE')
     7295      [0.19607843137254902, 0.39215686274509803, 0.9333333333333333]
     7296    """
     7297    fname = 'colhex_dec'
     7298    hexred = col[1:3]
     7299    hexgreen = col[3:5]
     7300    hexblue = col[5:7]
     7301
     7302    deccol = [int(hexred, 16)/255., int(hexgreen, 16)/255., int(hexblue, 16)/255.,]
     7303
     7304    return deccol
     7305
     7306def coldec_hex(col):
     7307    """ Function to pas a decimal ([r,g,b]; [0.,1.]) color to hexadecimal (#[RR][GG][BB], 00-64, 0A-FF)
     7308      col= '#'[RR][GG][BB] hexadecimal color string
     7309      >>>coldec_hex([0.0, 0.0, 0.0])
     7310      #000000
     7311      >>>coldec_hex([0.0, 1.0, 0.0])
     7312      #00FF00
     7313      >>>coldec_hex([0.19607843137254902, 0.39215686274509803, 0.9333333333333333])
     7314      #3264EE
     7315    """
     7316    fname = 'coldec_hex'
     7317
     7318    hexred = '{0:X}'.format(int(col[0]*255))
     7319    hexgreen = '{0:X}'.format(int(col[1]*255))
     7320    hexblue = '{0:X}'.format(int(col[2]*255))
     7321
     7322    if hexred == '0': hexred = '00'
     7323    if hexgreen == '0': hexgreen = '00'
     7324    if hexblue == '0': hexblue = '00'
     7325
     7326    hexcol = '#' + hexred + hexgreen + hexblue
     7327
     7328    return hexcol
     7329
     7330#quit()
     7331
Note: See TracChangeset for help on using the changeset viewer.