Changeset 545 in lmdz_wrf for trunk


Ignore:
Timestamp:
Jun 30, 2015, 6:24:47 PM (9 years ago)
Author:
lfita
Message:

Adding `draw_points' to draw points on a shadded map

Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/drawing.py

    r542 r545  
    3131namegraphics = ['create_movie', 'draw_2D_shad', 'draw_2D_shad_time',                 \
    3232  'draw_2D_shad_cont', 'draw_2D_shad_cont_time', 'draw_2D_shad_line',                \
    33   'draw_2D_shad_line_time', 'draw_barbs', 'draw_timeSeries', 'draw_topo_geogrid',    \
     33  'draw_2D_shad_line_time', 'draw_barbs', 'draw_points', 'draw_timeSeries',          \
     34   'draw_topo_geogrid',                                                              \
    3435  'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories',          \
    3536  'draw_lines', 'draw_lines_time', 'draw_Neighbourghood_evol', 'list_graphics',      \
     
    21822183      timepos, timelabels, cbar, Nneig, shadxtrms, vunits, gtitle, gkind, True)
    21832184
     2185def draw_points(filen, values):
     2186    """ Function to plot a series of points
     2187      [values]= [ptasciifile]:[gtit]:[mapvalues]:[pointcolor]:[pointlabels]:[locleg]:
     2188        [figurek]:[figuren]
     2189        [ptasciifile]:[file],[comchar],[collon],[collat],[lab]
     2190          [file]: column ASCII file with the location of the points
     2191          [comchar]: '|' list of characters for commentaries
     2192          [collon]: number of column with the longitude of the points
     2193          [collat]: number of column with the latitude of the points
     2194          [collab]: number of column with the labels of the points ('None', and will get
     2195            the values from the [pointlabels] variable
     2196        [gtit]: title of the figure ('|' for spaces)
     2197        [mapvalues]: drawing coastaline ([proj],[res]) or None
     2198          [proj]: projection
     2199             * 'cyl', cilindric
     2200             * 'lcc', lambert conformal
     2201          [res]: resolution:
     2202             * 'c', crude
     2203             * 'l', low
     2204             * 'i', intermediate
     2205             * 'h', high
     2206             * 'f', full
     2207        [pointcolor]: color for the points ('auto' for "red")
     2208        [pointlabels]: ',' of labels [only used if [collab]='None'] ('None' for no labels)
     2209        [locleg]: location of the legend (0, autmoatic)
     2210          1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
     2211          5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
     2212          9: 'upper center', 10: 'center'
     2213        [figurek]: kind of figure
     2214        [figuren]: name of the figure
     2215      [filen]= [ncfile],[lonvarn],[latvarn][,[varn],[dimvals],[vargn],[min],[max],[cbar],[varu]]
     2216        [ncfile]: netCDF to use to geolocalize the points
     2217        [lonvarn]: name of the variable with the longitudes
     2218        [latvarn]: name of the variable with the latitudes
     2219        [varn]: optional variable to add staff into the graph
     2220        [dimval]: '@' list of [dimn]|[dimval] to get the values for [varn]
     2221          [dimn]: name of the dimension
     2222          [dimval]: value of the dimension (no value all range)
     2223        [vargn]: name of the variable in the graph
     2224        [min]: minimum value for the extra variable
     2225        [max]: maximum value for the extra variable
     2226        [cbar]: color bar
     2227        [varu]: units of the variable
     2228    """
     2229    fname = 'draw_points'
     2230
     2231    if values == 'h':
     2232        print fname + '_____________________________________________________________'
     2233        print draw_points.__doc__
     2234        quit()
     2235
     2236    expectargs = '[ptasciifile]:[gtit]:[mapvalues]:[pointcolor]:[pointlabels]:' +    \
     2237      '[locleg]:[figurek]:[figuren]'
     2238 
     2239    drw.check_arguments(fname,len(expectargs.split(':')),values,':',                 \
     2240      expectargs.split(':'))
     2241
     2242    ptasciifile = values.split(':')[0]
     2243    gtit = values.split(':')[1]
     2244    mapvalues = values.split(':')[2]
     2245    pointcolor = values.split(':')[3]
     2246    pointlabels = values.split(':')[4]
     2247    locleg = int(values.split(':')[5])
     2248    figurek = values.split(':')[6]
     2249    figuren = values.split(':')[7]
     2250
     2251# Getting station locations
     2252##
     2253    filev = ptasciifile.split(',')[0]
     2254    comchar = ptasciifile.split(',')[1].split('|')
     2255    collon = int(ptasciifile.split(',')[2])
     2256    collat = int(ptasciifile.split(',')[3])
     2257    collab = ptasciifile.split(',')[4]
     2258
     2259    if not os.path.isfile(filev):
     2260        print errormsg
     2261        print '  ' + fname + ": file '" + filev + "' does not exist!!"
     2262        quit(-1)
     2263
     2264# Getting points position and labels
     2265    oascii = open(filev, 'r')
     2266    xptval = []
     2267    yptval = []
     2268    if collab != 'None':
     2269        ptlabels = []
     2270        for line in oascii:
     2271            if not drw.searchInlist(comchar, line[0:1]):
     2272                linevals = drw.reduce_spaces(line)
     2273                xptval.append(np.float(linevals[collon].replace('\n','')))
     2274                yptval.append(np.float(linevals[collat].replace('\n','')))
     2275                ptlabels.append(linevals[int(collab)].replace('\n',''))
     2276    else:
     2277        ptlabels = None
     2278        for line in oascii:
     2279            if  not drw.searchInlist(comchar, line[0:1]):
     2280                linevals = drw.reduce_spaces(line)
     2281                xptval.append(np.float(linevals[collon].replace('\n','')))
     2282                yptval.append(np.float(linevals[collat].replace('\n','')))
     2283
     2284    oascii.close()
     2285
     2286    if pointlabels != 'None' and collab == 'None':
     2287        ptlabels = pointlabels.split(',')
     2288
     2289# Getting localization of the points
     2290##
     2291    filev = filen.split(',')
     2292    Nvals = len(filev)
     2293
     2294    ncfile = filev[0]
     2295    lonvarn = filev[1]
     2296    latvarn = filev[2]
     2297    varn = None
     2298    varextrav = None
     2299    if Nvals == 10:
     2300        varn = filev[3]
     2301        dimvals = filev[4]
     2302        varextrav = [filev[5], np.float(filev[6]), np.float(filev[7]), filev[8],     \
     2303          filev[9]]
     2304   
     2305    if not os.path.isfile(ncfile):
     2306        print errormsg
     2307        print '  ' + fname + ": file '" + ncfile + "' does not exist!!"
     2308        quit(-1)
     2309
     2310    onc = NetCDFFile(ncfile, 'r')
     2311   
     2312    lonv, latv = drw.lonlat2D(onc.variables[lonvarn], onc.variables[latvarn])
     2313
     2314    print 'Lluis varn',varn
     2315    if varn is not None:
     2316        objextra = onc.variables[varn]
     2317        vard = objextra.dimensions
     2318        dd = {}
     2319        for dn in dimvals.split('@'):
     2320            ddn = dn.split('|')[0]
     2321            ddv = dn.split('|')[1]
     2322            dd[ddn] = ddv
     2323        slicevar = []
     2324        for dv in vard:
     2325            found= False
     2326            for dn in dd.keys():
     2327                if dn == dv:
     2328                    slicevar.append(int(dd[dn]))
     2329                    found = True
     2330                    break
     2331            if not found:
     2332                slicevar.append(slice(0,len(onc.dimensions[dv])))
     2333
     2334        varextra = np.squeeze(objextra[tuple(slicevar)])
     2335
     2336    drw.plot_points(xptval, yptval, lonv, latv, varextra, varextrav, gtit, mapvalues,\
     2337      pointcolor, ptlabels, locleg, figurek, figuren)
     2338
     2339    onc.close()
     2340
     2341    return
     2342
    21842343def draw_timeSeries(filen, values, variables):
    21852344    """ Function to draw a time-series
     
    26412800Notcheckingfile = ['draw_2D_shad_cont', 'draw_2D_shad_cont_time',                    \
    26422801  'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_lines', 'draw_lines_time',    \
    2643   'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories',          \
    2644   'variable_values']
     2802  'draw_points', 'draw_topo_geogrid_boxes', 'draw_trajectories',                     \
     2803  'draw_vals_trajectories', 'variable_values']
    26452804
    26462805####### ###### ##### #### ### ## #
     
    26782837elif oper == 'draw_lines_time':
    26792838    draw_lines_time(opts.ncfile, opts.values, opts.varname)
     2839elif oper == 'draw_points':
     2840    draw_points(opts.ncfile, opts.values)
    26802841elif oper == 'draw_timeSeries':
    26812842    draw_timeSeries(opts.ncfile, opts.values, opts.varname)
  • trunk/tools/drawing_tools.py

    r544 r545  
    5858
    5959# From nc_var_tools.py
     60def reduce_spaces(string):
     61    """ Function to give words of a line of text removing any extra space
     62    """
     63    values = string.replace('\n','').split(' ')
     64    vals = []
     65    for val in values:
     66         if len(val) > 0:
     67             vals.append(val)
     68
     69    return vals
     70
    6071def searchInlist(listname, nameFind):
    6172    """ Function to search a value within a list
     
    13681379    return varvals
    13691380
     1381def lonlat2D(lon,lat):
     1382    """ Function to return lon, lat 2D matrices from any lon,lat matrix
     1383      lon= matrix with longitude values
     1384      lat= matrix with latitude values
     1385    """
     1386    fname = 'lonlat2D'
     1387
     1388    if len(lon.shape) != len(lat.shape):
     1389        print errormsg
     1390        print '  ' + fname + ': longitude values with shape:', lon.shape,            \
     1391          'is different that latitude values with shape:', lat.shape, '(dif. size) !!'
     1392        quit(-1)
     1393
     1394    if len(lon.shape) == 3:
     1395        lonvv = lon[0,:,:]
     1396        latvv = lat[0,:,:]
     1397    elif len(lon.shape) == 2:
     1398        lonvv = lon[:]
     1399        latvv = lat[:]
     1400    elif len(lon.shape) == 1:
     1401        lonlatv = np.meshgrid(lon[:],lat[:])
     1402        lonvv = lonlatv[0]
     1403        latvv = lonlatv[1]
     1404
     1405    return lonvv, latvv
     1406
    13701407#######    #######    #######    #######    #######    #######    #######    #######    #######    #######
    13711408
     
    25002537#quit()
    25012538
    2502 def plot_points(xval, yval, ifile, vtit, kfig, mapv):
     2539def plot_points(xval, yval, vlon, vlat, extravals, extrapar, vtit, mapv, color,      \
     2540  labels, lloc, kfig, figname):
    25032541    """ plotting points
    25042542      [x/yval]: x,y values to plot
    2505       vn,vm= minmum and maximum values to plot
    2506       unit= units of the variable
    2507       ifile= name of the input file
    2508       vtit= title of the variable
    2509       kfig= kind of figure (jpg, pdf, png)
     2543      vlon= 2D-matrix with the longitudes
     2544      vlat= 2D-matrix with the latitudes
     2545      extravals= extra values to be added into the plot (None for nothing)
     2546      extrapar= [varname, min, max, cbar, varunits] of the extra variable
     2547      vtit= title of the graph ('|' for spaces)
    25102548      mapv= map characteristics: [proj],[res]
    25112549        see full documentation: http://matplotlib.org/basemap/
    25122550        [proj]: projection
    25132551          * 'cyl', cilindric
     2552          * 'lcc', lambert-conformal
    25142553        [res]: resolution:
    25152554          * 'c', crude
     
    25182557          * 'h', high
    25192558          * 'f', full
     2559      color= color for the points/labels ('auto', for "red")
     2560      labels= list of labels for the points (None, no labels)
     2561      lloc = localisation of the legend
     2562      kfig= kind of figure (jpg, pdf, png)
     2563      figname= name of the figure
     2564
    25202565    """
    25212566    fname = 'plot_points'
    2522 
    2523     dx=xval.shape[0]
    2524     dy=yval.shape[0]
     2567# Canging line kinds every 7 pts (end of standard colors)
     2568    ptkinds=['.','x','o','*','+','8','>','D','h','p','s']
     2569
     2570    Npts = len(xval)
     2571    if Npts > len(ptkinds)*7:
     2572        print errormsg
     2573        print '  ' + fname + ': too many',Npts,'points!!'
     2574        print "    enlarge 'ptkinds' list"
     2575        quit(-1)
     2576
     2577    N7pts = 0
     2578
     2579    if color == 'auto':
     2580        ptcol = "red"
     2581    else:
     2582        ptcol = color
     2583
     2584    dx=vlon.shape[1]
     2585    dy=vlat.shape[0]
    25252586
    25262587    plt.rc('text', usetex=True)
    25272588
    25282589    if not mapv is None:
    2529         lon00 = np.where(xval[:] < 0., 360. + olon[:], olon[:])
    2530         lat00 = yval[:]
    2531         lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
    2532         lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
    2533 
    2534         for iy in range(len(lat00)):
    2535             lon0[iy,:] = lon00
    2536         for ix in range(len(lon00)):
    2537             lat0[:,ix] = lat00
     2590        vlon = np.where(vlon[:] < 0., 360. + vlon[:], vlon[:])
    25382591
    25392592        map_proj=mapv.split(',')[0]
    25402593        map_res=mapv.split(',')[1]
    25412594
    2542         nlon = lon0[0,0]
    2543         xlon = lon0[dy-1,dx-1]
    2544         nlat = lat0[0,0]
    2545         xlat = lat0[dy-1,dx-1]
    2546 
    2547         lon2 = lon0[dy/2,dx/2]
    2548         lat2 = lat0[dy/2,dx/2]
     2595        nlon = np.min(vlon)
     2596        xlon = np.max(vlon)
     2597        nlat = np.min(vlat)
     2598        xlat = np.max(vlat)
     2599
     2600        lon2 = vlon[dy/2,dx/2]
     2601        lat2 = vlat[dy/2,dx/2]
    25492602
    25502603        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
     
    25582611              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
    25592612
    2560         lons, lats = np.meshgrid(olon[:], olat[:])
    2561         lons = np.where(lons < 0., lons + 360., lons)
    2562 
    2563         x,y = m(lons,lats)
    2564         plt.plot(x,y)
     2613#        lons, lats = np.meshgrid(vlon, vlat)
     2614#        lons = np.where(lons < 0., lons + 360., lons)
     2615
     2616        x,y = m(vlon,vlat)
    25652617
    25662618        m.drawcoastlines()
     
    25712623        parallels = pretty_int(nlat,xlat,5)
    25722624        m.drawparallels(parallels,labels=[False,True,True,False])
    2573     else:
     2625#    else:
    25742626#        plt.xlim(0,dx-1)
    25752627#        plt.ylim(0,dy-1)
    25762628
    2577         plt.plot(xval, yval, '.')
    2578 
    2579     figname = ifile.replace('.','_') + '_' + vtit
     2629# Extra values
     2630    if extravals is not None:
     2631        plt.pcolormesh(x, y, extravals, cmap=plt.get_cmap(extrapar[3]),              \
     2632          vmin=extrapar[1], vmax=extrapar[2])
     2633        cbar = plt.colorbar()
     2634        cbar.set_label(extrapar[0].replace('_','\_') +'('+ units_lunits(extrapar[4])+\
     2635          ')')
     2636
     2637    if labels is not None:
     2638        for iv in range(len(xval)):
     2639#            plt.annotate(labels[iv], xy=(xval[iv],yval[iv]), xycoords='data')
     2640
     2641            if np.mod(iv,7) == 0: N7pts = N7pts + 1
     2642#            print iv,xval[iv],yval[iv],labels[iv],ptkinds[N7pts]
     2643
     2644            plt.plot(xval[iv],yval[iv], ptkinds[N7pts],label=labels[iv])
     2645        plt.legend(loc=lloc)
     2646
     2647    else:
     2648        plt.plot(xval, yval, '.', color=ptcol)
     2649
    25802650    graphtit = vtit.replace('_','\_').replace('&','\&')
    25812651
    2582     plt.title(graphtit)
     2652    plt.title(graphtit.replace('|', ' '))
    25832653   
    25842654    output_kind(kfig, figname, True)
Note: See TracChangeset for help on using the changeset viewer.