Index: /trunk/tools/drawing.py
===================================================================
--- /trunk/tools/drawing.py	(revision 2249)
+++ /trunk/tools/drawing.py	(revision 2250)
@@ -67,4 +67,5 @@
 ## e.g. # drawing.py -o draw_WRFeta_levels -f 120lev/simin_vars.nc,80lev/simin_vars.nc,50lev/simin_vars.nc,50lev_assigned/simin_vars.nc,38lev/simin_vars.nc -f '120lev,80lev,50lev,50leva,38lev:auto:auto:0|6|2:FPS!Alps!vert!levels:pdf:no:true'
 ## e.g. # drawing.py -o draw_2Dshad_map -S 'orog;$conv^{ini}$;lat|-1,lon|-1;lon;lat;auto;rainbow#auto#auto#time@minutes!since!1949-12-01!00:00:00|exct,6,h|%d$^{%H}$|date!([DD]$^{[HH]}$);Srange,Srange;convini|Case1|1a;pdf;binary|shadow,NW,auto|-70.,-36,-62.,-30.;cyl,c;yes' -v convini -f UBA_ERA-I_1a_2D.nc
+## e.g. # $pyHOME/drawing.py -o draw_river_pattern -S 'ORCHIDEEdef:ORCHIDEEdef:auto:cyl,l:None:-100.|-65.|-20.|15.:False:True:South|America|ORCHIDEE|routing|0.5|deg:pdf:0|10|1:True' -v Parana,Amazon
 
 #######
@@ -101,4 +102,6 @@
 # draw_points_lonlat: Function to plot a series of lon/lat points
 # draw_ptZvals: Function to plot a given list of points by their Z value and a colorbar
+# draw_river_pattern: Function to plot rivers' patterns from ORCHIDEE's routing scheme file 
+#   ('routing.nc' and 'river_desc.nc')
 # draw_SkewT: creation of a SkewT-logP diagram using matplotlib's API example  
 # draw_stations_map: Function to plot a map with the stations
@@ -139,5 +142,6 @@
   'draw_Neighbourghood_evol',                                                        \
   'draw_points', 'draw_points_lonlat',                                               \
-  'draw_ptZvals', 'draw_river_desc', 'draw_SkewT', 'draw_subbasin',                  \
+  'draw_ptZvals', 'draw_river_desc', 'draw_river_pattern', 'draw_SkewT',             \
+  'draw_subbasin',                                                                   \
   'draw_stations_map', 'draw_Taylor',                                                \
   'draw_time_lag', 'draw_timeSeries', 'draw_topo_geogrid',                           \
@@ -10909,4 +10913,321 @@
 #draw_2Dshad_map(ncfile, values, 'convini', axfig=None, fig=None)
 
