def set_constants_from_dict(constant_descriptions): """ Modify/Add constants in the library. Args: constant_descriptions (dict): Dictionary containing the description of the constants. The key should be the name of the constant, and the value should be a dictionary containing the following keys: * value (float): The value assigned. * units (string): The units of the value, e.g, m/s, J/kg. """ for name in constant_descriptions.keys(): value = constant_descriptions[name]['value'] units = constant_descriptions[name]['units'] set_constant(name, value, units)
def test_setting_existing_constant(): set_constant('seconds_per_day', 100000, 'seconds/day') new_constant = default_constants['seconds_per_day'] assert new_constant.values == 100000 assert new_constant.units == 'seconds/day'
def test_setting_new_constant(): set_constant('my_own_constant', 10., 'W m^-1 degK^-1') assert 'my_own_constant' in default_constants new_constant = default_constants['my_own_constant'] assert new_constant.values == 10. assert new_constant.units == 'W m^-1 degK^-1'
def get_grid(nx=None, ny=None, nz=28, n_ice_interface_levels=10, p_surf_in_Pa=None, p_toa_in_Pa=None, proportion_sigma_levels=0.1, proportion_isobaric_levels=0.25, x_name='longitude', y_name='latitude', latitude_grid='gaussian'): """ Args: nx : int, optional Number of longitudinal points. ny : int, optional Number of latitudinal points. nz : int, optional Number of vertical mid levels. n_ice_interface_levels (int, optional): Number of vertical interface levels to use for ice. Use None to disable the ice vertical grid. p_surf_in_Pa : float, optional Surface pressure in Pa. x_name : str, optional Name of latitudinal dimension y_name : str, optional Name of longitudinal dimension latitude_grid : 'gaussian' or 'regular' Type of spacing to use for the latitudinal grid. Returns: grid_state: dict A model state containing grid quantities. """ if p_surf_in_Pa is None: p_surf_in_Pa = get_constant('reference_air_pressure', 'Pa') if p_toa_in_Pa is None: p_toa_in_Pa = get_constant('top_of_model_pressure', 'Pa') else: set_constant('top_of_model_pressure', p_toa_in_Pa, 'Pa') return_state = get_hybrid_sigma_pressure_levels( nz + 1, p_surf_in_Pa, p_toa_in_Pa, proportion_isobaric_levels, proportion_sigma_levels) return_state['surface_air_pressure'] = DataArray(p_surf_in_Pa, dims=[], attrs={'units': 'Pa'}) return_state['time'] = datetime(2000, 1, 1) return_state.update(HybridSigmaPressureDiagnosticComponent()(return_state)) if nx is not None: return_state['longitude'] = DataArray( np.linspace(0., 360., nx * 2, endpoint=False)[:-1:2], dims=[x_name], attrs={'units': 'degrees_east'}, ) if ny is not None: if latitude_grid.lower() == 'regular': return_state['latitude'] = DataArray( np.linspace(-90., 90., ny * 2 + 1, endpoint=True)[1:-1:2], dims=[y_name], attrs={'units': 'degrees_north'}, ) elif latitude_grid.lower() == 'gaussian': lat, lat_interface = gaussian_latitudes(ny) return_state['latitude'] = DataArray( lat, dims=[y_name], attrs={'units': 'degrees_north'}, ) else: raise ValueError( 'latitude_grid can be either regular or gaussian. ' + 'Other grid types are currently not supported.') if n_ice_interface_levels is not None: return_state['height_on_ice_interface_levels'] = DataArray( np.zeros(n_ice_interface_levels), dims=['ice_interface_levels'], attrs={'units': 'm'}, ) return return_state
# -*- coding: utf-8 -*- import sympl from ._core import (get_default_state, get_grid, mass_to_volume_mixing_ratio, get_interface_values, numpy_version_of, bolton_q_sat, bolton_dqsat_dT, calculate_q_sat, list_available_constants, set_constants_from_dict) from ._components import ( Frierson06LongwaveOpticalDepth, GrayLongwaveRadiation, HeldSuarez, GridScaleCondensation, BergerSolarInsolation, SimplePhysics, RRTMGLongwave, RRTMGShortwave, EmanuelConvection, SlabSurface, GFSDynamicalCore, DcmipInitialConditions, IceSheet, Instellation, DryConvectiveAdjustment) sympl.set_constant('top_of_model_pressure', 20., 'Pa') __all__ = (get_default_state, get_grid, mass_to_volume_mixing_ratio, numpy_version_of, get_interface_values, list_available_constants, set_constants_from_dict, bolton_q_sat, bolton_dqsat_dT, calculate_q_sat, Frierson06LongwaveOpticalDepth, GrayLongwaveRadiation, HeldSuarez, GridScaleCondensation, BergerSolarInsolation, SimplePhysics, RRTMGLongwave, RRTMGShortwave, EmanuelConvection, SlabSurface, GFSDynamicalCore, DcmipInitialConditions, IceSheet, Instellation, DryConvectiveAdjustment) __version__ = '0.16.2'
from datetime import timedelta import matplotlib.pyplot as plt def plot_function(fig, state): ax = fig.add_subplot(1, 1, 1) CS = ax.contourf(state['longitude'], state['latitude'], state['surface_air_pressure'].to_units('mbar')) plt.colorbar(CS) ax.set_title('Surface Pressure at: '+str(state['time'])) monitor = PlotFunctionMonitor(plot_function) set_constant('reference_air_pressure', value=1e5, units='Pa') dycore = climt.GFSDynamicalCore() dcmip = climt.DcmipInitialConditions(add_perturbation=True) grid = climt.get_grid(nx=128, ny=64, nz=20) my_state = climt.get_default_state([dycore], grid_state=grid) timestep = timedelta(minutes=10) out = dcmip(my_state) my_state.update(out) for i in range(1000): diag, output = dycore(my_state, timestep)
fig.tight_layout() fields_to_store = [ 'air_temperature', 'air_pressure', 'eastward_wind', 'northward_wind', 'air_pressure_on_interface_levels', 'surface_pressure', 'upwelling_longwave_flux_in_air', 'specific_humidity', 'surface_temperature', 'convective_heating_rate', 'latitude', 'longitude' ] # Create plotting object monitor = PlotFunctionMonitor(plot_function) netcdf_monitor = NetCDFMonitor('gcm_without_seasonal_cycle.nc', write_on_store=True, store_names=fields_to_store) set_constant('stellar_irradiance', value=200, units='W m^-2') model_time_step = timedelta(minutes=10) # Create components convection = climt.EmanuelConvection() simple_physics = TimeDifferencingWrapper(climt.SimplePhysics()) radiation_step = timedelta(hours=1) radiation_lw = UpdateFrequencyWrapper(climt.RRTMGLongwave(), radiation_step) radiation_sw = UpdateFrequencyWrapper(climt.RRTMGShortwave(), radiation_step) slab_surface = climt.SlabSurface()
def test_setting_wrong_units(): with pytest.raises(ValueError) as excinfo: set_constant('abcd', 100, 'Wii') assert 'valid unit' in str(excinfo.value)