fig.set_size_inches(10, 5) ax = fig.add_subplot(1, 2, 1) state['air_temperature'].mean(dim='lon').plot.contourf(ax=ax, levels=16) ax.set_title('Temperature') ax = fig.add_subplot(1, 2, 2) state['eastward_wind'].mean(dim='lon').plot.contourf(ax=ax, levels=16) ax.set_title('Zonal Wind') plt.suptitle('Time: ' + str(state['time'])) model_time_step = timedelta(seconds=600) monitor = PlotFunctionMonitor(plot_function) grid = climt.get_grid(nx=128, ny=62) held_suarez = climt.HeldSuarez() dycore = climt.GFSDynamicalCore([held_suarez]) my_state = climt.get_default_state([dycore], grid_state=grid) my_state['eastward_wind'].values[:] = np.random.randn( *my_state['eastward_wind'].shape) for i in range(10000): diag, output = dycore(my_state, model_time_step) if (my_state['time'].hour % 2 == 0 and my_state['time'].minute == 0): print('max. zonal wind: ', np.amax(my_state['eastward_wind'].values)) monitor.store(my_state)
def main(): # ============ Adjustable Variables ============ # Integration Options dt = timedelta(minutes=15) # timestep duration = '48_00:00' # run duration ('<days>_<hours>:<mins>')t linearized = True ncout_freq = 6 # netcdf write frequency (hours) plot_freq = 6 # plot Monitor call frequency (hours) ntrunc = 42 # triangular truncation for spharm (e.g., 21 --> T21) # Diffusion Options diff_on = True # Use diffusion? k = 2.338e16 # Diffusion coefficient for del^4 hyperdiffusion # Forcing Options forcing_on = True # Apply vort. tendency forcing? damp_ts = 14.7 # Damping timescale (in days) # I/O Options ncoutfile = os.path.join(os.path.dirname(__file__), 'sardeshmukh88.nc') append_nc = False # Append to an existing netCDF file? # ============================================== start = time() # Get the initial state state = super_rotation(linearized=linearized, ntrunc=ntrunc) # Set up the Timestepper with the desired Prognostics if linearized: dynamics_prog = LinearizedDynamics(ntrunc=ntrunc) diffusion_prog = LinearizedDiffusion(k=k, ntrunc=ntrunc) damping_prog = LinearizedDamping(tau=damp_ts) else: dynamics_prog = NonlinearDynamics(ntrunc=ntrunc) diffusion_prog = NonlinearDiffusion(k=k, ntrunc=ntrunc) damping_prog = NonlinearDamping(tau=damp_ts) prognostics = [TendencyInDiagnosticsWrapper(dynamics_prog, 'dynamics')] if diff_on: prognostics.append(TendencyInDiagnosticsWrapper(diffusion_prog, 'diffusion')) if forcing_on: # Get our suptropical RWS forcing (from equatorial divergence) rws, rlat, rlon = rws_from_tropical_divergence(state) prognostics.append(TendencyInDiagnosticsWrapper(Forcing.from_numpy_array(rws, rlat, rlon, ntrunc=ntrunc, linearized=linearized), 'forcing')) prognostics.append(TendencyInDiagnosticsWrapper(damping_prog, 'damping')) stepper = Leapfrog(prognostics) # Create Monitors for plotting & storing data plt_monitor = PlotFunctionMonitor(debug_plots.fourpanel) if os.path.isfile(ncoutfile) and not append_nc: os.remove(ncoutfile) aliases = get_component_aliases(*prognostics) nc_monitor = NetCDFMonitor(ncoutfile, write_on_store=True, aliases=aliases) # Figure out the end date of this run d, h, m = re.split('[_:]', duration) end_date = state['time'] + timedelta(days=int(d), hours=int(h), minutes=int(m)) # Begin the integration loop idate = state['time'] while state['time'] <= end_date: # Get the state at the next timestep using our Timestepper diagnostics, next_state = stepper(state, dt) # Add any calculated diagnostics to our current state state.update(diagnostics) # Write state to netCDF every <ncout_freq> hours fhour = (state['time'] - idate).days*24 + (state['time'] - idate).seconds/3600 if fhour % ncout_freq == 0: print(state['time']) nc_monitor.store(state) # Make plot(s) every <plot_freq> hours if fhour % plot_freq == 0: plt_monitor.store(state) # Advance the state to the next timestep next_state['time'] = state['time'] + dt state = next_state print('TOTAL INTEGRATION TIME: {:.02f} min\n'.format((time()-start)/60.))
from datetime import datetime, timedelta def my_plot_function(fig, state): ax = fig.add_subplot(1, 1, 1) ax.set_xlabel('longitude') ax.set_ylabel('latitude') ax.set_title('Lowest model level air temperature (K)') im = ax.pcolormesh( state['air_temperature'].to_units('degK').values[0, :, :], vmin=260., vmax=310.) cbar = fig.colorbar(im) plot_monitor = PlotFunctionMonitor(my_plot_function) state = get_initial_state(nx=256, ny=128, nz=64) state['time'] = datetime(2000, 1, 1) physics_stepper = AdamsBashforth( UpdateFrequencyWrapper(Radiation(), timedelta(hours=2)), BoundaryLayer(), DeepConvection(), ) implicit_dynamics = ImplicitDynamics() timestep = timedelta(minutes=30) while state['time'] < datetime(2010, 1, 1): physics_diagnostics, state_after_physics = physics_stepper(state) dynamics_diagnostics, next_state = implicit_dynamics(state_after_physics)
# Add diffusion if diff_on: prognostics.append( TendencyInDiagnosticsWrapper(diffusion_prog, 'diffusion')) # Add our forcing if forcing_on: # Get our suptropical RWS forcing (from equatorial divergence) prognostics.append(TendencyInDiagnosticsWrapper(forcing_prog, 'forcing')) prognostics.append(TendencyInDiagnosticsWrapper(damping_prog, 'damping')) # Create Timestepper stepper = Leapfrog(prognostics) # Create Monitors for plotting & storing data plt_monitor = PlotFunctionMonitor(debug_plots.fourpanel) if os.path.isfile(ncoutfile) and not append_nc: os.remove(ncoutfile) aliases = get_component_aliases(*prognostics) nc_monitor = NetCDFMonitor(ncoutfile, write_on_store=True, aliases=aliases) # Figure out the end date of this run d, h, m = re.split('[_:]', duration) end_date = state['time'] + timedelta(days=int(d), hours=int(h), minutes=int(m)) # Begin the integration loop idate = state['time'] while state['time'] <= end_date: # Get the state at the next timestep using our Timestepper diagnostics, next_state = stepper(state, dt)
Created on Tue Nov 14 23:35:51 2017 @author: zifan """ import climt from sympl import PlotFunctionMonitor def plot_function(fig, state): ax = fig.add_subplot(1, 1, 1) state['surface_air_pressure'].transpose().plot.contourf(ax=ax, levels=16) monitor = PlotFunctionMonitor(plot_function) dycore = climt.GfsDynamicalCore(number_of_longitudes=198, number_of_latitudes=94, dry_pressure=1e5) dcmip = climt.DcmipInitialConditions() my_state = climt.get_default_state( [dycore], x=dycore.grid_definition['x'], y=dycore.grid_definition['y'], mid_levels=dycore.grid_definition['mid_levels'], interface_levels=dycore.grid_definition['interface_levels']) my_state['surface_air_pressure'].values[:] = 1e5 dycore(my_state)