+def draw_river_pattern(values, riverns):
+    """ Function to plot rivers' patterns from ORCHIDEE's routing scheme file 
+          ('routing.nc' and 'river_desc.nc')
+      values= [routingvars]:[descvalues]:[rivervalues]:[mapvalues]:[stationsvalues]:
+          [lonlatbox]:[drawcountry]:[drawbasinid]:[gtit]:[kindfig]:[legvals]:
+          [closefig]
+        [routingvars]= '|' list of [basinsfilen]|[basinsvarid]|[basinslonname]|
+            [basinslatname]|[basinsflowname], names of the variables in routing 
+             scheme file with the required values to make the plot (use 'ORCHIDEEdef' 
+             to use its default values 'routing.nc|basins|nav_lon|nav_lat|trip')
+          [basinsfilen]: name of the file with the basins' information
+          [basinsvarid]: basins' id
+          [basinslonname]: name of the variable with the longitudes
+          [basinslatname]: name of the variable with the latitudes
+          [basinsflowname]: name with the variable with the flow directions 
+             (1-8: N, NE, E, ..., NW; 97: sub-basin; 98: small to sea; 99: large to 
+             sea)
+        [descvalues]= '|' list of [descfilen]|[TAILdesccoding]|[desclon]|[desclat], 
+          names of the variables from routing output required for the plot (use 
+          'ORCHIDEEdef' to use its default values 'river_desc.nc|_coding|lon|lat')
+          [descfilen]: netCDF file with the description of the rivers as in ORCHIDEE
+            One ASCII variable per name of river with (e.g. Parana):
+              double Parana_frac(lat, lon) ;
+                Parana_frac:units = "-" ;
+                Parana_frac:long_name = "Fraction of basin Parana per grid box" ;
+                Parana_frac:missing_value = 1.e+20 ;
+                Parana_frac:Nb_of_grid_points_in_basin = 380 ;
+                Parana_frac:Longitude_of_outflow_point = -58.5 ;
+                Parana_frac:Latitude_of_outflow_point = -34.5 ;
+                Parana_frac:Number_of_streams = 380 ;
+                Parana_frac:Total_number_of_hops_to_ocean = 6840 ;
+                Parana_frac:Minimum_number_of_hops_to_ocean_for_any_stream = 1 ;
+                Parana_frac:Average_number_of_hops_to_ocean_for_any_stream = 18 ;
+                Parana_frac:Maximum_number_of_hops_to_ocean_for_any_stream = 32 ;
+                Parana_frac:Average_residence_time_in_basin = 19153.2279625174 ;
+              double Parana_upstream(lat, lon) ;
+                Parana_upstream:units = "m^2" ;
+                Parana_upstream:long_name = "Upstream area of basin Parana in the grid box" ;
+                Parana_upstream:missing_value = 1.e+20 ;
+              int Parana_coding(lat, lon) ;
+                Parana_coding:units = "-" ;
+                Parana_coding:long_name = "Pfafstetter codes of grid boxes in basin Parana" ;
+                Parana_coding:missing_value = 999999999 ;
+          [TAILdesccoding]: tail of the variable with the river coding as:
+            [rivername][TAILdescoding]
+          [desclon]: longitude values
+          [desclat]: latitude values
+        [rivervalues]= '|' separated list of [colordescid]|[rivercolor]|[rivernocolor]|[riverwidth]
+            [riverwidth] (use 'auto' for 'rainbow|#AAAAAAA|#CCCCCC|0.5')
+          [barcolordescid]: color bar to use to distinguish among selected rivers to draw
+          [rivercolor]: color for the river-flows of the non selected rivers
+          [rivernocolor]: color for the outflows of the non selected rivers
+          [riverwidth]: width of the lines of the rivers' path
+        [mapvalues]= map characteristics: [proj],[res]
+          see full documentation: http://matplotlib.org/basemap/
+          [proj]: projection
+            * 'cyl', cilindric
+            * 'lcc', lambert conformal
+          [res]: resolution:
+            * 'c', crude
+            * 'l', low
+            * 'i', intermediate
+            * 'h', high
+            * 'f', full
+        [stationsvalues]= '|' list of values in order to add stations and its labels 
+            into the plot (use 'None' for no stations file) [stationsfilen]|[stname]|
+            [stlonn]|[stlatn]|[stcol]|[stsize]
+          [stationsfilen]: name of the netCDF file with the values of the stations
+          |stloname]: variable with the name of the stations
+          |stlonn]: variable with the longitude of the stations
+          [stlatn]: variable with the latitude of the stations
+          [stcol]: color to use for the labels of the stations
+          [stsize]: character size to use for the labels of the stations
+        [lonlatbox]= '|' separated list of [SWlon]|[SWlat]|[NElon]|[NElat] to define
+          only a given region to plot as a lonlat box ('all' for all the area in file)
+          [SWlon]: longitude SW vertex
+          [SWlat]: latitude SW vertex
+          [NElon]: longitude NE vertex
+          [NElat]: latitude NE vertex
+        [drawcountry]= whether country lines should be plotted or not
+        [drawbasinid]= whether basins id should be plotted or not
+        [gtit]= title of the graph ('|', for spaces)
+        [kindfig]= kind of figure (png, ps, pdf)
+        [legvals]= [locleg]|[fontsize]|[Ncol] ('auto' for 0|12|1)
+          [locleg]: location of the legend (0, autmoatic)
+            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
+            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
+            9: 'upper center', 10: 'center'
+          [fontsize]: font size for the legend (auto for 12)
+          [Ncol]: numnber of columns
+        [closefig]= whether figure should be closed or not
+      riverns= ',' list of the names of the rivers to plot (as in [descfilen])
+        'all': for all rivers in file
+        'larger',[Npaths]: all river larger than [Npaths] grid points (NOT now)
+    """
+    import numpy.ma as ma
+    fname = 'draw_river_pattern'
+
+    if values == 'h':
+        print fname + '_____________________________________________________________'
+        print draw_river_desc.__doc__
+        quit()
+
+    expectargs = '[routingvars]:[descvalues]:[rivervalues]:[mapvalues]:' +           \
+      '[stationsvalues]:[lonlatbox]:[drawcountry]:[drawbasinid]:[gtit]:[kindfig]:' + \
+      '[legvals]:[closefig]'
+ 
+    drw.check_arguments(fname,values,expectargs,':')
+
+    routingvars = values.split(':')[0]
+    descvalues = values.split(':')[1]
+    rivervalues = values.split(':')[2]
+    mapvals = values.split(':')[3]
+    stationvalues = values.split(':')[4]
+    lonlatbox = values.split(':')[5]
+    drawcountry = gen.Str_Bool(values.split(':')[6])
+    drawbasinid = gen.Str_Bool(values.split(':')[7])
+    gtit = values.split(':')[8].replace('|',' ')
+    kindfig = values.split(':')[9]
+    legvals = values.split(':')[10]
+    closefig = gen.Str_Bool(values.split(':')[11])
+
+    if routingvars == 'ORCHIDEEdef':
+        basinsfilen = 'routing.nc'
+        basinsvarid = 'basins'
+        basinslonname = 'nav_lon'
+        basinslatname = 'nav_lat'
+        basinsflowname = 'trip'
+    else:
+        [basinsfilen, basinsvarid, basinslonname, basinslatname, basinsflowname] =   \
+          routingvars.split('|')
+    basinsvarns = [basinsvarid, basinslonname, basinslatname, basinsflowname]
+    basinsexpectvars = ['basinsvarid', 'basinslonname', 'basinslatname',             \
+      'basinsflowname']
+
+    if descvalues == 'ORCHIDEEdef':
+        descfilen = 'river_desc.nc'
+        TAILdesccoding = '_coding'
+        desclon = 'lon'
+        desclat = 'lat'
+    else:
+        [descfilen, TAILdesccoding, desclon, desclat] = descvalues.split('|')
+    descvarns = [desclon, desclat]
+    descexpectvarns = ['desclon', 'desclat']
+
+    if rivervalues == 'auto':
+        barcolordescid = 'rainbow'
+        rivercolor = '#AAAAAA'
+        rivernocolor = '#CCCCCC'
+        riverwidth = 0.5
+    else:
+        [barcolordescid, rivercolor, rivernocolor, riverwidth]= rivervalues.split('|')
+        riverwidth = np.float(riverwdith)
+
+    if stationvalues == 'None':
+        stationsfilen = None
+        stn = None
+        stlon = None
+        stlat = None
+        stcol = None
+        stsize = None
+    else:
+        [stationsfilen, stname, stlonn, stlatn, stcol, stsize] =                     \
+          stationvalues.split('|')
+        stsize = int(stsize)
+        stvarns = [stname, stlonn, stlatn]
+        stexpectvarns = ['stname', 'stlonn', 'stlatn']
+
+    # Getting rivers' information
+    if not os.path.isfile(basinsfilen):
+        print errormsg
+        print '  ' + fname + ": file with basins information '" + basinsfilen +      \
+          "' does not exist !!"
+        quit(-1)
+    oriver = NetCDFFile(basinsfilen, 'r')
+    ivar = 0
+    for vn in basinsexpectvars:
+        if not oriver.variables.has_key(basinsvarns[ivar]):
+            print errormsg
+            print '  ' +fname+ ": basins file '" + basinfilen + "' does not have " + \
+              vn + " as '" + basinsvarns[ivar] + "' !!"
+        ivar = ivar + 1
+    obid = oriver.variables[basinsvarid]
+    oblon = oriver.variables[basinslonname]
+    oblat = oriver.variables[basinslatname]
+    obflow = oriver.variables[basinsflowname]
+
+    if routingvars == 'ORCHIDEEdef':
+        # Data is fliped along latitudes
+        bid = obid[::-1,:]
+        blon = oblon[::-1,:]
+        blat = oblat[::-1,:]
+        bflow = obflow[::-1,:]
+    else:
+        bid = obid[:]
+        blon = oblon[:]
+        blat = oblat[:]
+        bflow = obflow[:]
+    oriver.close()
+
+    # Getting rivers' description
+    if not os.path.isfile(descfilen):
+        print errormsg
+        print '  ' + fname + ": file with decription information '" + descfilen +    \
+          "' does not exist !!"
+        quit(-1)
+    odesc = NetCDFFile(descfilen, 'r')
+    ivar = 0
+    for vn in descexpectvarns:
+        if not odesc.variables.has_key(descvarns[ivar]):
+            print errormsg
+            print '  '+fname+": dfescription file '"+descfilen+"' does not have " +  \
+              vn + " as '" + descvarns[ivar] + "' !!"
+        ivar = ivar + 1
+    odlon = odesc.variables[desclon]
+    odlat = odesc.variables[desclat]
+    dlon = odlon[:]
+    dlat = odlat[:]
+
+    if stationsfilen is not None:
+        # Getting staions' information
+        if not os.path.isfile(stationsfilen):
+            print errormsg
+            print '  ' + fname + ": file with stations information '" +              \
+              stationsfilen + "' does not exist !!"
+            quit(-1)
+        ostation = NetCDFFile(stationsfilen, 'r')
+        ivar = 1
+        for vn in stexpectvars:
+            if not ostation.variables.has_key(stvarns[ivar]):
+                print errormsg
+                print '  ' + fname + ": stations file '" + stationsfilen +           \
+                  "' does not have " + vn + " as '" + stvarns[ivar] + "' !!"
+            ivar = ivar + 1
+        stname , stlonn, stlatn
+        ostn = ostation.variables[stname]
+        ostlon = ostation.variables[stlonn]
+        ostlat = ostation.variables[stlatn]
+        
+        Lstr = ostn.dimensions[1]
+        lenstr = len(ostaton.dimensions(Lstr))
+        stn = ncvar.get_str_nc(ostn, lenstr)
+        stlon = ostlon[:]
+        stlat = ostlat[:]
+        ostation.close()
+
+    # Getting river's ids:
+    if riverns.count(',') != 0:
+        rns = riverns.split(',')
+    else:
+        if riverns == 'all':
+            rns = []
+            Ltail = len(TAILdesccoding)
+            allvarns = odesc.variables.keys()
+            for vn in allvarns:
+                if vn.find(TAILdesccoding) != -1:
+                    Lvn = len(vn)
+                    rns.append(vn[0:Lvn-Ltail])
+            if len(rns) == 0:
+                print errormsg
+                print '  ' + fname + ": no river description found as '[rivername]"+ \
+                  TAILdesccoding + "' !!"
+                allvarns.sort()
+                print "    variables found in description file '" + descfilen +      \
+                  "': ", allvarns
+                quit(-1)
+
+        elif riverns[0:6] == 'larger':
+            print errormsg
+            print '  ' + fname + ": riverns == 'larger' not ready yet !!"
+            quit(-1)
+        else:
+            rns = [riverns]
+
+    print '  ' + fname + ': rivers to plot: [namne] [id] _____'
+    codings = {}
+    for rn in rns:
+        ocoding = odesc.variables[rn + TAILdesccoding]
+        maskcoding = ocoding[:].mask
+        rnid = bid[~maskcoding][0]
+        if rnid != gen.mamat[0]:
+            codings[rn] = rnid
+            print rn ,':', rnid
+
+    lon, lat = drw.lonlat2D(blon, blat)
+
+    if lonlatbox == 'all':
+        nlon = np.min(lon)
+        nlat = np.min(lat)
+        xlon = np.max(lon)
+        xlat = np.max(lat)
+    else:
+        nlon = np.float(lonlatbox.split('|')[0])
+        nlat = np.float(lonlatbox.split('|')[1])
+        xlon = np.float(lonlatbox.split('|')[2])
+        xlat = np.float(lonlatbox.split('|')[3])
+
+    imin, imax, jmin, jmax = gen.ijlonlat(lon, lat, nlon, xlon, nlat, xlat)
+
+    # legend values
+    if legvals != 'auto':
+        legvalues = drw.legend_values(legvals, '|')
+    else:
+        legvalues = [0, 12, 1]
+
+    drw.plot_multi_river_pattern(lon[jmin:jmax,imin:imax], lat[jmin:jmax,imin:imax], \
+      bflow[jmin:jmax,imin:imax], bid[jmin:jmax,imin:imax], codings, dlon, dlat,     \
+      stn, stlon, stlat, drawcountry, drawbasinid, barcolordescid, rivercolor,       \
+      rivernocolor, riverwidth, stcol, stsize, gtit, mapvals, kindfig, rns)
+
+    return
+
+#values = 'ORCHIDEEdef:ORCHIDEEdef:auto:cyl,l:None:all:False:False:ORCHIDEEE|routing|' + \
+#  '0.5|deg:pdf:0|10|1:True'
+#riverns = 'all'
+#draw_river_pattern(values, riverns)
+
 #quit()
 
