|
| 1 | +debug = False |
| 2 | +if not debug: |
| 3 | + import matplotlib |
| 4 | + matplotlib.use('Agg') |
| 5 | + |
| 6 | +import matplotlib.pyplot as plt |
| 7 | +import xarray as xr |
| 8 | +import metpy.calc as mpcalc |
| 9 | +from metpy.units import units |
| 10 | +from glob import glob |
| 11 | +import numpy as np |
| 12 | +import pandas as pd |
| 13 | +from multiprocessing import Pool |
| 14 | +from functools import partial |
| 15 | +import os |
| 16 | +from utils import * |
| 17 | +import sys |
| 18 | + |
| 19 | +# The one employed for the figure name when exported |
| 20 | +variable_name = 'soil_moisture' |
| 21 | + |
| 22 | +print('Starting script to plot '+variable_name) |
| 23 | + |
| 24 | +# Get the projection as system argument from the call so that we can |
| 25 | +# span multiple instances of this script outside |
| 26 | +if not sys.argv[1:]: |
| 27 | + print('Projection not defined, falling back to default (euratl, it, de)') |
| 28 | + projections = ['euratl','it','de'] |
| 29 | +else: |
| 30 | + projections=sys.argv[1:] |
| 31 | + |
| 32 | +def main(): |
| 33 | + """In the main function we basically read the files and prepare the variables to be plotted. |
| 34 | + This is not included in utils.py as it can change from case to case.""" |
| 35 | + file = glob(input_file) |
| 36 | + print('Using file '+file[0]) |
| 37 | + dset = xr.open_dataset(file[0]) |
| 38 | + dset = dset.metpy.parse_cf() |
| 39 | + |
| 40 | + saturation = xr.open_dataset('/home/mpim/m300382/icon_forecasts/soil_saturation.nc')['soil_saturation'] |
| 41 | + |
| 42 | + # Convert to normal soil moisture units |
| 43 | + depths = dset['W_SO'].depth.values |
| 44 | + depths[0]=depths[0]*2 |
| 45 | + rho_w=1000. |
| 46 | + |
| 47 | + w_so = dset['W_SO'].copy() # Otherwise it overwrites it |
| 48 | + |
| 49 | + for i, depth in enumerate(depths): |
| 50 | + w_so[:,i,:,:] = dset['W_SO'][:,i,:,:]/(depth*rho_w) |
| 51 | + |
| 52 | + # Expand the saturation matrix to have |
| 53 | + saturation = np.repeat(saturation.values[None,:,:], w_so.depth.shape[0], axis=0) |
| 54 | + saturation = np.repeat(saturation[None,:,:,:], w_so.time.shape[0], axis=0) |
| 55 | + w_so_sat = (w_so / saturation)*100. |
| 56 | + |
| 57 | + # Fix weird points with ice/rock |
| 58 | + w_so_sat = w_so_sat.where(w_so!=0,0.) |
| 59 | + |
| 60 | + lon, lat = get_coordinates(dset) |
| 61 | + lon2d, lat2d = np.meshgrid(lon, lat) |
| 62 | + |
| 63 | + time = pd.to_datetime(dset.time.values) |
| 64 | + cum_hour=np.array((time-time[0]) / pd.Timedelta('1 hour')).astype("int") |
| 65 | + |
| 66 | + levels_sm = np.arange(0, 100, 10.) |
| 67 | + |
| 68 | + cmap = plt.get_cmap('terrain_r') |
| 69 | + |
| 70 | + for projection in projections:# This works regardless if projections is either single value or array |
| 71 | + fig = plt.figure(figsize=(figsize_x, figsize_y)) |
| 72 | + ax = plt.gca() |
| 73 | + m, x, y =get_projection(lon2d, lat2d, projection, labels=True) |
| 74 | + |
| 75 | + # All the arguments that need to be passed to the plotting function |
| 76 | + args=dict(m=m, x=x, y=y, ax=ax, cmap=cmap, |
| 77 | + w_so_sat=w_so_sat, levels_sm=levels_sm, |
| 78 | + time=time, projection=projection, cum_hour=cum_hour) |
| 79 | + |
| 80 | + print('Pre-processing finished, launching plotting scripts') |
| 81 | + if debug: |
| 82 | + plot_files(time[1:2], **args) |
| 83 | + else: |
| 84 | + # Parallelize the plotting by dividing into chunks and processes |
| 85 | + dates = chunks(time, chunks_size) |
| 86 | + plot_files_param=partial(plot_files, **args) |
| 87 | + p = Pool(processes) |
| 88 | + p.map(plot_files_param, dates) |
| 89 | + |
| 90 | +def plot_files(dates, **args): |
| 91 | + # Using args we don't have to change the prototype function if we want to add other parameters! |
| 92 | + first = True |
| 93 | + for date in dates: |
| 94 | + # Find index in the original array to subset when plotting |
| 95 | + i = np.argmin(np.abs(date - args['time'])) |
| 96 | + # Build the name of the output image |
| 97 | + filename = subfolder_images[args['projection']]+'/'+variable_name+'_%s.png' % args['cum_hour'][i]#date.strftime('%Y%m%d%H')# |
| 98 | + |
| 99 | + cs = args['ax'].contourf(args['x'], args['y'], args['w_so_sat'][i,0], extend='both', cmap=args['cmap'], |
| 100 | + levels=args['levels_sm']) |
| 101 | + |
| 102 | + an_fc = annotation_forecast(args['ax'],args['time'][i]) |
| 103 | + an_var = annotation(args['ax'], 'Soil Moisture saturation' ,loc='lower left', fontsize=6) |
| 104 | + an_run = annotation_run(args['ax'], args['time']) |
| 105 | + |
| 106 | + if first: |
| 107 | + plt.colorbar(cs, orientation='horizontal', label='Saturation [%]', pad=0.03, fraction=0.04) |
| 108 | + |
| 109 | + if debug: |
| 110 | + plt.show(block=True) |
| 111 | + else: |
| 112 | + plt.savefig(filename, **options_savefig) |
| 113 | + |
| 114 | + remove_collections([cs, an_fc, an_var, an_run]) |
| 115 | + |
| 116 | + first = False |
| 117 | + |
| 118 | +if __name__ == "__main__": |
| 119 | + main() |
0 commit comments