def test_adams_bashforth_requires_same_timestep(mock_prognostic_call): """Test that the Asselin filter is being correctly applied""" mock_prognostic_call.return_value = ({'air_temperature': 0.}, {}) state = {'air_temperature': 273.} time_stepper = AdamsBashforth([MockPrognostic()]) state = time_stepper.__call__(state, timedelta(seconds=1.)) try: time_stepper.__call__(state, timedelta(seconds=2.)) except ValueError: pass except Exception as err: raise err else: raise AssertionError( 'AdamsBashforth must require timestep to be constant')
def get_steppable_component(self): component = self.get_component_instance() if isinstance(component, TendencyComponent): return AdamsBashforth(component) else: return component
def test_3d_stepping_output_matches_cached_output(self): component = self.get_component_instance() if isinstance(component, (TendencyComponent, ImplicitTendencyComponent)): component = AdamsBashforth(component) state = self.get_3d_input_state(component) output = call_with_timestep_if_needed(component, state) cached_output = self.get_cached_output('3d_stepping') if cached_output is None: self.cache_output(output, '3d_stepping') raise AssertionError( 'Failed due to no cached output, cached current output.') else: compare_outputs(output, cached_output)
ax.plot(state['air_temperature'].values.flatten(), state['air_pressure'].values.flatten(), '-o') ax.axes.invert_yaxis() ax.set_yscale('log') ax.set_ylim(1e5, 1.) ax.set_title('Temperature') ax.grid() ax.set_xlabel('K') ax.set_yticklabels([]) monitor = PlotFunctionMonitor(plot_function) rad_sw = RRTMGShortwave() rad_lw = RRTMGLongwave() time_stepper = AdamsBashforth([rad_sw, rad_lw]) timestep = timedelta(hours=1) mid_levels = {'label': 'mid_level', 'values': np.arange(60), 'units': ''} int_levels = {'label': 'interface_level', 'values': np.arange(61), 'units': ''} state = get_default_state([rad_sw, rad_lw], mid_levels=mid_levels, interface_levels=int_levels) tp_profiles = np.load('thermodynamic_profiles.npz') mol_profiles = np.load('molecule_profiles.npz') state['air_pressure'].values[0, 0, :] = tp_profiles['air_pressure'] state['air_temperature'].values[0, 0, :] = tp_profiles['air_temperature'] state['air_pressure_on_interface_levels'].values[
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) state_after_physics.update(physics_diagnostics) state_after_physics.update(dynamics_diagnostics) plot_monitor.store(state_after_physics) next_state['time'] = state['time'] + timestep state = next_state
def plot_function(fig, state): ax = fig.add_subplot(1, 1, 1) ax.plot(state['air_temperature'].values.flatten(), state['air_pressure'].values.flatten(), '-o') ax.axes.invert_yaxis() ax.set_yscale('log') ax.set_ylim(1e5, 100.) ax.set_xlabel('Kelvin') ax.set_ylabel('Pa') ax.set_title('Radiative equilibrium in a Grey Gas atmosphere') ax.grid() monitor = PlotFunctionMonitor(plot_function) diagnostic = Frierson06LongwaveOpticalDepth() radiation = GrayLongwaveRadiation() time_stepper = AdamsBashforth([radiation]) timestep = timedelta(hours=4) state = get_default_state([radiation, diagnostic]) for i in range(6 * 7 * 4 * 10): state.update(diagnostic(state)) diagnostics, new_state = time_stepper(state, timestep) state.update(diagnostics) if i % 5 == 0: monitor.store(state) state.update(new_state)
def timestepper_class(self, *args): return AdamsBashforth(*args, order=4)
def plot_function(fig, state): ax = fig.add_subplot(1, 1, 1) ax.plot( state['air_temperature'].values.flatten(), state['air_pressure'].values.flatten(), '-o') ax.axes.invert_yaxis() ax.set_yscale('log') ax.set_ylim(1e5, 100.) ax.set_xlabel('Kelvin') ax.set_ylabel('Pa') ax.set_title('Radiative equilibrium in a Grey Gas atmosphere') monitor = PlotFunctionMonitor(plot_function) diagnostic = Frierson06LongwaveOpticalDepth() radiation = GrayLongwaveRadiation() time_stepper = AdamsBashforth([radiation]) timestep = timedelta(hours=4) state = get_default_state([radiation, diagnostic]) for i in range(6*7*4*10): state.update(diagnostic(state)) diagnostics, new_state = time_stepper.__call__(state, timestep) state.update(diagnostics) if i % 5 == 0: monitor.store(state) state.update(new_state)
convection.current_time_step = timestep state = get_default_state( [simple_physics, convection, radiation_lw, radiation_sw, slab]) state['air_temperature'].values[:] = 270 state['surface_albedo_for_direct_shortwave'].values[:] = 0.5 state['surface_albedo_for_direct_near_infrared'].values[:] = 0.5 state['surface_albedo_for_diffuse_shortwave'].values[:] = 0.5 state['zenith_angle'].values[:] = np.pi / 2.5 state['surface_temperature'].values[:] = 300. state['ocean_mixed_layer_thickness'].values[:] = 5 state['area_type'].values[:] = 'sea' time_stepper = AdamsBashforth([convection, radiation_lw, radiation_sw, slab]) for i in range(20000): convection.current_time_step = timestep diagnostics, state = time_stepper(state, timestep) state.update(diagnostics) diagnostics, new_state = simple_physics(state, timestep) state.update(diagnostics) if (i + 1) % 20 == 0: monitor.store(state) netcdf_monitor.store(state) print(i, state['surface_temperature'].values) print(state['surface_upward_sensible_heat_flux']) print(state['surface_upward_latent_heat_flux']) state.update(new_state)
def timestepper_class(self, *args, **kwargs): kwargs['order'] = 4 return AdamsBashforth(*args, **kwargs)
import climt import matplotlib.pyplot as plt import numpy as np from sympl import AdamsBashforth from datetime import timedelta incoming_radiation = climt.RRTMGShortwave( cloud_overlap_method=0, solar_constant = 2500) outgoing_radiation = climt.RRTMGLongwave( cloud_overlap_method=0) convection = climt.EmanuelConvection() surface = climt.SlabSurface() state = climt.get_default_state([incoming_radiation, outgoing_radiation, convection]) model_time_step = timedelta(hours=24) model = AdamsBashforth([incoming_radiation, outgoing_radiation, convection]) for step in range(50): diagnostics, new_state = model(state, model_time_step) state.update(diagnostics) state.update(new_state) state['time'] += model_time_step print state['time'], ':', state['air_temperature'].max().values #print state['time'], ':', state['surface_longwave_emissivity'].max().values #print state.keys()