@@ -10934,5 +11255,6 @@
   'draw_cycle', 'draw_ensembles_time', 'draw_multi_2D_shad', 'draw_multi_SkewT',     \
   'draw_lines',                                                                      \
-  'draw_lines_time', 'draw_multiWindRose', 'draw_points', 'draw_Taylor',             \
+  'draw_lines_time', 'draw_multiWindRose', 'draw_points', 'draw_river_pattern',      \
+  'draw_Taylor',                                                                     \
   'draw_time_lag', 'draw_topo_geogrid_boxes',                                        \
   'draw_trajectories', 'draw_vals_trajectories', 'draw_WRFeta_levels',               \
@@ -11043,4 +11365,6 @@
     elif oper == 'draw_river_desc':
         draw_river_desc(opts.ncfile, opts.values, opts.varname)
+    elif oper == 'draw_river_pattern':
+        draw_river_pattern(opts.values, opts.varname)
     elif oper == 'draw_subbasin':
         draw_subbasin(opts.ncfile, opts.values)
Index: /trunk/tools/drawing_tools.py
===================================================================
--- /trunk/tools/drawing_tools.py	(revision 2249)
+++ /trunk/tools/drawing_tools.py	(revision 2250)
@@ -189,4 +189,6 @@
 # plot_lines: Function to plot a collection of lines
 # plot_multiWindRose: Function to plot multi wind roses (from where the dinw blows)
