pycontrails.models.apcemm.APCEMM¶
- class pycontrails.models.apcemm.APCEMM(met, apcemm_path, apcemm_root=None, apcemm_input_params=None, cachestore=None, params=None, **params_kwargs)¶
Bases:
ModelRun APCEMM as a pycontrails
Model.This class acts as an adapter between the pycontrails
Modelinterface (shared with other contrail models) and APCEMM’s native interface.APCEMM was developed at the MIT Laboratory for Aviation and the Environment and is described in [Fritz et al., 2020].
- Parameters:
met (
MetDataset) – Pressure level dataset containingmet_variablesvariables. See Notes for variable names by data source.apcemm_path (
pathlib.Path | str) – Path to APCEMM executable. See Notes for information about acquiring and compiling APCEMM.apcemm_root (
pathlib.Path | str, optional) – Path to APCEMM root directory, used to setinput_background_conditionsandinput_engine_emissionsbased on the structure of the APCEMM GitHub repository. If not provided, pycontrails will use the default paths defined inAPCEMMInput.apcemm_input_params (
APCEMMInput, optional) – Value for APCEMM input parameters defined inAPCEMMInput. If provided, values forinput_background_conditionorinput_engine_emissionswill override values set based onapcemm_root. Attempting to provide values for input parameters that are determined automatically by this interface will result in an error. See Notes for detailed information about YAML file generation.cachestore (
CacheStore, optional) –CacheStoreused to store APCEMM run directories. If not provided, uses aDiskCacheStore. See Notes for detailed information about the file structure for APCEMM simulations.params (
dict[str,Any], optional) – Override APCEMM model parameters with dictionary. SeeAPCEMMParamsfor model parameters.**params_kwargs (
Any) – Override Cocip model parameters with keyword arguments. SeeAPCEMMParamsfor model parameters.
Notes
Meteorology
APCEMM requires temperature, humidity, gepotential height, and winds. Geopotential height is required because APCEMM expects meteorological fields on height rather than pressure surfaces. See
met_variablesfor the list of required variables.Variable keys for pressure level data¶ Parameter
ECMWF
GFS
Air Temperature
air_temperatureair_temperatureSpecific Humidity
specific_humidityspecific_humidityGeopotential/Geopotential Height
geopotentialgeopotential_heightEastward wind
eastward_windeastward_windNorthward wind
northward_windnorthward_windVertical velocity
lagrangian_tendency_of_air_pressurelagrangian_tendency_of_air_pressureAcquiring and compiling APCEMM
Users are responsible for acquiring and compiling APCEMM. The APCEMM source code is available through GitHub, and instructions for compiling APCEMM are available in the repository.
Note that APCEMM does not provide versioned releases, and future updates may break this interface. To guarantee compatibility between this interface and APCEMM, users should use commit 9d8e1ee from the APCEMM repository.
Configuring APCEMM YAML files
APCEMMInputprovides low-level control over the contents of YAML files used as APCEMM input. YAML file contents can be controlled by passing custom parameters in a dictionary through theapcemm_input_paramsparameter. Note, however, thatAPCEMMsets a number of APCEMM input parameters automatically, and attempting to override any automatically-determined parameters usingapcemm_input_paramswill result in an error. A list of automatically-determined parameters is available indynamic_yaml_params.Simulation initialization, execution, and postprocessing
This interface initializes, runs, and postprocesses APCEMM simulations in four stages:
A
DryAdvectionmodel is used to generate trajectories for contrails initialized at each flight waypoint. This is a necessary preprocessing step because APCEMM is a Lagrangian model and does not explicitly track changes in plume location over time. This step also provides time-dependent azimuths that define the orientation of advected contrails, which is required to compute contrail-normal wind shear from horizontal winds. Results from the trajectory calculation are stored intrajectories.Model parameters and results from the trajectory calculation are used to generate YAML files with APCEMM input parameters and netCDF files with meteorology data used by APCEMM simulations. A separate pair of files is generated for each waypoint processed by APCEMM. Files are saved as
apcemm_waypoint_<i>/input.yamlandapcemm_waypoint_<i>/input.ncin the modelcachestore, where<i>is replaced by the index of each simulated flight waypoint.A separate APCEMM simulation is run in each run directory inside the model
cachestore. Simulations are independent and can be run in parallel (controlled by then_jobsparameter inAPCEMMParams). Standard output and error streams from each simulation are saved inapcemm_waypoint_<i>/stdout.logandapcemm_waypoint_<i>/stderr.log, and APCEMM output is saved in a subdirectory specified by theoutput_directorymodel parameter (“out” by default).APCEMM simulation output is postprocessed. After postprocessing:
A
statuscolumn is attached to theFlightreturned byeval(). This column contains"NoSimulation"for waypoints where no simulation was run and the contents of the APCEMMstatus_case0output file for other waypoints.A
pd.DataFrameis created and stored invortex. This dataframe contains time series output from the APCEMM “early plume model” of the aircraft exhaust plume and downwash vortex, read fromMicro_000000.outoutput files saved by APCEMM.If APCEMM simulated at least one persistent contrail, A
pd.DataFrameis created and stored incontrail. This dataframe contains paths to netCDF files, saved at prescribed time intervals during the APCEMM simulation, and can be used to open APCEMM output (e.g., usingxr.open_dataset()) for further analysis.
Numerics
APCEMM simulations are initialized at flight waypoints and represent the evolution of the cross-section of contrails formed at each waypoint. APCEMM does not explicitly model the length of contrail segments and does not include any representation of deformation by divergent flow. APCEMM output represents properties of cross-sections of contrails formed at flight waypoints, not properties of contrail segments that form between flight waypoints. Unlike
Cocip, output produced by this interface does not include trailing NaN values.Known limitations
Engine core exit temperature and bypass area are not provided as output by pycontrails aircraft performance models and are currently set to static values in APCEMM input files. These parameters will be computed dynamically in a future release.
APCEMM does not compute contrail radiative forcing internally. Radiative forcing must be computed offline by the user. Tools for radiative forcing calculations may be included in a future version of the interface.
APCEMM currently produces different results in simulations that do not read vertical velocity data from netCDF input files and in simulations that read vertical velocities that are set to 0 everywhere (see https://github.com/MIT-LAE/APCEMM/issues/17). Reading of vertical velocity data from netCDF input files will be disabled in this interface until this issue is resolved.
References
- __init__(met, apcemm_path, apcemm_root=None, apcemm_input_params=None, cachestore=None, params=None, **params_kwargs)¶
Methods
__init__(met, apcemm_path[, apcemm_root, ...])apcemm_file(waypoint[, name])Get path to file from an APCEMM simulation initialized at a specific waypoint.
Compute fields required for APCEMM initial conditions and attach to
source.Calculate Lagrangian trajectories using a
DryAdvectionmodel.Return an ECMWF-specific list of required meteorology variables.
eval([source])Set up and run APCEMM simulations initialized at flight waypoints.
generate_apcemm_input(waypoint)Generate APCEMM yaml and netCDF input files for a single waypoint.
Return a model-agnostic list of required meteorology variables.
get_data_param(other, key[, default, set_attr])Get data from other source-compatible object with default set by model parameter key.
get_source_param(key[, default, set_attr])Get source data with default set by parameter key.
Return a GFS-specific list of required meteorology variables.
Process APCEMM output.
Ensure that
metis a MetDataset.require_source_type(type_)Ensure that
sourceistype_.run_apcemm(waypoints)Run APCEMM over multiple waypoints.
set_source([source])Attach original or copy of input
sourcetosource.set_source_met([optional, variable])Ensure or interpolate each required
met_variablesonsource.transfer_met_source_attrs([source])Transfer met source metadata from
mettosource.update_params([params])Update model parameters on
params.Attributes
Overridden APCEMM input parameters
Path to APCEMM executable
CacheStore for APCEMM run directories
Paths to APCEMM netCDF output at prescribed time intervals
Output from trajectory calculation
Time series output from the APCEMM early plume model
Set of
APCEMMInputattributes set dynamically by this model.Generate a unique hash for model instance.
Shortcut to create interpolation arguments from
params.Met data is not optional
Require meteorology is not None on __init__()
Required meteorology pressure level variables.
Instantiated model parameters, in dictionary form
Last flight processed in
eval()Set of required parameters if processing already complete on
metinput.Optional meteorology variables
- apcemm_file(waypoint, name=None)¶
Get path to file from an APCEMM simulation initialized at a specific waypoint.
- Parameters:
- Returns:
str– Path to a file in the APCEMM simulation root directory, ifnameis provided, or the path to the APCEMM simulation root directory otherwise.
- apcemm_input_params¶
Overridden APCEMM input parameters
- apcemm_path¶
Path to APCEMM executable
- attach_apcemm_initial_conditions()¶
Compute fields required for APCEMM initial conditions and attach to
source.This modifies
sourceby attaching quantities derived from meterology data and aircraft performance calculations.
- cachestore¶
CacheStore for APCEMM run directories
- compute_lagrangian_trajectories()¶
Calculate Lagrangian trajectories using a
DryAdvectionmodel.Lagrangian trajectories provide the expected time-dependent location (longitude, latitude, and altitude) and orientation (azimuth) of contrails formed by the input source. This information is used to extract time series of meteorological profiles at the contrail location from input meteorology data, and to compute contrail-normal horizontal shear from horizontal winds.
The length of Lagrangian trajectories is set by the
max_ageparameter, and trajectories are integrated using a time step set by thedt_lagrangianparameter. Contrails are advected both horizontally and vertically, and a fixed sedimentation velocity (set by thesedimentation_rateparameter) can be included to represent contrail sedimentation.Results of the trajectory calculation are attached to
trajectories.
- contrail¶
Paths to APCEMM netCDF output at prescribed time intervals
- default_params¶
alias of
APCEMMParams
- downselect_met()¶
Downselect
metdomain to the max/min bounds ofsource.Override this method if special handling is needed in met down-selection.
sourcemust be defined before callingdownselect_met().This method copies and re-assigns
metusingmet.copy()to avoid side-effects.
- Raises:
ValueError – Raised if
sourceis not defined. Raised ifsourceis not aGeoVectorDataset.
- property dynamic_yaml_params¶
Set of
APCEMMInputattributes set dynamically by this model.Other
APCEMMInputattributes can be set statically by passing parameters inapcemm_input_paramsto theAPCEMMconstructor.
- classmethod ecmwf_met_variables()¶
Return an ECMWF-specific list of required meteorology variables.
- Returns:
tuple[MetVariable]– List of ECMWF-specific variants of required variables
- eval(source=None, **params)¶
Set up and run APCEMM simulations initialized at flight waypoints.
Simulates the formation and evolution of contrails from a Flight using the APCEMM plume model described in Fritz et. al. (2020) [Fritz et al., 2020].
- Parameters:
source (
Flight | None) – Input Flight to model.**params (
Any) – Overwrite model parameters before eval.
- Returns:
Flight | NoReturn– Flight with exit status of APCEMM simulations. Detailed APCEMM outputs are attached to modelvortexandcontrailattributes (seeAPCEMMnotes for details).
References
- generate_apcemm_input(waypoint)¶
Generate APCEMM yaml and netCDF input files for a single waypoint.
For details about generated input files, see
APCEMMnotes.- Parameters:
waypoint (
int) – Waypoint for which to generate input files.
- classmethod generic_met_variables()¶
Return a model-agnostic list of required meteorology variables.
- Returns:
tuple[MetVariable]– List of model-agnostic variants of required variables
- get_data_param(other, key, default=<object object>, *, set_attr=True)¶
Get data from other source-compatible object with default set by model parameter key.
Retrieves data with the following hierarchy:
other.data[key]. Returnsnp.ndarray | xr.DataArray.other.attrs[key]params[key]default
In case 3., the value of
params[key]is attached toother.attrs[key]unlessset_attris set to False.- Parameters:
- Returns:
Any– Value(s) found for key inotherdata,otherattrs, or model params- Raises:
KeyError – Raises KeyError if key is not found in any location and
defaultis not provided.
- get_source_param(key, default=<object object>, *, set_attr=True)¶
Get source data with default set by parameter key.
Retrieves data with the following hierarchy:
source.data[key]. Returnsnp.ndarray | xr.DataArray.source.attrs[key]params[key]default
In case 3., the value of
params[key]is attached tosource.attrs[key]unlessset_attris set to False.- Parameters:
- Returns:
Any– Value(s) found for key in source data, source attrs, or model params- Raises:
KeyError – Raises KeyError if key is not found in any location and
defaultis not provided.
- classmethod gfs_met_variables()¶
Return a GFS-specific list of required meteorology variables.
- Returns:
tuple[MetVariable]– List of GFS-specific variants of required variables
- property hash¶
Generate a unique hash for model instance.
- Returns:
str– Unique hash for model instance (sha1)
- property interp_kwargs¶
Shortcut to create interpolation arguments from
params.The output of this is useful for passing to
interpolate_met().- Returns:
dict[str,Any]– Dictionary with keys”method”
”bounds_error”
”fill_value”
”localize”
”use_indices”
”q_method”
as determined by
params.
- long_name = 'Interface to APCEMM plume model'¶
- met¶
Met data is not optional
- met_required = True¶
Require meteorology is not None on __init__()
- met_variables = (MetVariable(short_name='t', standard_name='air_temperature', long_name='Air Temperature', level_type='isobaricInhPa', ecmwf_id=130, grib1_id=11, grib2_id=(0, 0, 0), units='K', amip='ta', description='Air temperature is the bulk temperature of the air, not the surface (skin) temperature.'), MetVariable(short_name='q', standard_name='specific_humidity', long_name='Specific Humidity', level_type='isobaricInhPa', ecmwf_id=133, grib1_id=51, grib2_id=(0, 1, 0), units='kg kg**-1', amip='hus', description='Specific means per unit mass. Specific humidity is the mass fraction of water vapor in (moist) air.'), (MetVariable(short_name='z', standard_name='geopotential', long_name='Geopotential', level_type='isobaricInhPa', ecmwf_id=129, grib1_id=6, grib2_id=(0, 3, 4), units='m**2 s**-2', amip=None, description='Geopotential is the sum of the specific gravitational potential energy relative to the geoid and the specific centripetal potential energy.'), MetVariable(short_name='gh', standard_name='geopotential_height', long_name='Geopotential Height', level_type='isobaricInhPa', ecmwf_id=156, grib1_id=7, grib2_id=(0, 3, 5), units='m', amip='zg', description='Geopotential is the sum of the specific gravitational potential energy relative to the geoid and the specific centripetal potential energy. Geopotential height is the geopotential divided by the standard acceleration due to gravity. It is numerically similar to the altitude (or geometric height) and not to the quantity with standard name height, which is relative to the surface.')), MetVariable(short_name='u', standard_name='eastward_wind', long_name='Eastward Wind', level_type='isobaricInhPa', ecmwf_id=131, grib1_id=33, grib2_id=(0, 2, 2), units='m s**-1', amip='ua', description='"Eastward" indicates a vector component which is positive when directed eastward (negative westward). Wind is defined as a two-dimensional (horizontal) air velocity vector, with no vertical component.'), MetVariable(short_name='v', standard_name='northward_wind', long_name='Northward Wind', level_type='isobaricInhPa', ecmwf_id=132, grib1_id=34, grib2_id=(0, 2, 3), units='m s**-1', amip='va', description='"Northward" indicates a vector component which is positive when directed northward (negative southward). Wind is defined as a two-dimensional (horizontal) air velocity vector, with no vertical component.'), MetVariable(short_name='w', standard_name='lagrangian_tendency_of_air_pressure', long_name='Vertical Velocity (omega)', level_type='isobaricInhPa', ecmwf_id=135, grib1_id=39, grib2_id=(0, 2, 8), units='Pa s**-1', amip='wap', description='The Lagrangian tendency of air pressure, often called "omega", plays the role of the upward component of air velocity when air pressure is being used as the vertical coordinate. If the vertical air velocity is upwards, it is negative when expressed as a tendency of air pressure; downwards is positive. Air pressure is the force per unit area which would be exerted when the moving gas molecules of which the air is composed strike a theoretical surface of any orientation.'))¶
Required meteorology pressure level variables. Each element in the list is a
MetVariableor atuple[MetVariable]. If element is atuple[MetVariable], the variable depends on the data source and the tuple must include entries for a model-agnostic variable, an ECMWF-specific variable, and a GFS-specific variable. Only one of the three variable in the tuple is required for model evaluation.
- name = 'apcemm'¶
- optional_met_variables¶
Optional meteorology variables
- params¶
Instantiated model parameters, in dictionary form
- process_apcemm_output()¶
Process APCEMM output.
After processing, a
statuscolumn will be attached tosource, and additional output data will be attached tovortexandcontrail. For details about contents of APCEMM output files, seeAPCEMMnotes.
- processed_met_variables¶
Set of required parameters if processing already complete on
metinput.
- require_met()¶
Ensure that
metis a MetDataset.- Returns:
MetDataset– Returns reference tomet. This is helpful for type narrowingmetwhen meteorology is required.- Raises:
ValueError – Raises when
metis None.
- require_source_type(type_)¶
Ensure that
sourceistype_.- Returns:
_Source– Returns reference tosource. This is helpful for type narrowingsourceto specific type(s).- Raises:
ValueError – Raises when
sourceis not_type_.
- run_apcemm(waypoints)¶
Run APCEMM over multiple waypoints.
Multiple waypoints will be processed in parallel if the
APCEMMn_jobsparameter is set to a value larger than 1.- Parameters:
waypoints (
list[int]) – List of waypoints at which to initialize simulations.
- set_source(source=None)¶
Attach original or copy of input
sourcetosource.- Parameters:
source (
MetDataset | GeoVectorDataset | Flight | Iterable[Flight] | None) – Parametersourcepassed ineval(). If None, an empty MetDataset with coordinates likemetis set tosource.
See also
- set_source_met(optional=False, variable=None)¶
Ensure or interpolate each required
met_variablesonsource.For each variable in
met_variables, checksourcefor data variable with the same name.For
GeoVectorDatasetsources, try to interpolatemetif variable does not exist.For
MetDatasetsources, try to get data frommetif variable does not exist.- Parameters:
optional (
bool, optional) – Includeoptional_met_variablesvariable (
MetVariable | Sequence[MetVariable] | None, optional) – MetVariable to set, frommet_variables. If None, set all variables inmet_variablesandoptional_met_variablesifoptionalis True.
- Raises:
ValueError – Variable does not exist and
sourceis a MetDataset.
- trajectories¶
Output from trajectory calculation
- update_params(params=None, **params_kwargs)¶
Update model parameters on
params.- Parameters:
params (
dict[str,Any], optional) – Model parameters to update, as dictionary. Defaults to {}**params_kwargs (
Any) – Override keys inparamswith keyword arguments.
- vortex¶
Time series output from the APCEMM early plume model