pycontrails.core.models¶
Physical model data structures.
Module Attributes
Model input source types |
|
Model output source types |
|
Model attribute source types |
Functions
|
Interpolate specific humidity against |
|
Interpolate |
|
Raise error for invalid |
|
Update parameter dictionary in place. |
Classes
|
Override buffers in |
|
Base class for physical models. |
|
Class for constructing model parameters. |
- class pycontrails.core.models.AdvectionBuffers(copy_source=True, interpolation_method='linear', interpolation_bounds_error=False, interpolation_fill_value=nan, interpolation_localize=False, interpolation_use_indices=False, interpolation_q_method=None, verify_met=True, downselect_met=True, met_longitude_buffer=(10.0, 10.0), met_latitude_buffer=(10.0, 10.0), met_level_buffer=(40.0, 40.0), met_time_buffer=(np.timedelta64(0, 'h'), np.timedelta64(0, 'h')))¶
Bases:
ModelParamsOverride buffers in
ModelParamsfor advection models.- as_dict()¶
Convert object to dictionary.
We use this method instead of dataclasses.asdict to use a shallow/unrecursive copy. This will return values as Any instead of dict.
- Returns:
dict[str,Any]– Dictionary version of self.
- copy_source = True¶
Copy input
sourcedata on eval
- downselect_met = True¶
Downselect input
MetDataset`to region aroundsource.
- interpolation_bounds_error = False¶
If True, points lying outside interpolation will raise an error
- interpolation_fill_value = nan¶
Used for outside interpolation value if
interpolation_bounds_erroris False
- interpolation_localize = False¶
Experimental. See
pycontrails.core.interpolation.
- interpolation_method = 'linear'¶
Interpolation method. Supported methods include “linear”, “nearest”, “slinear”, “cubic”, and “quintic”. See
scipy.interpolate.RegularGridInterpolatorfor the description of each method. Not all methods are supported by all met grids. For example, the “cubic” method requires at least 4 points per dimension.
- interpolation_q_method = None¶
Experimental. Alternative interpolation method to account for specific humidity lapse rate bias. Must be one of
None,"cubic-spline", or"log-q-log-p". IfNone, no special interpolation is used for specific humidity. The"cubic-spline"method applies a custom stretching of the met interpolation table to account for the specific humidity lapse rate bias. The"log-q-log-p"method interpolates in the log of specific humidity and pressure, then converts back to specific humidity. Only used by models calling tointerpolate_met().
- interpolation_use_indices = False¶
Experimental. See
pycontrails.core.interpolation.
- met_latitude_buffer = (10.0, 10.0)¶
Met latitude buffer [WGS84] for evolution by advection.
- met_level_buffer = (40.0, 40.0)¶
Met level buffer [\(hPa\)] for evolution by advection.
- met_longitude_buffer = (10.0, 10.0)¶
Met longitude [WGS84] buffer for evolution by advection.
- met_time_buffer = (np.timedelta64(0,'h'), np.timedelta64(0,'h'))¶
Met time buffer for input to
Flight.downselect_met()Only applies whendownselect_metis True.
- verify_met = True¶
Call
_verify_met()on model instantiation.
- class pycontrails.core.models.Model(met=None, params=None, **params_kwargs)¶
Bases:
ABCBase class for physical models.
Implementing classes must implement the
eval()method- default_params¶
Default model parameter dataclass
alias of
ModelParams
- 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.
- classmethod ecmwf_met_variables()¶
Return an ECMWF-specific list of required meteorology variables.
- Returns:
tuple[MetVariable]– List of ECMWF-specific variants of required variables
- abstract eval(source=None, **params)¶
Abstract method to handle evaluation.
Implementing classes should override call signature to overload
sourceinputs and model outputs.- Parameters:
source (
ModelInput, optional) – Dataset defining coordinates to evaluate model. Defined by implementing class, but must be a subset of ModelInput. If None,metis assumed to be evaluation points.**params (
Any) – Overwrite model parameters before evaluation.
- Returns:
ModelOutput– Return type depends on implementing model
- 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.
- abstract property long_name¶
Get long name descriptor, annotated on
xr.DataArrayoutputs.
- met¶
Meteorology data
- met_required = False¶
Require meteorology is not None on __init__()
- met_variables¶
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.
- abstract property name¶
class`Flight`.
- Type:
Get model name for use as a data key in
xr.DataArrayor
- optional_met_variables¶
Optional meteorology variables
- params¶
Instantiated model parameters, in dictionary form
- 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_.
- 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.
- source¶
Data evaluated in model
- pycontrails.core.models.ModelInput = pycontrails.core.met.MetDataset | pycontrails.core.vector.GeoVectorDataset | pycontrails.core.flight.Flight | collections.abc.Sequence[pycontrails.core.flight.Flight] | None¶
Model input source types
- pycontrails.core.models.ModelOutput = pycontrails.core.met.MetDataArray | pycontrails.core.met.MetDataset | pycontrails.core.vector.GeoVectorDataset | pycontrails.core.flight.Flight | list[pycontrails.core.flight.Flight]¶
Model output source types
- class pycontrails.core.models.ModelParams(copy_source=True, interpolation_method='linear', interpolation_bounds_error=False, interpolation_fill_value=nan, interpolation_localize=False, interpolation_use_indices=False, interpolation_q_method=None, verify_met=True, downselect_met=True, met_longitude_buffer=(0.0, 0.0), met_latitude_buffer=(0.0, 0.0), met_level_buffer=(0.0, 0.0), met_time_buffer=(np.timedelta64(0, 'h'), np.timedelta64(0, 'h')))¶
Bases:
objectClass for constructing model parameters.
Implementing classes must still use the
@dataclassoperator.- as_dict()¶
Convert object to dictionary.
We use this method instead of dataclasses.asdict to use a shallow/unrecursive copy. This will return values as Any instead of dict.
- Returns:
dict[str,Any]– Dictionary version of self.
- copy_source = True¶
Copy input
sourcedata on eval
- downselect_met = True¶
Downselect input
MetDataset`to region aroundsource.
- interpolation_bounds_error = False¶
If True, points lying outside interpolation will raise an error
- interpolation_fill_value = nan¶
Used for outside interpolation value if
interpolation_bounds_erroris False
- interpolation_localize = False¶
Experimental. See
pycontrails.core.interpolation.
- interpolation_method = 'linear'¶
Interpolation method. Supported methods include “linear”, “nearest”, “slinear”, “cubic”, and “quintic”. See
scipy.interpolate.RegularGridInterpolatorfor the description of each method. Not all methods are supported by all met grids. For example, the “cubic” method requires at least 4 points per dimension.
- interpolation_q_method = None¶
Experimental. Alternative interpolation method to account for specific humidity lapse rate bias. Must be one of
None,"cubic-spline", or"log-q-log-p". IfNone, no special interpolation is used for specific humidity. The"cubic-spline"method applies a custom stretching of the met interpolation table to account for the specific humidity lapse rate bias. The"log-q-log-p"method interpolates in the log of specific humidity and pressure, then converts back to specific humidity. Only used by models calling tointerpolate_met().
- interpolation_use_indices = False¶
Experimental. See
pycontrails.core.interpolation.
- met_latitude_buffer = (0.0, 0.0)¶
Met latitude buffer for input to
Flight.downselect_met(), in WGS84 coordinates. Only applies whendownselect_metis True.
- met_level_buffer = (0.0, 0.0)¶
Met level buffer for input to
Flight.downselect_met(), in [\(hPa\)]. Only applies whendownselect_metis True.
- met_longitude_buffer = (0.0, 0.0)¶
Met longitude buffer for input to
Flight.downselect_met(), in WGS84 coordinates. Only applies whendownselect_metis True.
- met_time_buffer = (np.timedelta64(0,'h'), np.timedelta64(0,'h'))¶
Met time buffer for input to
Flight.downselect_met()Only applies whendownselect_metis True.
- verify_met = True¶
Call
_verify_met()on model instantiation.
- pycontrails.core.models.SourceType = pycontrails.core.met.MetDataset | pycontrails.core.vector.GeoVectorDataset | pycontrails.core.flight.Flight | pycontrails.core.fleet.Fleet¶
Model attribute source types
- pycontrails.core.models.interpolate_gridded_specific_humidity(mda, vector, q_method, log_applied, **interp_kwargs)¶
Interpolate specific humidity against
vectorwith experimentalq_method.- Parameters:
mda (
MetDataArray) – MetDataArray of specific humidity.vector (
GeoVectorDataset) – Flight or GeoVectorDataset instanceq_method (
{None, "cubic-spline", "log-q-log-p"}) – Experimental method to use for interpolating specific humidity.log_applied (
bool) – Whether or not a log transform was applied to specific humidity.**interp_kwargs (
Any,) – Additional keyword only arguments passed to intersect_met.
- Returns:
numpy.ndarray– Interpolated values.
- pycontrails.core.models.interpolate_met(met, vector, met_key, vector_key=None, *, q_method=None, **interp_kwargs)¶
Interpolate
vectoragainstmetgridded data.If
vector_key(=``met_key`` by default) already exists, return values atvector_key.Mutates parameter
vectorin place by attaching new key and returns values.- Parameters:
met (
MetDataset | None) – Met data to interpolate againstvector (
GeoVectorDataset) – Flight or GeoVectorDataset instancemet_key (
str) – Key of met variable inmet.vector_key (
str, optional) – Key of variable to attach tovector. By default, usemet_key.q_method (
str, optional) – Experimental method to use for interpolating specific humidity. SeeModelParamsfor more information.**interp_kwargs (
Any,) – Additional keyword only arguments passed toGeoVectorDataset.intersect_met(). For example,level=[...].
- Returns:
npt.NDArray[np.floating]– Interpolated values.- Raises:
KeyError – Parameter
met_keynot found inmet.
- pycontrails.core.models.raise_invalid_q_method_error(q_method)¶
Raise error for invalid
q_method.- Parameters:
q_method (
str) –q_methodto raise error for.- Raises:
ValueError –
q_methodis not one ofNone,"log-q-log-p", or"cubic-spline".
- pycontrails.core.models.update_param_dict(param_dict, new_params)¶
Update parameter dictionary in place.
- Parameters:
param_dict (
dict[str,Any]) – Active model parameter dictionarynew_params (
dict[str,Any]) – Model parameters to update, as a dictionary
- Raises:
KeyError – Raises when
new_paramskey is not found inparam_dict