+# plot_river_pattern: Function to plot ORCHIDEE's pattern or rivers (following trip 
+#    variable from 'routing.nc' and river description following 'river_desc.nc')
 # plot_SkewT: Function to plot a SkewT-logP diagram using matplotlib's API example 
 # plot_stations_map: Function to plot a map with a series of stations
@@ -1822,5 +1824,5 @@
 def legend_values(legstring, char):
     """ Function to determine the values for the legend
-      legstring= char separated list of [locleg][char][fontsize]: 
+      legstring= [char] separated list of [locleg][char][fontsize][char][ncol]: 
           [locleg]: location of the legend (0, automatic)
             1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
@@ -7584,5 +7586,6 @@
   stn, stlon, stlat, drawcountry, drawbasinid, colordescid, coloriver, colornoriver, \
   colorst, stsize, graphtit, mapv, kfig, figname):
-    """ Function to plot vectors
+    """ Function to plot ORCHIDEE's pattern of one river (following trip variable from 
+        'routing.nc' and river description following 'river_desc.nc')
       xvals= values for the x-axis
       yvals= values for the y-axis
@@ -7590,5 +7593,9 @@
       veccolor= basin id
       descid= description id
-, desclon, desclat,
+      desclon= longitude of description
+      desclat= latitude of description
+      stn= name of the stations
+      stlon= longitude of the stations
+      stlat= latitude of the stations
       mapv= map characteristics: [proj],[res]
         see full documentation: http://matplotlib.org/basemap/
@@ -7604,4 +7611,9 @@
       drawcountry= whether country lines should be plotted or not
       drawbasinid= whether basins id should be plotted or not
+      colordescid= color map for the id of the rivers
+      coloriver= color for the non-selected rivers in the plot
+      colornoriver= color for the non-river paths values
+      colorst= color for the stations
+      stsize= color for the size of the labels of the stations
       graphtit= title of the graph ('|', for spaces)
       kfig= kind of figure
@@ -7794,4 +7806,240 @@
 
     return
+
+def plot_multi_river_pattern(xvals, yvals, fvals, veccolor, descids, desclon,        \
+  desclat, stn, stlon, stlat, drawcountry, drawbasinid, colordescid, coloriver,      \
+  colornoriver, pathwidth, colorst, stsize, graphtit, mapv, kfig, riverns):
+    """ Function to plot ORCHIDEE's pattern or multiple rivers (following trip variable from 
+        'routing.nc' and river description following 'river_desc.nc')
+      xvals= values for the x-axis
+      yvals= values for the y-axis
+      fvals= values for the flow (1-8: N, NE, E, ..., NW; 97: sub-basin; 98: small to sea; 99: large to sea)
+      veccolor= basin id
+      descids= dictionary with the description of each river
+      desclon= longitude of description
+      desclat= latitude of description
+      stn= name of the stations
+      stlon= longitude of the stations
+      stlat= latitude of the stations
+      mapv= map characteristics: [proj],[res]
+        see full documentation: http://matplotlib.org/basemap/
+        [proj]: projection
+          * 'cyl', cilindric
+          * 'lcc', lambert conformal
+        [res]: resolution:
+          * 'c', crude
+          * 'l', low
+          * 'i', intermediate
+          * 'h', high
+          * 'f', full
+      drawcountry= whether country lines should be plotted or not
+      drawbasinid= whether basins id should be plotted or not
+      colordescid= color map for the id of the rivers
+      coloriver= color for the non-selected rivers in the plot
+      colornoriver= color for the non-river paths values
+      pathwidth= width of the line with the river paths
+      colorst= color for the stations
+      stsize= color for the size of the labels of the stations
+      graphtit= title of the graph ('|', for spaces)
+      kfig= kind of figure
+      riverns= list with the name of the rivers to be plotted
+    """
+    fname = 'plot_multi_river_pattern'
+
+    figname = 'multi_river_pattern'
+
+    dx=xvals.shape[1]
+    dy=xvals.shape[0]
+    xmin = np.min(xvals)
+    xmax = np.max(xvals)
+    ymin = np.min(yvals)
+    ymax = np.max(yvals)
+
+# flow direction
+
+    plt.rc('text', usetex=True)
+
+    ddx = np.abs(xvals[dy/2+1,dx/2] - xvals[dy/2,dx/2])
+    ddy = np.abs(yvals[dy/2,dx/2+1] - yvals[dy/2,dx/2])
+    fontcharac = {'family': 'serif', 'weight': 'normal', 'size': 3}
+
+    xlabpos = []
+    ylabpos = []
+    labels = []
+    labcol = []
+    flow = []
+    flowvals = []
+    xtrack = []
+    ytrack = []
+    colortrack = []
+    trackid = []
+    stnlL = []
+    stlonlL = []
+    stlatlL = []
+
+# Setting up colors for each label
+#   From: http://stackoverflow.com/questions/15235630/matplotlib-pick-up-one-color-associated-to-one-value-in-a-colorbar
+    my_cmap = plt.cm.get_cmap(colordescid)
+    vcolmin = np.min(descids.values())
+    vcolmax = np.max(descids.values())
+
+    norm = mpl.colors.Normalize(vcolmin, vcolmax)
+
+# Vector angles
+    lengthtrac = np.float(xvals[0,1] - xvals[0,0])
+    lengthtrac2 = lengthtrac*np.sqrt(2.)
+
+    print '  ' + fname + ': getting colors for the river-paths ...'
+    for j in range(0,dy):
+        for i in range(0,dx):
+            if veccolor[j,i] != '--':
+#                ibeg = xvals[j,i]-lengthtrac/2.
+#                jbeg = yvals[j,i]-lengthtrac/2.
+                ibeg = xvals[j,i]
+                jbeg = yvals[j,i]
+                labels.append(int(veccolor[j,i]))
+                flowvals.append(fvals[j,i])
+                angle = (fvals[j,i] - 1)*np.pi/4
+                if gen.searchInlist([2,4,6,8], fvals[j,i]):
+                    iend = ibeg + lengthtrac2*np.sin(angle)
+                    jend = jbeg + lengthtrac2*np.cos(angle)
+                elif gen.searchInlist([1,3,5,7], fvals[j,i]):
+                    iend = ibeg + lengthtrac*np.sin(angle)
+                    jend = jbeg + lengthtrac*np.cos(angle)
+                else:
+                    ibeg = xvals[j,i]
+                    jbeg = yvals[j,i]
+                    iend = None
+                    jend = None
+
+                xlabpos.append(ibeg)
+                ylabpos.append(jbeg)
+                xtrack.append(ibeg)
+                xtrack.append(iend)
+                xtrack.append(None)
+                ytrack.append(jbeg)
+                ytrack.append(jend)
+                ytrack.append(None)
+                if len(desclon.shape) == 2:
+                    difflonlat = np.sqrt((desclon-xvals[j,i])**2 + (desclat-yvals[j,i])**2)
+                    mindiffLl = np.min(difflonlat)
+                    ilatlon = gen.index_mat(difflonlat, mindiffLl)
+                else:
+                    ilatlon = np.zeros((2), dtype=int)
+                    difflon = np.abs(desclon - xvals[j,i])
+                    mindiffl = np.min(difflon)
+                    ilatlon[1] = gen.index_vec(difflon,mindiffl)
+                    difflat = np.abs(desclat - yvals[j,i])
+                    mindiffL = np.min(difflat)
+                    ilatlon[0] = gen.index_vec(difflat,mindiffL)
+
+                if not gen.searchInlist(descids.values(), veccolor[j,i]):
+                    labcol.append(colornoriver)
+                    colortrack.append(colornoriver)
+#                        print 'Lluis: veccol:', veccolor[j,i], 'mindiffl', mindiffl,'mindiffL:',mindiffL
+                else:
+#                        print 'Lluis right! mindiffl', mindiffl,'mindiffL:',mindiffL
+                    labcol.append(coloriver)
+                    colortrack.append(my_cmap(norm(veccolor[j,i])))
+
+                trackid.append(veccolor[j,i])
+
+    totvals = len(flowvals)
+
+    if not mapv is None:
+        lon00 = np.where(xvals[:] < 0., 360. + xvals[:], xvals[:])
+        lat00 = yvals[:]
+
+        map_proj=mapv.split(',')[0]
+        map_res=mapv.split(',')[1]
+
+        nlon = np.min(xvals)
+        xlon = np.max(xvals)
+        nlat = np.min(yvals)
+        xlat = np.max(yvals)
+
+        lon2 = xvals[dy/2,dx/2]
+        lat2 = yvals[dy/2,dx/2]
+
+        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
+          xlon, ',', xlat
+
+        if map_proj == 'cyl':
+            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
+              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
+        elif map_proj == 'lcc':
+            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
+              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
+        else:
+            print errormsg
+            print '  ' + fname + ": projection '" + map_proj + "' not ready!!"
+            print '    projections available: cyl, lcc'
+            quit(-1)
+
+        m.drawcoastlines()
+        drawcountry = True
+        if drawcountry: m.drawcountries()
+
+        meridians = gen.pretty_int(nlon,xlon,5)
+        m.drawmeridians(meridians,labels=[True,False,False,True],color="black")
+
+        parallels = gen.pretty_int(nlat,xlat,5)
+        m.drawparallels(parallels,labels=[False,True,True,False],color="black")
+
+    Npaths = len(xlabpos)
+    print '  ' + fname + ' plotting ', Npaths ,'river-paths ...'
+    j = 0
+    for i in range(Npaths):
+        gen.percendone(i,Npaths,5.,'  ' + fname + ': drawn')
+        plt.plot(xtrack[j:j+2], ytrack[j:j+2], color=colortrack[i],                  \
+          linewidth=pathwidth)
+        j = j + 3
+
+# Sea-flow
+    for i in range(len(xlabpos)):
+        if flowvals[i] == 97:
+            plt.plot(xlabpos[i], ylabpos[i], 'x', color=colortrack[i],               \
+              markersize=lengthtrac2)
+        elif flowvals[i] == 98:
+            plt.plot(xlabpos[i], ylabpos[i], '*', color=colortrack[i],               \
+              markersize=lengthtrac2)
+        elif flowvals[i] == 99:
+            plt.plot(xlabpos[i], ylabpos[i], 'h', color=colortrack[i],               \
+              markersize=lengthtrac2)
+
+    plt.xlim(xmin,xmax)
+    plt.ylim(ymin,ymax)
+
+    if drawbasinid:
+        print '  ' + fname + ' drawing basins ids ...'
+        idlabelled = []
+        for i in range(len(xlabpos)):
+            if not gen.searchInlist(idlabelled, labels[i]):
+                plt.text(xlabpos[i]+0.05*lengthtrac, ylabpos[i]+0.05*lengthtrac,     \
+                  labels[i], color=labcol[i], fontdict=fontcharac)
+                idlabelled.append(labels[i])
+                
+#            plt.text(xlabpos[i]+0.1*lengthtrac, ylabpos[i]+0.1*lengthtrac, trackid[i],   \
+#              color=colortrack[i], fontdict=fontcharac)
+#            plt.text(xlabpos[i]+0.1*lengthtrac, ylabpos[i]+0.1*lengthtrac, str(flowvals[i]),   \
+#              color=colortrack[i], fontdict=fontcharac)
+
+    if stn is not None:
+        for ist in range(len(stlon)):
+            if stlon[ist] > xmin and stlon[ist] < xmax and stlat[ist] > ymin and     \
+              stlat[ist] < ymax:
+                stname = '*'
+                for ic in range(len(stn[ist,:])):
+                    stname  = stname + stn[ist,ic]
+#            plt.annotate(stname, xy=(stlon[ist],stlat[ist]), color=colorst, )
+                plt.text(stlon[ist], stlat[ist], stname, color=colorst, fontsize=stsize)
+
+#    cbar = plt.colorbar()
+    plt.title(graphtit.replace('&','\&'))
+
+    output_kind(kfig, figname, True)
+
+    return
+
 
 def var_3desc(ovar):
Index: /trunk/tools/generic_tools.py
===================================================================
--- /trunk/tools/generic_tools.py	(revision 2249)
+++ /trunk/tools/generic_tools.py	(revision 2250)
@@ -10383,4 +10383,10 @@
     latexsymb = {}
 
+    if type(itext) != type('S.'):
+        print warnmsg
+        print '  ' + fname + ": passed text '", itext, "' is not a string type !!"
+        print '    passed type:', type(itext), 'transforming it to string'
+        itext = str(itext)
+
     Litext = len(itext)
     for ic in range(Litext):
