- Timestamp:
- Apr 6, 2016, 4:32:37 PM (9 years ago)
- Location:
- trunk/tools
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/tools/drawing.py
r704 r705 28 28 ## e.g. # drawing.py -o draw_vectors -f wrfout_d01_2001-11-11_00:00:00 -S 'T|Time|Times|2,Y|south_north|XLAT|-1,X|west_east|XLONG|-1:3@3,wind@rainbow,9:10m wind,ms-1:cyl,l:WRF 10 m winds:pdf:winds' -v U10,V10 29 29 ## e.g. # drawing.py -o draw_basins -f routing.py -S 'Y|y|nav_lat|-1,X|x|nav_lon|-1:1@1,rainbow,9:basins,-:cyl,l:ORCDHIEE river-basins:pdf:basins_named' -v nav_lon,nav_lat,trip,basins 30 ## 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 30 31 31 32 main = 'drawing.py' … … 40 41 'draw_lines', 'draw_lines_time', 'draw_Neighbourghood_evol', \ 41 42 'draw_points', 'draw_points_lonlat', \ 42 'draw_ptZvals', 'draw_ timeSeries',\43 'draw_ptZvals', 'draw_river_desc', 'draw_timeSeries', \ 43 44 'draw_topo_geogrid', \ 44 45 'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories', \ … … 3329 3330 return 3330 3331 3331 3332 3332 def draw_basins(ncfile, values, varns): 3333 3333 """ Function to plot wind basins … … 3457 3457 if len(varn.split(',')) != 3: 3458 3458 print errormsg 3459 print ' ' + fname + ": color of vectors should be according to '" +\3460 3461 3459 print ' ' + fname + ": color of vectors should be according to '" + \ 3460 coln + "' but a third varibale is not provided !!" 3461 quit(-1) 3462 3462 3463 3463 ocolvec = of.variables[varNs[3]] … … 3484 3484 3485 3485 return 3486 3487 def draw_river_desc(ncfile, values, riverns): 3488 """ Function to plot rivers' description from ORCHIDEE's routing scheme 3489 values= [dimname]|[vardimname]|[value]:[basinvals]:[upstreamvals]:[mapvalues]: 3490 [gtit]:[kindfig]:[legloc]:[figuren] 3491 'X/Y'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of: 3492 [dimname]: name of the dimension in the file 3493 [vardimname]: name of the variable with the values for the dimension in the file 3494 [value]: which value of the given dimension (-1, all; [ibeg]@[iend], i-range beginning, end) 3495 No value takes all the range of the dimension 3496 [basinsvals]= [colorline] 3497 [basincolor]: ',' list of colors of the line to use to mark the basins contours (single value also possible) 3498 [upstreamvals]= [upstreamvarn],[colorbar] 3499 [upstreamcolor]: colorbar to use to plot the basins upstream values 3500 [mapvalues]= map characteristics: [proj],[res] 3501 see full documentation: http://matplotlib.org/basemap/ 3502 [proj]: projection 3503 * 'cyl', cilindric 3504 * 'lcc', lambert conformal 3505 [res]: resolution: 3506 * 'c', crude 3507 * 'l', low 3508 * 'i', intermediate 3509 * 'h', high 3510 * 'f', full 3511 gtit= title of the graph ('|', for spaces) 3512 kindfig= kind of figure 3513 legloc= location of the legend (0, automatic) 3514 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 3515 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 3516 9: 'upper center', 10: 'center' kfig= kind of figure 3517 figuren= name of the figure 3518 ncfile= file to use 3519 riverns= ',' list of the name of the rivers to plot 3520 """ 3521 import numpy.ma as ma 3522 fname = 'draw_river_desc' 3523 3524 if values == 'h': 3525 print fname + '_____________________________________________________________' 3526 print draw_river_desc.__doc__ 3527 quit() 3528 3529 expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[basinvals]:' + \ 3530 '[upstreamvals]:[mapvalues]:[gtit]:[kindfig]:[legloc]:[figuren]' 3531 3532 drw.check_arguments(fname,values,expectargs,':') 3533 3534 dimvals = values.split(':')[0] 3535 basinvals = values.split(':')[1] 3536 upstreamvals = values.split(':')[2] 3537 mapvals = values.split(':')[3] 3538 gtit = values.split(':')[4] 3539 kindfig = values.split(':')[5] 3540 legloc = int(values.split(':')[6]) 3541 figuren = values.split(':')[7] 3542 3543 basincol = basinvals 3544 if basincol.find(',') != 1: 3545 basincolor = basincol.split(',') 3546 else: 3547 basincolor = [basincol] 3548 3549 upstreamcolor = upstreamvals 3550 3551 of = NetCDFFile(ncfile,'r') 3552 3553 dims = {} 3554 for dimv in dimvals.split(','): 3555 dns = dimv.split('|') 3556 dims[dns[0]] = [dns[1], dns[2], dns[3]] 3557 3558 varNs = [] 3559 for dn in dims.keys(): 3560 if dn == 'X': 3561 varNs.append(dims[dn][1]) 3562 dimx = len(of.dimensions[dims[dn][0]]) 3563 elif dn == 'Y': 3564 varNs.append(dims[dn][1]) 3565 dimy = len(of.dimensions[dims[dn][0]]) 3566 3567 if riverns.find(',') != -1: 3568 riverns = riverns.split(',') 3569 else: 3570 riverns = [riverns] 3571 3572 rivers = [] 3573 riversubbasins = {} 3574 riversupstream = {} 3575 riversoutflow = {} 3576 for rivern in riverns: 3577 print rivern 3578 3579 # subBasins 3580 basinvar = rivern + '_coding' 3581 if not drw.searchInlist(of.variables.keys(), basinvar): 3582 print errormsg 3583 print ' ' + fname + ": file does not have variable '" + basinvar + "' !!" 3584 quit(-1) 3585 rivers.append(rivern) 3586 obasin = of.variables[basinvar] 3587 riversubbasins[rivern] = obasin[:] 3588 if rivern == riverns[0]: 3589 finalmask = obasin[:].mask 3590 else: 3591 finalmask = finalmask * obasin[:].mask 3592 3593 # upstream 3594 upstreamvar = rivern + '_upstream' 3595 if not drw.searchInlist(of.variables.keys(), upstreamvar): 3596 print errormsg 3597 print ' ' + fname + ": file does not have variable '" + upstreamvar + "' !!" 3598 quit(-1) 3599 oupstream = of.variables[upstreamvar] 3600 riversupstream[rivern] = oupstream[:] 3601 if rivern == riverns[0]: 3602 uunits = oupstream.getncattr('units') 3603 3604 # River metadata 3605 fracvar = rivern + '_frac' 3606 if not drw.searchInlist(of.variables.keys(), fracvar): 3607 print errormsg 3608 print ' ' + fname + ": file does not have variable '" + fracvar + "' !!" 3609 quit(-1) 3610 ofrac = of.variables[fracvar] 3611 riversoutflow[rivern] = [ofrac.getncattr('Longitude_of_outflow_point'), \ 3612 ofrac.getncattr('Latitude_of_outflow_point')] 3613 3614 ivar = 0 3615 for varN in varNs: 3616 varslice = [] 3617 3618 ovarN = of.variables[varN] 3619 vard = ovarN.dimensions 3620 for vdn in vard: 3621 found = False 3622 for dd in dims.keys(): 3623 if dims[dd][0] == vdn: 3624 if dims[dd][2].find('@') != -1: 3625 rvals = dims[dd][2].split('@') 3626 varslice.append(slice(int(rvals[0]), int(rvals[1]))) 3627 elif dims[dd][2] == '-1': 3628 varslice.append(slice(0,len(of.dimensions[dims[dd][0]]))) 3629 else: 3630 varslice.append(int(dims[dd][2])) 3631 3632 found = True 3633 break 3634 if not found: 3635 varslice.append(slice(0,len(of.dimensions[dims[dd][0]]))) 3636 3637 if varN == dims['X'][1]: 3638 lonvals0 = np.squeeze(ovarN[tuple(varslice)]) 3639 elif varN == dims['Y'][1]: 3640 latvals0 = np.squeeze(ovarN[tuple(varslice)]) 3641 3642 ivar = ivar + 1 3643 3644 if len(lonvals0.shape) == 1: 3645 lonvals, latvals = np.meshgrid(lonvals0, latvals0) 3646 else: 3647 lonvals = lonvals0 3648 latvals = latvals0 3649 3650 # Masking only the lon,lat with rivers 3651 malonvals = ma.masked_array(lonvals, mask=finalmask) 3652 malatvals = ma.masked_array(latvals, mask=finalmask) 3653 3654 if mapvals == 'None': 3655 mapvalues = None 3656 else: 3657 mapvalues = mapvals 3658 3659 drw.plot_river_desc(malonvals, malatvals, rivers, riversubbasins, riversupstream, riversoutflow, \ 3660 basincolor, upstreamcolor, uunits, mapvalues, gtit, kindfig, legloc, figuren) 3661 3662 of.close() 3663 3486 3664 #quit() 3487 3665 … … 3489 3667 3490 3668 ngraphics = "'" + drw.numVector_String(namegraphics, "', '") + "'" 3491 3669 3492 3670 ### Options 3493 3671 ##string_operation="operation to make: " + '\n' + " out, output values -S inidim1,[inidim2,...]:enddim1,[enddim2,...]" … … 3568 3746 elif oper == 'draw_ptZvals': 3569 3747 draw_ptZvals(opts.ncfile, opts.values, opts.varname) 3748 elif oper == 'draw_river_desc': 3749 draw_river_desc(opts.ncfile, opts.values, opts.varname) 3570 3750 elif oper == 'draw_timeSeries': 3571 3751 draw_timeSeries(opts.ncfile, opts.values, opts.varname) -
trunk/tools/drawing_tools.py
r704 r705 3 3 # From http://stackoverflow.com/questions/13336823/matplotlib-python-error 4 4 import numpy as np 5 from matplotlib.pylab import *6 5 import matplotlib as mpl 7 6 mpl.use('Agg') 7 from matplotlib.pylab import * 8 8 import matplotlib.pyplot as plt 9 9 from mpl_toolkits.basemap import Basemap … … 1520 1520 elif u == '1/m': lu='$m^{-1}$' 1521 1521 elif u == 'm-1': lu='$m^{-1}$' 1522 elif u == 'm^2': lu='$m^{2}$' 1522 1523 elif u == 'm2/s': lu='$m2s^{-1}$' 1523 1524 elif u == 'm2s-1': lu='$m2s^{-1}$' … … 6406 6407 6407 6408 return stdn, lonn, un 6409 6410 def plot_river_desc(lons, lats, rns, rss, rus, ros, bcolor, ucolor, uuts, mapv, \ 6411 graphtit, kfig, lloc, figname): 6412 """ Function to plot rivers from 'river_desc.nc' ORCDHIEE 6413 lons= values for the x-axis 6414 lats= values for the y-axis 6415 rns= list of the name of the rivers to plot 6416 rss= dictionary with the lon,lats of the subbasins of each river 6417 rus= dictionary with the lon,lats of the upstream values of each river 6418 ros= dictionary with the lon,lats of the outflow points of each river 6419 bcolor= color of the lines for the subbasins 6420 ucolor= bar color for the upstreams 6421 uuts= units of the upstream 6422 mapv= map characteristics: [proj],[res] 6423 see full documentation: http://matplotlib.org/basemap/ 6424 [proj]: projection 6425 * 'cyl', cilindric 6426 * 'lcc', lambert conformal 6427 [res]: resolution: 6428 * 'c', crude 6429 * 'l', low 6430 * 'i', intermediate 6431 * 'h', high 6432 * 'f', full 6433 graphtit= title of the graph ('|', for spaces) 6434 lloc= location of the legend (0, automatic) 6435 1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right', 6436 5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center', 6437 9: 'upper center', 10: 'center' kfig= kind of figure 6438 figname= name of the figure 6439 """ 6440 fname = 'plot_basins' 6441 6442 colvalues, linekinds, pointkinds, lwidths, psizes = ColorsLinesPointsStyles( \ 6443 len(rns), bcolor, ['-'], ['.'], [1.], [1.], None) 6444 6445 dx=lons.shape[1] 6446 dy=lats.shape[0] 6447 6448 plt.rc('text', usetex=True) 6449 6450 nlon = np.min(lons) 6451 xlon = np.max(lons) 6452 nlat = np.min(lats) 6453 xlat = np.max(lats) 6454 6455 dlon = xlon - nlon 6456 dlat = xlat - nlat 6457 6458 # Making bigger the area to map 6459 nlon = np.min(lons)-dlon*0.1 6460 xlon = np.max(lons)+dlon*0.1 6461 nlat = np.min(lats)-dlat*0.1 6462 xlat = np.max(lats)+dlat*0.1 6463 6464 plt.xlim(nlon,xlon) 6465 plt.ylim(nlat,xlat) 6466 6467 if not mapv is None: 6468 lon00 = np.where(lons[:] < 0., 360. + lons[:], lons[:]) 6469 lat00 = lats[:] 6470 6471 map_proj=mapv.split(',')[0] 6472 map_res=mapv.split(',')[1] 6473 6474 lon2 = (nlon + xlon)/2. 6475 lat2 = (nlat + xlat)/2. 6476 6477 print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \ 6478 xlon, ',', xlat 6479 6480 if map_proj == 'cyl': 6481 m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat, \ 6482 urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) 6483 elif map_proj == 'lcc': 6484 m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \ 6485 llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res) 6486 else: 6487 print errormsg 6488 print ' ' + fname + ": projection '" + map_proj + "' not ready!!" 6489 print ' projections available: cyl, lcc' 6490 quit(-1) 6491 6492 m.drawcoastlines() 6493 6494 meridians = pretty_int(nlon,xlon,5) 6495 m.drawmeridians(meridians,labels=[True,False,False,True],color="black") 6496 6497 parallels = pretty_int(nlat,xlat,5) 6498 m.drawparallels(parallels,labels=[False,True,True,False],color="black") 6499 6500 plt.xlabel('W-E') 6501 plt.ylabel('S-N') 6502 6503 umin = 10.e20 6504 umax = -umin 6505 for rn in rns: 6506 nrns = np.min(rus[rn]) 6507 xrns = np.max(rus[rn]) 6508 6509 if umin > nrns: umin = nrns 6510 if umax < xrns: umax = xrns 6511 6512 i = 0 6513 for rn in rns: 6514 plt.pcolormesh(lons, lats, rus[rn], vmin=umin, vmax=umax, \ 6515 cmap=plt.get_cmap(ucolor), norm=matplotlib.colors.LogNorm()) 6516 # plt.pcolormesh(lons, lats, rss[rn], cmap=plt.get_cmap(ucolor)) 6517 if rn == rns[0]: cbar = plt.colorbar() 6518 riverarea = rss[rn] 6519 6520 riverarea.mask = ma.nomask 6521 rarea = np.where(riverarea == 999999999, -5, riverarea) 6522 rarea = np.where(rarea > 0, 1, 0) 6523 plt.contour(lons, lats, rarea, levels = [0.], colors=colvalues[i], \ 6524 linewidths=1.5) 6525 6526 oflow = ros[rn] 6527 plt.plot(oflow[0], oflow[1], 'h', color=colvalues[i], label=rn) 6528 # plt.annotate(rn, xy=(0., i*0.05), xycoords='axes fraction', color=colvalues[i]) 6529 i = i+1 6530 6531 6532 # Attempts to plot sub-basins 6533 6534 # Gradient subbasins (not working) 6535 # gradriver = np.zeros((dy,dx), dtype=int) 6536 # for j in range(dy-2): 6537 # for i in range(dx-2): 6538 # gradriver[j,i] = riverarea[j,i+1]-riverarea[j,i]+riverarea[j+1,i]- \ 6539 # riverarea[j,i] 6540 # garea = np.where(gradriver != 0, 1, gradriver) 6541 # print garea 6542 # plt.contour(lons, lats, garea, levels = [0.], colors='red', linewidths=1.) 6543 6544 # Not working 6545 # subbasins = np.sort(np.unique(rarea)) 6546 # for subb in subbasins: 6547 # if subb > 0.: 6548 # sarea = np.where(rarea != subb, 0, rarea) 6549 # plt.contour(lons, lats, sarea, levels = [1.], colors='gray', linewidths=1.) 6550 6551 cbar.set_label('upstream (' + units_lunits(uuts) + ')') 6552 plt.legend(loc=lloc) 6553 6554 # plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')', \ 6555 # xy=(0.80,-0.15), xycoords='axes fraction', color='black') 6556 6557 plt.title(graphtit.replace('|',' ').replace('&','\&')) 6558 6559 output_kind(kfig, figname, True) 6560 6561 return 6562
Note: See TracChangeset
for help on using the changeset viewer.