Represents a dataset where measurements are spread over multiple
    files.

    If filenames contain timestamps, this information is used to determine
    the time for a granule or measurement.  If filenames do not contain
    timestamps, this information is obtained from the file contents.

    Attributes:

        basedir (pathlib.Path or str):
            Describes the directory under which all granules are located.
            Can be either a string or a pathlib.Path object.

        subdir (pathlib.Path or str):
            Describes the directory within basedir where granules are
            located.  May contain string formatting directives where
            particular fields are replaces, such as `year`, `month`, and
            `day`.  For example: `subdir = '{year}/{month}'`.  Sorting
            cannot be more narrow than by day.

        re (str):
            Regular expression that should match valid granule files within
            `basedir` / `subdir`.  Should use symbolic group names to capture
            relevant information when possible, such as starting time, orbit
            number, etc.  For time identification, relevant fields are
            contained in MultiFileDataset.date_info, where each field also
            exists in a version with "_end" appended.
            MultiFileDataset.refields contains all recognised fields.

            If any _end fields are found, the ending time is equal to the
            beginning time with any _end fields replaced.  If no _end
            fields are found, the `granule_duration` attribute is used to
            determine the ending time, or the file is read to get the
            ending time (hopefully the header is enough).

        granule_cache_file (pathlib.Path or str):
            If set, use this file to cache information related to
            granules.  This is used to cache granule times if those are
            not directly inferred from the filename.  Otherwise, this is
            not used.  The full path to this file shall be `basedir` /
            `granule_cache_file`.

        granule_duration (datetime.timedelta):
            If the filename contains starting times but no ending times,
            granule_duration is used to determine the ending time.  This
            should be a datetime.timedelta object.


Represents datasets where each file contains one measurement.

    An example of this would be ACE-FTS, or some radio-occultation datasets.

    Attributes:

        filename_fields (Mapping[str, dtype])

            dict with {name, dtype} for fields that should be copied from
            the filename (as obtained with self.re) into the header


Mixin for any dataset where the contents are in NetCDF.

    This may provide a good default for any NetCDF-based dataset.  The
    reading routine will take the most commonly occurring dimension as the
    ndarray axes, and the rest within structured multidimensional dtype.

    USE WITH CARE!  PROVISIONAL API!

    This one should use xarray, of course!  See
    https://arts.mi.uni-hamburg.de/trac/rt/ticket/145


For any dataset created by typhon or its dependencies.

    Currently supports only saving to npz, through the save_npz method.
    Eventually, should also support other file formats, in particular
    NetCDF.


A deque-like object sliding through a dataset.

    For a particular dataset, keep data corresponding to time period in
    memory.  When reading new data, discard a corresponding time period of
    data in the past.  This should be useful to process longer periods of
    data that do not fit into memory, to calculate sliding window
    statistics, or to perform processing where values nearby in time are
    required.


Error when trying to collapse / expand invalid collocation data


Class for finding and storing collocations between FileSet objects

    If you want to find collocations between Arrays, use :func:`collocate`
    instead.


Colors for printing messages to stdout.


    Logs metrics by land cover.

    Note: Only 0 and 1 classes are taken into account.


A Sampler which performs oversampling in imbalanced datasets.


Image to Patch Embedding


EF segmentation network.


Resnet of 8 downsampling + BIT + bitemporal feature Differencing + a small CNN


    Args:
        encoder_name: Name of the classification model that will be used as an encoder (a.k.a backbone)
            to extract features of different spatial resolution
        encoder_depth: A number of stages used in encoder in range [3, 5]. Each stage generate features
            two times smaller in spatial dimensions than previous one (e.g. for depth 0 we will have features
            with shapes [(N, C, H, W),], for depth 1 - [(N, C, H, W), (N, C, H // 2, W // 2)] and so on).
            Default is 5
        encoder_weights: One of **None** (random initialization), **"imagenet"** (pre-training on ImageNet) and
            other pretrained weights (see table with available weights for each encoder_name)
        decoder_channels: List of integers which specify **in_channels** parameter for convolutions used in decoder.
            Length of the list should be the same as **encoder_depth**
        decoder_use_batchnorm: If **True**, BatchNorm2d layer between Conv2D and Activation layers
            is used. If **"inplace"** InplaceABN will be used, allows to decrease memory consumption.
            Available options are **True, False, "inplace"**
        decoder_attention_type: Attention module used in decoder of the model. Available options are
            **None** and **scse** (https://arxiv.org/abs/1808.08127).
        in_channels: A number of input channels for the model, default is 3 (RGB images)
        classes: A number of classes for output mask (or you can think as a number of channels of output mask)
        activation: An activation function to apply after the final convolution layer.
            Available options are **"sigmoid"**, **"softmax"**, **"logsoftmax"**, **"tanh"**, **"identity"**,
                **callable** and **None**.
            Default is **None**

    Returns:
        ``torch.nn.Module``: Unet


Add encoder functionality such as:
    - output channels specification of feature tensors (produced by encoder)
    - patching first convolution for arbitrary input channels


Abstract base model class, don't use this class for model training.

    Use subclasses of this class for training/evaluating different models, e.g. use `CudaLSTM` for training a standard
    LSTM model or `EA-LSTM` for training an Entity-Aware-LSTM. Refer to
    `Documentation/Modelzoo <https://neuralhydrology.readthedocs.io/en/latest/usage/models.html>`_ for a full list of
    available models and how to integrate a new model.

    Parameters
    ----------
    cfg : Config
        The run configuration.


LSTM model class, which relies on PyTorch's CUDA LSTM class.

    This class implements the standard LSTM combined with a model head, as specified in the config. All features
    (time series and static) are concatenated and passed to the LSTM directly. If you want to embedd the static features
    prior to the concatenation, use the `EmbCudaLSTM` class.
    To control the initial forget gate bias, use the config argument `initial_forget_bias`. Often it is useful to set
    this value to a positive value at the start of the model training, to keep the forget gate closed and to facilitate
    the gradient flow.
    The `CudaLSTM` class does only support single timescale predictions. Use `MTSLSTM` to train a model and get
    predictions on multiple temporal resolutions at the same time.

    Parameters
    ----------
    cfg : Config
        The run configuration.


Single-layer regression head with different output activations.

    Parameters
    ----------
    n_in : int
        Number of input neurons.
    n_out : int
        Number of output neurons.
    activation: str, optional
        Output activation function. Can be specified in the config using the `output_activation` argument. Supported
        are {'linear', 'relu', 'softplus'}. If not specified (or an unsupported activation function is specified), will
        default to 'linear' activation.


Auxiliary class to build (multi-layer) fully-connected networks.

    This class is used in different places of the codebase to build fully-connected networks. E.g., the `EA-LSTM` and
    `EmbCudaLSTM` use this class to create embedding networks for the static inputs.
    Use the config argument `embedding_hiddens` to specify the hidden neurons of the embedding network. If only one
    number is specified the embedding network consists of a single linear layer that maps the input into the specified
    dimension.
    Use the config argument `embedding_activation` to specify the activation function for intermediate layers. Currently
    supported are 'tanh' and 'sigmoid'.
    Use the config argument `embedding_dropout` to specify the dropout rate in intermediate layers.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    input_size : int, optional
        Number of input features. If not specified, the number of input features is the sum of all static inputs (i.e.,
        catchment attributes, one-hot-encoding, etc.)


ODE-LSTM from [#]_.

    An ODE-RNN post-processes the hidden state of a normal LSTM.
    Parts of this code are derived from https://github.com/mlech26l/learning-long-term-irregular-ts.

    The forward pass in this model works somewhat differently than the other models, because ODE-LSTM relies on
    irregularly timed samples. To simulate such irregularity, we aggregate parts of the input sequence to random
    frequencies. While doing so, we try to take care that we don't aggregate too coarsely right before the model
    should create a high-frequency prediction.

    Since this aggregation means that parts of the input sequence are at random frequencies, we cannot easily
    return predictions for the full input sequence at each frequency. Instead, we only return sequences of length
    predict_last_n for each frequency (we do not apply the random aggregation to these last time steps).

    The following describes the aggregation strategy implemented in the forward method:

    1. slice one: random-frequency steps (cfg.ode_random_freq_lower_bound <= freq <= lowest-freq) until beginning
                  of the second-lowest frequency input sequence.
    2. slice two: random-frequency steps (lowest-freq <= freq <= self._frequencies[1]) until beginning of
                  next-higher frequency input sequence.
    3. repeat step two until beginning of highest-frequency input sequence.
    4. slice three: random-frequency steps (self._frequencies[-2] <= freq <= highest-freq) until predict_last_n
                    of the lowest frequency.
    5. lowest-frequency steps to generate predict_last_n lowest-frequency predictions.
    6. repeat steps four and five for the next-higher frequency (using the same random-frequency bounds but
       generating predictions for the next-higher frequency).

    Parameters
    ----------
    cfg : Config
        The run configuration.

    References
    ----------
    .. [#] Lechner, M.; Hasani, R.: Learning Long-Term Dependencies in Irregularly-Sampled Time Series. arXiv, 2020,
        https://arxiv.org/abs/2006.04418.


An ODE-RNN cell (Adapted from https://github.com/mlech26l/learning-long-term-irregular-ts) [#]_.

    Parameters
    ----------
    input_size : int
        Input dimension
    hidden_size : int
        Size of the cell's hidden state
    num_unfolds : int
        Number of steps into which each timestep will be broken down to solve the ODE.
    method : {'euler', 'heun', 'rk4'}
        Method to use for ODE solving (Euler's method, Heun's method, or Runge-Kutta 4)

    References
    ----------
    .. [#] Lechner, M.; Hasani, R.: Learning Long-Term Dependencies in Irregularly-Sampled Time Series. arXiv, 2020,
        https://arxiv.org/abs/2006.04418.


Replication of the CuDNN LSTM

    The idea of this model is to be able to train an LSTM using the nn.LSTM layer, which uses the
    optimized CuDNN implementation, and later to copy the weights into this model for a more
    in-depth network analysis.
    Can be used with trained models. For instance, from the `CudaLSTM` or `EmbCudaLSTM` classes, the CudNN LSTM layer can be
    accessed as `model.lstm`, where `model` is a `CudaLSTM` or `EmbCudaLSTM` instance.

    Note: Currently only supports one-layer CuDNN LSTMs

    Parameters
    ----------
    cfg : Config
        The run configuration.

    Example
    -------
    >>> # copy weights from PyTorch LSTM to this LSTM implementation
    >>> cudnn_lstm = nn.LSTM(input_size=15, hidden_size=128, num_layers=1)
    >>> lstm = LSTM(cfg=cfg)
    >>> lstm.copy_weights(cudnn_lstm)


Multi-Timescale LSTM (MTS-LSTM) from Gauch et al. (preprint to be released soon).

    An LSTM architecture that allows simultaneous prediction at multiple timescales within one model.
    There are two flavors of this model: MTS-LTSM and sMTS-LSTM (shared MTS-LSTM). The MTS-LSTM processes inputs at
    low temporal resolutions up to a point in time. Then, the LSTM splits into one branch for each target timescale.
    Each branch processes the inputs at its respective timescale. Finally, one prediction head per timescale generates
    the predictions for that timescale based on the LSTM output.
    Optionally, one can specify:
    - a different hidden size for each LSTM branch (use a dict in the ``hidden_size`` config argument)
    - different dynamic input variables for each timescale (use a dict in the ``dynamic_inputs`` config argument)
    - the strategy to transfer states from the initial shared low-resolution LSTM to the per-timescale
    higher-resolution LSTMs. By default, this is a linear transfer layer, but you can specify 'identity' to use an
    identity operation or 'None' to turn off any transfer (via the ``transfer_mtlstm_states`` config argument).

    The sMTS-LSTM variant has the same overall architecture, but the weights of the per-timescale branches (including
    the output heads) are shared.
    Thus, unlike MTS-LSTM, the sMTS-LSTM cannot use per-timescale hidden sizes or dynamic input variables.

    Parameters
    ----------
    cfg : Config
        The run configuration.


EmbCudaLSTM model class, which adds embedding networks for static inputs to the standard LSTM.

    This class extends the standard `CudaLSTM` class to preprocess the static inputs by an embedding network, prior
    to concatenating those values to the dynamic (time series) inputs. Use the config argument `embedding_hiddens` to
    specify the architecture of the fully-connected embedding network. No activation function is applied to the outputs
    of the embedding network.
    To control the initial forget gate bias, use the config argument `initial_forget_bias`. Often it is useful to set
    this value to a positive value at the start of the model training, to keep the forget gate closed and to facilitate
    the gradient flow.
    The `EmbCudaLSTM` class does only support single timescale predictions. Use `MTSLSTM` to train a model and get
    predictions on multiple temporal resolutions at the same time.

    Parameters
    ----------
    cfg : Config
        The run configuration.


Base class to run inference on a model.

    Use subclasses of this class to evaluate a trained model on its train, test, or validation period.
    For regression settings, `RegressionTester` is used; for uncertainty prediction, `UncertaintyTester`.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    run_dir : Path
        Path to the run directory.
    period : {'train', 'validation', 'test'}, optional
        The period to evaluate, by default 'test'.
    init_model : bool, optional
        If True, the model weights will be initialized with the checkpoint from the last available epoch in `run_dir`.


Tester class to run inference on a regression model.

    Use the `evaluate` method of this class to evaluate a trained model on its train, test, or validation period.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    run_dir : Path
        Path to the run directory.
    period : {'train', 'validation', 'test'}
        The period to evaluate.
    init_model : bool, optional
        If True, the model weights will be initialized with the checkpoint from the last available epoch in `run_dir`.


Tester class to run inference on an uncertainty model.

    Use the `evaluate` method of this class to evaluate a trained model on its train, test, or validation period.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    run_dir : Path
        Path to the run directory.
    period : {'train', 'validation', 'test'}
        The period to evaluate.
    init_model : bool, optional
        If True, the model weights will be initialized with the checkpoint from the last available epoch in `run_dir`.


Class that logs runs to tensorboard and saves plots to disk.

    Parameters
    ----------
    cfg : Config
        The run configuration.


Base class for regularization terms.

    Regularization terms subclass this class by implementing the `forward` method.

    Parameters
    ----------
    cfg: Config
        The run configuration.


Regularization that penalizes inconsistent predictions across frequencies.

    This regularization can only be used if at least two frequencies are predicted. For each pair of adjacent
    frequencies f and f', where f is a higher frequency than f', it aggregates the f-predictions to f' and calculates
    the mean squared deviation between f' and aggregated f.

    Parameters
    ----------
    cfg : Config
        The run configuration.

    Raises
    ------
    ValueError
        If the run configuration only predicts one frequency.


Base loss class.

    All losses extend this class by implementing `_get_loss`.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    prediction_keys : List[str]
        List of keys that will be predicted. During the forward pass, the passed `prediction` dict
        must contain these keys. Note that the keys listed here should be without frequency identifier.
    ground_truth_keys : List[str]
        List of ground truth keys that will be needed to compute the loss. During the forward pass, the
        passed `data` dict must contain these keys. Note that the keys listed here should be without
        frequency identifier.
    additional_data : List[str], optional
        Additional list of keys that will be taken from `data` in the forward pass to compute the loss.
        For instance, this parameter can be used to pass the variances that are needed to compute an NSE.


Mean squared error loss.

    To use this loss in a forward pass, the passed `prediction` dict must contain
    the key ``y_hat``, and the `data` dict must contain ``y``.

    Parameters
    ----------
    cfg : Config
        The run configuration.


Root mean squared error loss.

    To use this loss in a forward pass, the passed `prediction` dict must contain
    the key ``y_hat``, and the `data` dict must contain ``y``.

    Parameters
    ----------
    cfg : Config
        The run configuration.


Basin-averaged Nash--Sutcliffe Model Efficiency Coefficient loss.

    To use this loss in a forward pass, the passed `prediction` dict must contain
    the key ``y_hat``, and the `data` dict must contain ``y`` and ``per_basin_target_stds``.

    A description of the loss function is available in [#]_.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    eps: float, optional
        Small constant for numeric stability.

    References
    ----------
    .. [#] Kratzert, F., Klotz, D., Shalev, G., Klambauer, G., Hochreiter, S., and Nearing, G.: "Towards learning
       universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets"
       *Hydrology and Earth System Sciences*, 2019, 23, 5089-5110, doi:10.5194/hess-23-5089-2019


Basin-averaged Nash--Sutcliffe Model Efficiency Coefficient loss.

    This loss function weights multiple outputs according to user-specified weights in the
    config argument 'target_loss_weights'. To use this loss in a forward pass, the passed
    `prediction` dict must contain the key ``y_hat``, and the `data` dict must contain
    ``y`` and ``per_basin_target_stds``.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    eps: float, optional
        Small constant for numeric stability.


Default class to train a model.

    Parameters
    ----------
    cfg : Config
        The run configuration.


Class to estimate rating curves from stage and discharge data and to convert stage to discharge and vice-versa.

    Parameters
    ----------
    stages : Sequence
        Stage data to estimate a rating curve
    discharges : Sequence
        Discharge data to estimate a rating curve
    move_stages_to_zero : bool, optional
        Option to account for any offset in the stage data. This will automatically set the minimum measured stage to
        zero.


Data set class for the CAMELS US data set by [#]_ and [#]_.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    is_train : bool
        Defines if the dataset is used for training or evaluating. If True (training), means/stds for each feature
        are computed and stored to the run directory. If one-hot encoding is used, the mapping for the one-hot encoding
        is created and also stored to disk. If False, a `scaler` input is expected and similarly the `id_to_int` input
        if one-hot encoding is used.
    period : {'train', 'validation', 'test'}
        Defines the period for which the data will be loaded
    basin : str, optional
        If passed, the data for only this basin will be loaded. Otherwise the basin(s) are read from the appropriate
        basin file, corresponding to the `period`.
    additional_features : List[Dict[str, pd.DataFrame]], optional
        List of dictionaries, mapping from a basin id to a pandas DataFrame. This DataFrame will be added to the data
        loaded from the dataset and all columns are available as 'dynamic_inputs', 'static_inputs' and
        'target_variables'
    id_to_int : Dict[str, int], optional
        If the config argument 'use_basin_id_encoding' is True in the config and period is either 'validation' or
        'test', this input is required. It is a dictionary, mapping from basin id to an integer (the one-hot encoding).
    scaler : Dict[str, Union[pd.Series, xarray.DataArray]], optional
        If period is either 'validation' or 'test', this input is required. It contains the means and standard
        deviations for each feature and is stored to the run directory during training (train_data/train_data_scaler.p)

    References
    ----------
    .. [#] A. J. Newman, M. P. Clark, K. Sampson, A. Wood, L. E. Hay, A. Bock, R. J. Viger, D. Blodgett,
        L. Brekke, J. R. Arnold, T. Hopson, and Q. Duan: Development of a large-sample watershed-scale
        hydrometeorological dataset for the contiguous USA: dataset characteristics and assessment of regional
        variability in hydrologic model performance. Hydrol. Earth Syst. Sci., 19, 209-223,
        doi:10.5194/hess-19-209-2015, 2015
    .. [#] Addor, N., Newman, A. J., Mizukami, N. and Clark, M. P.: The CAMELS data set: catchment attributes and
        meteorology for large-sample studies, Hydrol. Earth Syst. Sci., 21, 5293-5313, doi:10.5194/hess-21-5293-2017,
        2017.


Data set class for the CAMELS GB dataset by [#]_.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    is_train : bool
        Defines if the dataset is used for training or evaluating. If True (training), means/stds for each feature
        are computed and stored to the run directory. If one-hot encoding is used, the mapping for the one-hot encoding
        is created and also stored to disk. If False, a `scaler` input is expected and similarly the `id_to_int` input
        if one-hot encoding is used.
    period : {'train', 'validation', 'test'}
        Defines the period for which the data will be loaded
    basin : str, optional
        If passed, the data for only this basin will be loaded. Otherwise the basin(s) are read from the appropriate
        basin file, corresponding to the `period`.
    additional_features : List[Dict[str, pd.DataFrame]], optional
        List of dictionaries, mapping from a basin id to a pandas DataFrame. This DataFrame will be added to the data
        loaded from the dataset, and all columns are available as 'dynamic_inputs', 'static_inputs' and
        'target_variables'
    id_to_int : Dict[str, int], optional
        If the config argument 'use_basin_id_encoding' is True in the config and period is either 'validation' or
        'test', this input is required. It is a dictionary, mapping from basin id to an integer (the one-hot encoding).
    scaler : Dict[str, Union[pd.Series, xarray.DataArray]], optional
        If period is either 'validation' or 'test', this input is required. It contains the means and standard
        deviations for each feature and is stored to the run directory during training (train_data/train_data_scaler.p)

    References
    ----------
    .. [#] Coxon, G., Addor, N., Bloomfield, J. P., Freer, J., Fry, M., Hannaford, J., Howden, N. J. K., Lane, R.,
        Lewis, M., Robinson, E. L., Wagener, T., and Woods, R.: CAMELS-GB: Hydrometeorological time series and landscape
        attributes for 671 catchments in Great Britain, Earth Syst. Sci. Data Discuss.,
        https://doi.org/10.5194/essd-2020-49, in review, 2020.


Base data set class to load and preprocess data.

    Use subclasses of this class for training/evaluating a model on a specific data set. E.g. use `CamelsUS` for the US
    CAMELS data set and `CamelsGB` for the CAMELS GB data set.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    is_train : bool
        Defines if the dataset is used for training or evaluating. If True (training), means/stds for each feature
        are computed and stored to the run directory. If one-hot encoding is used, the mapping for the one-hot encoding
        is created and also stored to disk. If False, a `scaler` input is expected and similarly the `id_to_int` input
        if one-hot encoding is used.
    period : {'train', 'validation', 'test'}
        Defines the period for which the data will be loaded
    basin : str, optional
        If passed, the data for only this basin will be loaded. Otherwise, the basin(s) is(are) read from the
        appropriate basin file, corresponding to the `period`.
    additional_features : List[Dict[str, pd.DataFrame]], optional
        List of dictionaries, mapping from a basin id to a pandas DataFrame. This DataFrame will be added to the data
        loaded from the dataset and all columns are available as 'dynamic_inputs', 'static_inputs' and
        'target_variables'
    id_to_int : Dict[str, int], optional
        If the config argument 'use_basin_id_encoding' is True in the config and period is either 'validation' or
        'test', this input is required. It is a dictionary, mapping from basin id to an integer (the one-hot encoding).
    scaler : Dict[str, Union[pd.Series, xarray.DataArray]], optional
        If period is either 'validation' or 'test', this input is required. It contains the means and standard
        deviations for each feature and is stored to the run directory during training (train_data/train_data_scaler.p)


Data set class providing hourly data for CAMELS US basins.

    This class extends the `CamelsUS` dataset class by hourly in- and output data. Currently, only NLDAS forcings are
    available at an hourly resolution.

    Parameters
    ----------
    cfg : Config
        The run configuration.
    is_train : bool
        Defines if the dataset is used for training or evaluating. If True (training), means/stds for each feature
        are computed and stored to the run directory. If one-hot encoding is used, the mapping for the one-hot encoding
        is created and also stored to disk. If False, a `scaler` input is expected and similarly the `id_to_int` input
        if one-hot encoding is used.
    period : {'train', 'validation', 'test'}
        Defines the period for which the data will be loaded
    basin : str, optional
        If passed, the data for only this basin will be loaded. Otherwise the basin(s) are read from the appropriate
        basin file, corresponding to the `period`.
    additional_features : List[Dict[str, pd.DataFrame]], optional
        List of dictionaries, mapping from a basin id to a pandas DataFrame. This DataFrame will be added to the data
        loaded from the dataset and all columns are available as 'dynamic_inputs', 'static_inputs' and
        'target_variables'
    id_to_int : Dict[str, int], optional
        If the config argument 'use_basin_id_encoding' is True in the config and period is either 'validation' or
        'test', this input is required. It is a dictionary, mapping from basin id to an integer (the one-hot encoding).
    scaler : Dict[str, Union[pd.Series, xarray.DataArray]], optional
        If period is either 'validation' or 'test', this input is required. It contains the means and standard
        deviations for each feature and is stored to the run directory during training (train_data/train_data_scaler.p)


        Returns a PrimaryHDU containing model data == exp*model flux
        Also writes out fits file containing this.


        Returns a  of PrimaryHDU objects containing simulated Poisson datons
        Also writes out fits files containing these.


Multiprocessing wrapper class


Users can override the remaining methods from the parent class here,
    or create new ones (e.g. as required by plugins)


A class for plotting WWZ results.


A class for weighted wavelet z-transform analysis.


    Run the components specified by the configuration file.

    Model configurations are implemented for the for the following:

    PET:         One of:
                        'hs'            =  Hargreaves-Samani
                        'hargreaves'    =  Hargreaves
                        'pm'            =  Penman-Monteith
                        'thornthwaite'  =  Thornthwaite
    RUNOFF:      One of:
                        'abcd'  =  The ABCD model
                        'gwam'  =  Global Water Assessment Model
    ROUTING:     One of:
                        'mrtm'  =  Modified River Transport Model

    Available output statistics modules include:
        - Hydropower actual
        - Hydropower potential
        - Drought
        - Diagnostics

    Spin-up is built in to the ABCD model and does not need to be calculated
    separately. If any component needs to have the model spin up before
    running, they must be in the SPINUP_COMPONENTS list.

    It is possible to run any subset of the three main modules, as long as all
    the required inputs are provided. For example, to run only the routing
    module, provide a custom runoff array.

    Xanthos suports two types of modules: those that iterate one timestep at a
    time (ex. GWAM), and those that take all times at once (ex. ABCD). These
    properties must be specified in the *_STEPWISE_COMPONENTS in order to work
    properly.


    An extensible global hydrologic model.

    Xanthos is an open-source hydrologic model, designed to quantify
    and analyze global water availability. Xanthos simulates historical
    and future global water availability on a monthly time step at a
    spatial resolution of 0.5 geographic degrees.


    Components for use in model configurations.

    @author   Chris R. Vernon, Xinya Li
    @email:   chris.vernon@pnnl.gov; xinya.li@pnl.gov
    @Project: Xanthos 2.0

    License:  BSD 2-Clause, see LICENSE and DISCLAIMER files

    Copyright (c) 2017, Battelle Memorial Institute


Download and unpack example data supplement from Zenodo that matches the current installed
    Xanthos distribution.
    :param example_data_directory:              Full path to the directory you wish to install
                                                the Xanthos example data to.  Must be write-enabled
                                                for the user.


Custom exception for invalid Xanthos inputs.


Read the Xanthos configuration .ini file.


Exception for invalid configuration options.


Load system-wide input data.


    Test the hargreaves_gwam_mrtm configuration.

    Uses the config file test/configs/hargreaves_gwam_mrtm.ini which runs for
    one year with no outputs and no optional modules.


    A hydrology emulator.

    | Reference:
    |
    | Liu, Y., Hejazi, M.A., Li, H., Zhang, X., (2017), A Hydrological Emulator for Global
    |    Applications, Geoscientific Model Development Discussions, DOI: 10.5194/gmd-2017-113
    |
    | Martinez, G. F., & Gupta, H. V. (2010). Toward improved identification
    |    of hydrological models: A diagnostic evaluation of the 'abcd' monthly
    |    water balance model for the conterminous United States. Water Resources Research, 46(8).

    @:param prm     Object containing calibrated data
    @:param hist    Object containing Watch data
                    hist.
    @:return a      Float from 0-1
    @:return b      Float from 100-1000 mm
    @:return c      Float from 0-1
    @:return d      Float from 0-1
    @:return m      Float from 0-1


Calibrate the ABCD runoff module.


    Analyze drought impacts based on runoff or soil moisture.

    Drought metrics based on work done by Sheffield and Wood (2008).

    Sheffield, J. and Eric F. Wood (2008) "Projected changes in drought
      occurrence under future global warming from multi-model,
      multi-scenario, IPCC AR4 simulations", _Clim Dyn_ 31: 79--105,
      doi:10.1007/s00382-007-0340-z


    Compute country and GCAM-region level hydropower production time series based on xanthos streamflow output.

    Gridded streamflow is used to drive dam simulations for 1593 large dams (~54% global hydropower installed capacity).
    Each dam is has been pre-assigned an optimized look-up table, which assigns a turbine release at each time step
    using current reservoir storage, inflow and month of year. Power output time series are summed across dams for each
    country and scaled up to account for unsimulated capacity (i.e., for dams not represented in the model).


    Perform diagnostics by comparing the estimates of average total annual
    runoff (km^3/yr) of xanthos to other models.

    Estimates of average total annual runoff (km^3/yr)
    The comparison data file needs to be preprocessed.
    Dimension: (67420, 1)
    Unit: km3/year

    Runoff
    - VIC     The major comparison
    - WBM     Ref comparison: WBM (Fekete et al., 2000) and WBMc (Fekete et al., 2000)
              are also used as additional comparisons (2 column csv files)
    - UNH     Ref comparison: UNH-GRDC 1986-1995


    Write out main Xanthos output variables.

    Output settings:
        OutputFormat  =  0 (default, netcdf file); 1 (csv file); 2 (mat file); 3 (parquet file)
        OutputUnit    =  0 (default, mm); 1 (km3)
        OutputInYear  =  0 (default, per month); 1 (per year, 12-month results combine into annual result)


A collection of methods for communicating with the UI.


Base class for computation flows.


Struct-like class to hold computed statistics.

        The 'med' attribute is optional, may be None.


Computes histogram and statistics by loading all data into RAM


Computes histogram and statistics using rolling algorithms.


A Mock class for the return value of parse_cli_args().


TestCase base class with methods to generate datasets.


Integration tests for the whole script.


Tests for the parse_cli_args() function.


Tests for the UiComm class.


Tests for the InMemoryFlow class


Tests for the VarSpec class


Parsed components of opt.x or opt.y


User-defined settings at the visualization-level.

    All settings are attributes. If the -f option was specified, settings
    defined in that file override the defaults.

    Attributes:
    - xScale: (str) 'Log' or 'Linear'
    - yScale: (str) 'Log' or 'Linear'


Tests the code to create a reasonable filename for the downloaded provenance.


Class for errors associated with untainting the cgi query string.


Class for errors associated with calculating the intersection.


Mock for agiovanni.cfg.ConfigEnvironment


A base-class for a mode of program containing a main()
    function to use.

    This class is not instantiated.


Contains the default main() execution sequence.

    A mask is generated at the data's resolution, and then applied
    to the data. This is for algorithms that do not need any
    information about the mask, and can function just fine without
    knowing a shape was selected.


Contains the custom main() execution sequence for area averaged
    time series mode.

    This mode exists because area averaged time series computations,
    later in the generation of the result, require the mask to be
    unapplied and to be weighted by cos(lat).

    In this mode, the mask is generated at a higher resolution equal
    to a constant factor of the data's resolution. The mask is then
    regridded to the data's resolution with the additional property
    that the mask consists of weights in [0, 1] equal to the porportion
    of the cell covered by the shape. These mask values are weighted
    a second time by cos(lat).


This version only preps the Mask for application in
    g4_area_avg_diff_time_series.py. It is in that script that
    shape_mask is added to each cube being processed and then
    used as a weight for averaging.

    see AreaAverageModeApplyMask() for additional info


A collection of static utility functions.


Mock agiovanni.cfg.ConfigEnvironment class


Base class for mode tests.


Tests for the AreaAverageMode class.


Tests that the script when no -S option is provided.


Tests the intersection code.


An abstracted configuration environment.

    Provides access to the Giovanni configuration (giovanni.cfg) through
    Python. Abstracted so it can be mocked for testing.


An exception thrown when an NCO call returns a non-zero status.

    Attributes
      return_code, int containing the NCO return code.


An exception thrown when an NCO executable is not found.

    Attributes
      command_name


An exception throw by the code in this file.


Runs a bunch of commands in the specified number of threads.


Runs a command and logs it's output.


    This is a stupid class that just pre-pends the command id to every log message for multi-threading. It feels to me
    as though there has to be a better way of doing this. This class feels very java-ish.


    Used to indicate something went wrong with one of the functions in this
    module.


Immutable class for holding geographic bounds.


Immutable class for holding geographic resolution.


Exception associated with trying to lock a file.


Base class of celeryconfig module


Visualizes a netcdf file to a png.


Exception that occurs when GDAL returns a non-zero exit code.

    Attributes
      return_code, return code returned


An exception thrown when unable to perform the an operation on
    netcdf


An immutable class that holds informatm about a provenance item.

    Attributes:
      file_path, text contents of the item element
      name, XML attribute "NAME" of the item element
      type_, XML attribute "TYPE" of the item element


Class for errors associated with bounding boxes.


This class has bounding box utility functions


test_netcdf.py: Test the netcdf library functionality.


Tests that the intersection code.


Tests writing a file list and then reading it back.


Tests for the mfst.read_file_list function.

    These tests write manifest files and test the function's ability
    to read them correctly.


Tests for the ConfigEnvironment Class.

    These tests create a fake giovanni_config.pl in a temp directory
    and set it to the highest precendence in the PATH.


Tests that the Bounds class.


Tests the resolution class.


unit test for visualizationTask module


unit test for celeryconfigBase module


unit test for visualizationManager module


This class serializes a netcdf file to JSON. The netcdf file needs to have
    the following dimensions:

time

lat - latitude

lon - longitude

    and one more more 3 dimensional variables with the time, lat, and lon
    dimensions in that order.


NetCDF file object


    @brief This class searches Google Scholar (http://scholar.google.com)
    Search for articles and publications containing terms of interest.


S2 data request paramaters.

    Attributes
    ----------
    datestart : str
        Starting date for data request in form "2019-01-01".
    dateend : str
        Starting date for data request in form "2019-12-31".
    scale : int
        pixel resolution
    bands : list, optional
        List of strings with band name.
        the default is ['B3', 'B4', 'B5',
        'B6', 'B7', 'B8A', 'B11', 'B12'].


Area of interest for area info and data.

    Attributes
    ----------
    name : str
        Name of the area.
    geometry : str
        Geometry of the area of interest e.g. from geopandas.
        Currently only polygons tested. Ayush: modified to work with Point type. The default is None.
    coordinate_list : list, optional
        List of coordinates of a polygon
        (loop should be closed). Computed from geometry if not
        provided. The default is None.
    tile : str, optional
        Tile id as string for the data. Used to keep the data in
        same crs because an area can be in multiple tiles with
        different crs. The default is None.
    qi : pandas dataframe
        Dataframe with quality information about available imagery for the AOI.
        qi is empty at init and can be computed with
        ee_get_s2_quality_info function.
    data : pandas dataframe or xarray
        Dataframe holding data retrieved from GEE. Data can be computed using
        function
        qi is empty at init and can be computed with ee_get_s2_data and
        converted to xarray using s2_data_to_xarray function.

    Methods
    -------
    __init__


    Handles the responses from the web server. Only response that is
    handled is a GET that will return all known models.


    This class is responsible for announcing a new model to PEcAn.
    This will send out a message every so often to ennounce the model
    and PEcAn will listen for these messages and register the model
    in the database. At that point the model will be shown in the
    web ui as well.


    A general interface for two sample tests. This interface guarantees that the
    code for the contrast curve / grid calculations can be used with all test
    implemented.


    This is a general interface for all bootstrap tests. It implements all
    functionality needed to save and load bootstrap results as json files and
    to run a new bootstrap experiment. It extends the classical
    :meth:`~applefy.statistics.parametric.TTest` as both use the same test
    statistic :math:`T_{obs}`. But for a given value of :math:`T_{obs}` the
    bootstrap tests will give a different p-value / fpf.


    The GaussianBootstrapTest is a parametric hypothesis test which assumes that
    the noise is Gaussian. This test is approximately equivalent to the ttest.
    This implementation is only for illustration purposes and should not be
    used in practice.


    The LaplaceBootstrapTest is a parametric hypothesis test which assumes that
    the distribution of the noise is Laplace. The test accounts for the higher
    occurrence rate of bright noise values as well as for the small sample size
    at close separations to the star. Applefy comes with
    `previously computed <../02_user_documentation/03_bootstrapping.ipynb>`_
    lookup tables.


    A classical two sample ttest. Assumes iid Gaussian noise and tests for
    differences in means.


    The Contrast class is the main interface to compute contrast curves with
    applefy. It allows to compute contrast grids as well as classical
    analytical contrast curves. For an example on how to use this class see the
    `user documentation <../02_user_documentation/01_contrast_curves.ipynb>`_


    Class for the evaluation and organization of residuals from one
    method (e.g. pca with 10 components). Supports both contrast curves and
    contrast grids. Usually ContrastResult is used within an instance of
    :meth:`~Contrast`. But, it can also be used individually.


    Applefy allows to compute contrast curves with different post-processing
    algorithms. However, it does not come with any implementation of these
    techniques. Instead, we use existing implementations in packages like
    `PynPoint <https://pynpoint.readthedocs.io/en/latest/>`_ or
    `VIP <https://vip.readthedocs.io/en/latest/>`_.
    The DataReductionInterface is an interface which guarantees that these
    external implementations can be used within applefy.
    See `wrappers <wrappers.html>`_ for examples.


    The SimplePCAPynPoint is a wrapper around the simple full frame PCA
    implemented in `PynPoint <https://pynpoint.readthedocs.io/en/latest/\
    pynpoint.util.html#pynpoint.util.psf.pca_psf_subtraction>`__.
    It only allows to compute the residuals for a fixed number of PCA
    components. The advantage of this wrapper over
    :meth:`~MultiComponentPCAPynPoint` is, that it does not require to
    create a PynPoint database file.


    The MultiComponentPCAPynPoint is a wrapper around the full
    frame PCA implemented in `PynPoint <https://pynpoint.readthedocs.io/en/\
    latest/pynpoint.processing.html#pynpoint.processing.psfsubtraction.\
    PcaPsfSubtractionModule>`__. While the wrapper
    :meth:`~SimplePCAPynPoint` only accepts a single fixed number
    of PCA components, MultiComponentPCAPynPoint computes several residuals
    with different number of components. This can be more efficient as the
    PCA basis needs to be computed only once. The disadvantage over
    :meth:`~SimplePCAPynPoint` is that MultiComponentPCAPynPoint needs to
    create a Pynpoint database and delete it after computing the residuals.


    The SimplePCAvip is a wrapper around the simple full frame PCA
    implemented in `VIP <https://vip.readthedocs.io/en/latest/vip_hci.\
    psfsub.html#vip_hci.psfsub.pca_fullfr.pca>`__.
    It only allows to compute the residuals for a fixed number of PCA
    components.


    The MultiComponentPCAvip is a wrapper around the full
    frame PCA implemented in `VIP <https://vip.readthedocs.io/en/latest/\
    vip_hci.psfsub.html#vip_hci.psfsub.pca_fullfr.pca>`__. While the wrapper
    :meth:`~SimplePCAvip` only accepts a single fixed number
    of PCA components, MultiComponentPCAvip computes several residuals
    with different number of components.


    The PCAannvip is a wrapper around the annular PCA
    implemented in `VIP <https://vip.readthedocs.io/en/latest/vip_hci.\
    psfsub.html#vip_hci.psfsub.pca_local.pca_annular>`__.
    It only allows to compute the residuals for a fixed number of PCA
    components.


    The MultiComponentPCAannvip is a wrapper around the annular PCA implemented
    in `VIP <https://vip.readthedocs.io/en/latest/\
    vip_hci.psfsub.html#vip_hci.psfsub.pca_local.pca_annular>`__. While the
    wrapper
    :meth:`~PCAannvip` only accepts a single fixed number
    of PCA components, MultiComponentPCAannvip computes several residuals
    with different number of components.


    A capsule to manage the parameters of how photometry is calculated on
    residuals frames. The function is a wrapper of the parameters
    needed by the function :meth:`~get_flux` which is the foundation
    of many other functions.


    Abstract interface for :meth:`~IterNoiseBySeparation` and
    :meth:`~IterNoiseForPlanet`.


    An iterator that allows to sample noise photometry for different reference
    positions (angle_offsets). This is needed to average out the effect of
    rotation on the contrast. See
    `Figure 10 <../04_apples_with_apples/paper_experiments/10_Rotation.ipynb>`_
    for more information.


    An iterator that allows to sample noise photometry for different reference
    positions relative to a given planet position. This is needed to average out
    the effect of rotation on the detection uncertainty. See
    `Figure 10 <../04_apples_with_apples/paper_experiments/10_Rotation.ipynb>`_
    for more information.


Collection of file utility methods


Collection of label parsing utility methods


Collection of input/output utility methods


Class containing various model options.


Class that contains all default model variables.


    Specify the range of parameter values to include in model runs.

    variables can be either lists, tuples or numpy arrays

    Set value to None to ignore the parameter range and use the default value
    that is specified in the ModelParameters class

    add _s to any parameter name in the ``model_parameters.py`` file that
    you would like to change. For example topo_gradient_s = [0.01, 0.1] will
    change parameter topo_gradient in the ``model_parameters.py`` file and
    will first run a model scenario with a gradient of 0.01 and then one
    with a gradient of 0.1


    Specify the range of parameter values to include in model runs.

    variables can be either lists, tuples or numpy arrays

    Set value to None to ignore the parameter range and use the default value
    that is specified in the ModelParameters class

    add _s to any parameter name in the ``model_parameters.py`` file that
    you would like to change. For example topo_gradient_s = [0.01, 0.1] will
    change parameter topo_gradient in the ``model_parameters.py`` file and
    will first run a model scenario with a gradient of 0.01 and then one
    with a gradient of 0.1

    variables can be either lists, tuples or numpy arrays

    set value to None to ignore the parameter range and use the default value
    that is specified in the ModelParameters class


    Specify the range of parameter values to include in model runs

    variables can be either lists, tuples or numpy arrays

    set value to None to ignore the parameter range and use the default value
    that is specified in the ``model_parameters.py`` file

    add _s to any parameter name in the ``model_parameters.py`` file that
    you would like to change. For example topo_gradient_s = [0.01, 0.1] will
    change parameter topo_gradient in the ``model_parameters.py`` file and
    will first run a model scenario with a gradient of 0.01 and then one
    with a gradient of 0.1


Holds results of fit


Does frequency integration


Class holding data, defining likelihood


A class representing a Blackbody


A class representing a modified greybody

    The form for the modified blackbody is

    .. math::

      f_{\\nu} \\propto \\left(1 - \\exp\\left[ - \\left(\\nu /
      \\nu_0\\right)^{\\beta} B_{\\nu}\\left( \\nu ; T \\right)

    where :math:`B_{\\nu}` is the Planck blackbody function in frequency
    units.  Class instances are static.


 A class representing the response of an instrument to an observation.

    Handles instrument responses and pipeline normalization conventions.


A set of instrument responses.


    relagn - relativistic SED model for AGN
    Assumes a radially stratified flow consisting of:
        - An outer standard accretion disc
        - A warm Comptonisation region (where the disc is having a bad day)
        - A hot Comptonisation region (i.e inner X-ray Corona)

    For more details on the model - see Hagen & Done (in prep)

    Attributes
    ----------
    risco : float
        Innremost stable circular orbit - units : Dimensionless (Rg)

    r_sg : float
        Self-Gravity radius of the disc, following Laor & Netzer 1989
        Units : Dimensionless (Rg)

    eta : float
        Accretion efficiency. Used to convert from mass accretion rate to
        luminosity. i.e L = eta * Mdot * c^2
        Units : dimensionless

    Egrid : array
        Energy grid used for calculations (in frame of black hole) - units : keV

    nu_grid : array
        Frequency grid corresponding to Egrid - units : Hz

    wave_grid : array
        Wavelength grid corresponding to Egrid - units : Angstrom

    E_obs : array
        Energy grid converted to observer frame (i.e redshift corrected) - units : keV

    nu_obs : array
        Frequency grid converted to observer frame - units : Hz

    wave_obs : array
        Wavelength grid converted to observer frame - units : Angstrom

    ###########################################################################
    There are other attributes, however it is recomended that you
    extract these using the built in methods in order to deal with unit choices
    correctly. The remaining ones after this are only necessary for the internal
    calculations, so no need to worry about them!
    ###########################################################################

    Important Methods
    -----------------
    get_totSED(rel=True)
        Extracts the total SED (disc + warm + hot components) in whatever
        units are set

    get_DiscComponent(rel=True)
        Extracts disc component from SED (after checking if it exists in the
        current model geometry) in whatever units are set

    get_WarmComponent(rel=True)
        Extracts warm Compton component from SED (after checking if it exists
        in the current model geometry) in whatever units are set

    get_HotComponent(rel=True)
        Extracts hot Compton component from SED (after checking if it exists
        in the current model geometry) in whatever units are set

    set_units(new_unit='cgs')
        Sets the system units to use when extracting spectra / system
        properties

    set_flux()
        Sets a flag s.t all spectra are given in terms of flux rather than
        luminosity

    set_lum()
        Sets a flag s.t all spectra are given in luminosity (this is the default)

    get_Ledd()
        Gives Eddington luminosity in whatever units are set
        (Note: in frame of black hole!!)

    get_Rg()
        Gives scale of gravitaional radius (Rg = GM/c^2) in whatever units
        are set

    get_Mdot()
        Gives PHYSICAL mass accretion rate, in either g/s or kg/s
        (depending on what units are set)

    ###########################################################################


    relqso - A simplified version of relagn, where we fix some parameters to
    typical values (kTe_hot = 100keV, kTe_warm=0.2keV, Gamma_warm = 2.5,
    r_warm = 2r_hot, and h_max = 10 (maybe 100 - change later))

    Here we also calculate r_hot based off the condition that L_diss = 0.02Ledd,
    which also sets \Gamma_hot, based of the ratio to Ldiss and Lseed
    Finally, the outer disc radius, r_out, is set to the self-gravity radius

    For more details on the model - see Hagen & Done (in prep)

    Attributes
    ----------
    r_h : float
        Outer radius of hot Compton region

    r_w : float
        Outer radius of warm Compton region

    gamma_h : float
        Spectral index of hot Compton component

    risco : float
        Innremost stable circular orbit - units : Dimensionless (Rg)

    r_sg : float
        Self-Gravity radius of the disc, following Laor & Netzer 1989
        Units : Dimensionless (Rg)

    eta : float
        Accretion efficiency. Used to convert from mass accretion rate to
        luminosity. i.e L = eta * Mdot * c^2
        Units : dimensionless

    Egrid : array
        Energy grid used for calculations (in frame of black hole) - units : keV

    nu_grid : array
        Frequency grid corresponding to Egrid - units : Hz

    wave_grid : array
        Wavelength grid corresponding to Egrid - units : Angstrom

    E_obs : array
        Energy grid converted to observer frame (i.e redshift corrected) - units : keV

    nu_obs : array
        Frequency grid converted to observer frame - units : Hz

    wave_obs : array
        Wavelength grid converted to observer frame - units : Angstrom

    ###########################################################################
    There are other attributes, however it is recomended that you
    extract these using the built in methods in order to deal with unit choices
    correctly. The remaining ones after this are only necessary for the internal
    calculations, so no need to worry about them!
    ###########################################################################

    Important Methods
    -----------------
    get_totSED(rel=True)
        Extracts the total SED (disc + warm + hot components) in whatever
        units are set

    get_DiscComponent(rel=True)
        Extracts disc component from SED (after checking if it exists in the
        current model geometry) in whatever units are set

    get_WarmComponent(rel=True)
        Extracts warm Compton component from SED (after checking if it exists
        in the current model geometry) in whatever units are set

    get_HotComponent(rel=True)
        Extracts hot Compton component from SED (after checking if it exists
        in the current model geometry) in whatever units are set

    set_units(new_unit='cgs')
        Sets the system units to use when extracting spectra / system
        properties

    set_flux()
        Sets a flag s.t all spectra are given in terms of flux rather than
        luminosity

    set_lum()
        Sets a flag s.t all spectra are given in luminosity (this is the default)

    get_Ledd()
        Gives Eddington luminosity in whatever units are set
        (Note: in frame of black hole!!)

    get_Rg()
        Gives scale of gravitaional radius (Rg = GM/c^2) in whatever units
        are set

    get_Mdot()
        Gives PHYSICAL mass accretion rate, in either g/s or kg/s
        (depending on what units are set)

    ###########################################################################


    class that allows printing using user-specified verbosity levels

    Instantiate class using a given verbosity level, then call the instance
    by passing objects to be printed as arguments.

    Example:

        verbPrint = VerbosityPrint(1)
        verbPrint("I'm an example!")

        output: "I'm an example!"

        verbPrint = VerbosityPrint(0)
        verbPrint("I'm another example!")

        output: ""


    Class for computing a pixel area map for the Roman WFI detectors.

    Inputs
    ------
    detector (integer):
        WFI detector ID number.

    siaf_file (string; default=None):
        Path to the science instrument aperture file (SIAF) containing
        the geometric distortion polynomial coefficients. If None, then
        the code will look up the copy of the SIAF included in the
        package data.

    verbose (boolean; default=False):
        Optional argument to enable logging messages with additional
        information.

    Examples
    --------
    To compute the pixel area map of the science pixels (4088 x 4088) of
    detector WFI07 that does not include the reference pixel border:

    >>> from soc_roman_tools.pixel_area import pixel_area_map
    >>> pam07 = pixel_area_map.PixelArea(7)
    >>> pam07.compute()
    >>> pam07.save_asdf()


    Bootstrapper implementation.  See ``use_astropy_helpers`` for parameter
    documentation.


A class describing a single order for a High Resolutoin Spectrograph
    observation.

    Parameters
    -----------
    order: integer
        Order of the HRS observations

    region: list, tuple, or `~numpy.ndarray`
        region is an object that contains coordinates for pixels in
        the image which are part of this order.  It should be a list
        containing two arrays with the coordinates listed in each array.

    flux: `~numpy.ndarray`
        Fluxes corresponding to each pixel coordinate in region.

    wavelength: `~numpy.ndarray`
        Wavelengths corresponding to each pixel coordinate in region.

    order_type: str
        Type of order for the Order of the HRS observations

    flux_unit: `~astropy.units.UnitBase` instance or str, optional
        The units of the flux.

    wavelength_unit: `~astropy.units.UnitBase` instance or str, optional
        The units of the wavelength

    error: `~numpy.ndarray`
        Error corresponding to each pixel coordinate in region.

    mask: `~numpy.ndarray`
        Mask corresponding to each pixel coordinate in region.


A class describing the solution between x-position, order, and wavelength.

    Parameters
    ----------
    x: ~numpy.ndarray
        Array of the x-positions

    order: ~numpy.ndarray
        Array of the order-positions

    wavelength: ~numpy.ndarray
        Array of the wavelength at each x-position

    model: ~astropy.modeling.models
        A 2D model describing the transformation between x, order, and wavelength

    Raises
    ------

    Notes
    -----

    Examples
    --------


HRSModel is a class that describes the High Resolution Specotrgraph  on SALT


A subclass of `NDData` for a one dimensional spectrum in Astropy.

    This class inherits all the base class functionality from the NDData class
    and has similar properties with the specutils.Spectrum1D object.

    This is a placeholder until specutils is released

    Parameters
    ----------
    wavelength : `~numpy.ndarray`
        wavelength of the spectrum

    data : `~numpy.ndarray`
        flux of the spectrum

    wcs : `~astropy.wcs.WCS`
        transformation between pixel coordinates and "dispersion" coordinates
        this carries the unit of the dispersion

    unit : `~astropy.unit.Unit` or None, optional
        unit of the flux, default=None

    mask : `~numpy.ndarray`, optional
        Mask for the data, given as a boolean Numpy array with a shape
        matching that of the data. The values must be ``False`` where
        the data is *valid* and ``True`` when it is not (like Numpy
        masked arrays). If `data` is a numpy masked array, providing
        `mask` here will causes the mask from the masked array to be
        ignored.

    meta : `dict`-like object, optional
        Metadata for this object.  "Metadata" here means all information that
        is included with this object but not part of any other attribute
        of this particular object.  e.g., creation date, unique identifier,
        simulation parameters, exposure time, telescope name, etc.


A class describing with PyQt4 GUI for normalizing the spectra by fitting continuum .

   Parameters
   ----------
   warr: ~numpy.ndarray
       Array with wavelength

   farr: ~numpy.ndarray
       Array with fluxes

   oarr: ~numpy.ndarray
       Array with orders numbers

   outfile: ~str
       Name of the fits file the output will be written to

   fittype: ~str
       Fitting type. Can be "individual" for fitting individual orders. For other values of this parameter whole spectrum will be fit simultaneously.

   Returns
   -------
       The resulting spectrum will be saved to "outfile". The normalization will be performed only for orders which were inspected by hand.

   Notes
   -----
       Rejected region should be in format "(Lower wavelength)-(Higher wavelength)" without spaces. In case of multiple regions


    <Briefly describe the analysis task here.  Just a 1-2 sentence description
    of what the task does should be sufficient.>


A subtask for reading and remapping MLD observations


    The base class for analysis tasks.

    Attributes
    ----------
    config : mpas_tools.config.MpasConfigParser
        Contains configuration options

    taskName : str
        The name of the task, typically the same as the class name except
        starting with lowercase (e.g. 'myTask' for class 'MyTask')

    componentName : {'ocean', 'seaIce'}
        The name of the component (same as the folder where the task
        resides)

    tags : list of str
        Tags used to describe the task (e.g. 'timeSeries', 'climatology',
        horizontalMap', 'index', 'transect').  These are used to determine
        which tasks are generated (e.g. 'all_transect' or 'no_climatology'
        in the 'generate' flags)

    runDirectory : str
        The base input directory for namelists, streams files and restart files

    historyDirectory : str
        The base input directory for history files

    plotsDirectory : str
        The directory for writing plots (which is also created if it doesn't
        exist)

    namelist : ``shared.io.NameList``
        the namelist reader

    runStreams : ``shared.io.StreamsFile``
        the streams file reader for streams in the run directory (e.g. restart
        files)

    historyStreams : ``shared.io.StreamsFile``
        the streams file reader for streams in the history directory (most
        streams other than restart files)

    calendar : {'gregorian', 'gregoraian_noleap'}
        The calendar used in the MPAS run

    runAfterTasks : list of ``AnalysisTasks``
        tasks that must be complete before this task can run

    subtasks :  list of mpas_analysis.shared.AnalysisTask
        Subtasks of this task

    xmlFileNames : list of strings
        The XML file associated with each plot produced by this analysis, empty
        if no plots were produced

    logger : ``logging.Logger``
        A logger for output during the run phase of an analysis task


    A custom formatter for logging

    Modified from:
    https://stackoverflow.com/a/8349076/7728169


    Modified based on code by:
    https://www.electricmonk.nl/log/2011/08/14/redirect-stdout-and-stderr-to-a-logger-in-python/

    Copyright (C) 2011 Ferry Boender

    License: "available under the GPL" (the author does not provide more
    details)

    Fake file-like stream object that redirects writes to a logger instance.


    An analysis tasks for computing time series from output from the
    ``timeSeriesStatsMonthly`` analysis member.

    Attributes
    ----------

    variableList : list of str
        A list of variable names in ``timeSeriesStatsMonthly`` to be
        included in the time series

    allVariables : list of str
        A list of all available variable names in ``timeSeriesStatsMonthly``
        used to raise an exception when an unavailable variable is requested

    inputFiles : list of str
        A list of input files from which to extract the time series.

    startDate, endDate : str
        The start and end dates of the time series as strings

    startYear, endYear : int
        The start and end years of the time series


    Describes a main webpage containg one or more pages for components

    Attributes
    ----------
    config : mpas_tools.config.MpasConfigParser
        Config options

    controlConfig : mpas_tools.config.MpasConfigParser
        Config options for a control run

    customConfigFiles : list of str
        The names of custom config files to be copied to the HTML directory
        for provenance

    pageTemplate, componentTemplate, configTemplate : str
        The contents of templates used to construct the page

    components : OrederdDict of dict
        Each component has a name, subdirectory and image name used to find
        the appropriate thumbnail.


    Describes a component with one or more gallery groups, each with one or
    more galleries, and a list of "quick links" to the gallery groups

    Attributes
    ----------
    config : mpas_tools.config.MpasConfigParser
        Config options

    controlConfig : mpas_tools.config.MpasConfigParser
        Config options for a control run

    name : str
        The name of the component as it should appear in the list of
        components, at the top of the component webpage and in the page
        title (e.g "Sea Ice" as opposed to "sea_ice" or "seaIce")

    subdirecory : str
        The subdirectory for the component's webpage

    templates : OrderedDict of str
        The contents of templates used to construct the page

    groups : tree of OrederdDict
        A tree of information describing the the gallery groups in the page,
        the galleries in each group and the images in each gallery.


    An analysis tasks for computing climatologies from output from the
    ``timeSeriesStatsMonthly*`` analysis members.

    Attributes
    ----------

    variableList : dict of lists
        A dictionary with seasons as keys and a list of variable names in
        the stream to be included in the climatologies for each season in the
        values.

    allVariables : list of str
        A list of all available variable names in the stream used to raise an
        exception when an unavailable variable is requested

    inputFiles : list of str
        A list of input files used to compute the climatologies.

    ncclimoModel : {'mpaso', 'mpascice'}
        The name of the component expected by ``ncclimo``

    startDate, endDate : str
        The start and end dates of the climatology as strings

    startYear, endYear : int
        The start and end years of the climatology

    seasonSubtasks : dict
        If using xarray to compute climatologies, a dictionary of subtasks, one
        for each possible season

    op : {'avg', 'min', 'max'}
         operator for monthly stats

    streamName : str
        The name of the stream to read from, one of
        ``timeSeriesStatsMonthlyOutput``,
        ``timeSeriesStatsMonthlyMinOutput``,
        ``timeSeriesStatsMonthlyMaxOutput``


    An analysis subtasks for computing climatologies from output from the
    ``timeSeriesStatsMonthly`` analysis member for a single month or season.

    Attributes
    ----------

    season : str
        The season of the climatology

    parentTask : ``MpasClimatologyTask``
        The task that this subtask belongs to.


    An analysis task for comparison of 2D model fields against observations.

    Attributes
    ----------
    seasons : list of str
       A list of seasons (keys in ``constants.monthDictionary``) over
       which the climatology should be computed.

    fileName : str
        The name of the observation file

    outFilePrefix : str
        The prefix in front of output files and mapping files, typically the
        name of the field being remapped

    comparisonGridNames : list of str
        The name(s) of the comparison grid to use for remapping.


    An analysis tasks for computing a reference-year climatology for computing
    climatology anomalies from the``timeSeriesStatsMonthly`` analysis member.

    Attributes
    ----------

    anomalyRefYear : int
        The reference year over which to compute the climatology


    An analysis tasks for computing climatologies from output from the
    ``timeSeriesStatsMonthly`` analysis member.

    Attributes
    ----------

    climatologyName :  str
        A name that describes the climatology (e.g. a short version of
        the important field(s) in the climatology) used to name the
        subdirectories for each stage of the climatology

    variableList : list of str
        A list of variable names in ``timeSeriesStatsMonthly`` to be
        included in the climatologies

    iselValues : dict
        A dictionary of dimensions and indices (or ``None``) used to extract
        a slice of the MPAS field.

    seasons : list of str
        A list of seasons (keys in ``shared.constants.monthDictionary``)
        over which the climatology should be computed or ['none'] if only
        monthly climatologies are needed.

    comparisonDescriptors : dict of ``MeshDescriptor``
        Descriptors of the comparison grids to use for remapping, with
        grid names as the keys.

    restartFileName : str
        If ``comparisonGridName`` is not ``None``, the name of a restart
        file from which the MPAS mesh can be read.

    useNcremap : bool, optional
        Whether to use ncremap to do the remapping (the other option being
        an internal python code that handles more grid types and extra
        dimensions)

    op : {'avg', 'min', 'max'}
         operator for monthly stats

    vertices : bool
        Whether to remap from vertices, rather than cells


    An analysis task for plotting 2D model fields against observations.

    Attributes
    ----------
    season : str
        A season (key in ``shared.constants.monthDictionary``) to be
        plotted.

    comparisonGridName : str
        The name of the comparison grid to plot.

    remapMpasClimatologySubtask : mpas_analysis.shared.climatology.RemapMpasClimatologySubtask
        The subtask for remapping the MPAS climatology that this subtask
        will plot

    remapObsClimatologySubtask : mpas_analysis.shared.climatology.RemapObservedClimatologySubtask
        The subtask for remapping the observational climatology that this
        subtask will plot

    secondRemapMpasClimatologySubtask : mpas_analysis.shared.climatology.RemapMpasClimatologySubtask
        A second subtask for remapping another MPAS climatology to plot
        in the second panel and compare with in the third panel

    removeMean : bool, optional
        If True, a common mask for the model and reference data sets is
        computed (where both are valid) and the mean over that mask is
        subtracted from both the model and reference results.  This is
        useful for data sets where the desire is to compare the spatial
        pattern but the mean offset is not meaningful (e.g. SSH)

    outFileLabel : str
        The prefix on each plot and associated XML file

    fieldNameInTitle : str
        The name of the field being plotted, as used in the plot title

    mpasFieldName : str
        The name of the variable in the MPAS timeSeriesStatsMonthly output

    diffTitleLabel : str, optional
        the title of the difference subplot

    unitsLabel : str
        the units of the plotted field, to be displayed on color bars

    imageCaption : str
        the caption when mousing over the plot or displaying it full
        screen

    galleryGroup : str
        the name of the group of galleries in which this plot belongs

    groupSubtitle : str or None
        the subtitle of the group in which this plot belongs (or blank
        if none)

    groupLink : str
        a short name (with no spaces) for the link to the gallery group

    galleryName : str or None
        the name of the gallery in which this plot belongs

    depth : {None, float, 'top', 'bot'}
        Depth at which to perform the comparison, 'top' for the surface
        'bot' for the base

    configSectionName : str
        the name of the section where the color map and range is defined

    maskMinThreshold : float or None
        a value below which the field is mask out in plots

    maskMaxThreshold : float or None
        a value above which the field is mask out in plots

    extend : {'neither', 'both', 'min', 'max'}
        Determines the ``contourf``-coloring of values that are outside the
        range of the levels provided if using an indexed colormap.


    Class for fortran manipulation of namelist files, provides
    read and write functionality


    Class to read in streams configuration file, provdies
    read and write functionality


    An analysis tasks for computing cell masks for transects defined by geojson
    features

    Attributes
    ----------
    aggregationFunction : callable
        An aggregation function returned by
        :py:func:`geometric_features.aggregation.get_region_by_name()`

    geojsonFileName : str
        A geojson file, typically from the MPAS ``geometric_features``
        repository, defining the shapes to be masked

    outFileSuffix : str
        The suffix for the resulting mask file

    maskFileName : str
        The name of the output mask file


    An analysis tasks for computing cell masks for regions defined by geojson
    features

    Attributes
    ----------
    regionGroup : str
        The name of one of the supported region groups (see
        :py:func:`geometric_features.aggregation.get_region_by_name()`)

    aggregationFunction : callable
        An aggregation function returned by
        :py:func:`geometric_features.aggregation.get_region_by_name()`

    geojsonFileName : str
        A geojson file, typically from the MPAS ``geometric_features``
        repository, defining the shapes to be masked

    outFileSuffix : str
        The suffix for the resulting mask file

    maskFileName : str
        The name of the output mask file

    obsFileName : str
        The name of an observations file to create masks for.  But default,
        lon/lat are taken from an MPAS restart file

    lonVar, latVar : str
        The name of the longitude and latitude variables in ``obsFileName``

    meshName : str
        The name of the mesh or grid, used as part of the mask file name.
        Default is the MPAS mesh name


    An analysis tasks for computing cell masks for regions defined by geojson
    features

    Attributes
    ----------
    regionMaskSubtasks : dict of ``ComputeRegionMasksSubtask`` objects
        The subtasks of this task with file names as keys


    ``MpasRelativeDelta`` is a subclass of ``dateutil.relativedelta`` for
    relative time intervals with different MPAS calendars.

    Only relative intervals (years, months, etc.) are supported and not the
    absolute date specifications (year, month, etc.).  Addition/subtraction
    of ``datetime.datetime`` objects or other ``MpasRelativeDelta`` (but
    currently not ``datetime.date``, ``datetime.timedelta`` or other related
    objects) is supported.


An analysis task for sea ice area tendency due to thermodynamics


A subtask for computing climatologies of sea ice tendencies


    An analysis task for comparison of sea ice production against
    observations


    A subtask for computing climatologies of sea ice production from
    climatologies of individual production terms


    A subtask for reading and remapping sea ice production from AnIceFlux
    observations


An analysis task for ridge area per unit area of sea ice


A subtask for computing climatologies of sea ice ridge area fraction


An analysis task for sea ice snow depth


    A subtask for computing climatologies of sea ice snow depth from
    climatologies of sea ice area and snow volume


    An analysis task for comparison of sea ice concentration against
    observations


A subtask for reading and remapping sea ice concentration observations


    An analysis task for comparison of sea ice thickness against
    observations


A subtask for reading and remapping sea ice thickness observations


An analysis task for melt pond area


A subtask for computing climatologies of melt pond area fraction


    An analysis task for comparison of iceberg concentration against
    observations


    A subtask for reading and remapping iceberg concentration from Altiberg
    observations


An analysis task for sea ice volume tendency due to transport


An analysis task for snow-ice formation rate


A subtask for computing climatologies of snow-ice formation rate


    Performs analysis of time series of sea-ice properties.

    Attributes
    ----------

    mpasTimeSeriesTask : ``MpasTimeSeriesTask``
        The task that extracts the time series from MPAS monthly output

    controlconfig : mpas_tools.config.MpasConfigParser
        Configuration options for a control run (if any)


An analysis task for volume per unit ice area


A subtask for computing climatologies of sea ice ridge volume


    An analysis task for comparison of sea ice melting against
    observations


    A subtask for computing climatologies of sea ice melting from
    climatologies of individual melt terms


    A subtask for reading and remapping sea ice melting from AnIceFlux
    observations


An analysis task for sea ice area tendency due to transport


An analysis task for snow melt rate


A subtask for computing climatologies of snow melt rate


An analysis task for sea ice volume tendency due to thermodynamics


An analysis task for sea ice broadband albedo


A subtask for computing climatologies of sea ice broadband albedo


A subtask for reading and remapping SOSE fields to the comparison grid


    Plots a time series, summed or averaged over various depth ranges

    Attributes
    ----------

    regionName : str
        The name of the region to plot

    inFileName : str
        The file containing the time-depth data set to plot

    outFileLabel : str
        The prefix on each plot and associated XML file

    fieldNameInTitle : str
        The name of the field being plotted, as used in the plot title

    mpasFieldName : str
        The name of the variable in the MPAS timeSeriesStatsMonthly output

    yAxisLabel : str
        the y-axis label of the plotted field (including units)

    sectionName : str
        A section in the config file where the colormap and contour values
        are defined

    thumbnailSuffix : str
        The text to be displayed under the thumbnail image, to which the
        region name will be prepended

    imageCaption : str
        The caption when mousing over the plot or displaying it full
        screen

    galleryGroup : str
        The name of the group of galleries in which this plot belongs

    groupSubtitle : str
        The subtitle of the group in which this plot belongs (or blank
        if none)

    groupLink : str
        A short name (with no spaces) for the link to the gallery group

    galleryName : str
        The name of the gallery in which this plot belongs

    controlConfig : mpas_tools.config.MpasConfigParser
        The configuration options for the control run (if any)


    An analysis task for plotting of BGC variables

    Authors
    -------
    Phillip J. Wolfram, Riley X. Brady, Xylar Asay-Davis


Apply unit conversions to native model output to align with observations.


A subtask for reading and remapping BGC observations


    Performs analysis of time series of salinity anomalies from the first
    simulation year as a function of depth.


    Extract and plot time series of transport through transects on the MPAS
    mesh.


    Computes time-series of transport through transects.

    Attributes
    ----------
    startYear, endYear : int
        The beginning and end of the time series to compute

    masksSubtask : ``ComputeRegionMasksSubtask``
        A task for creating mask files for each ice shelf to plot

    transectsToPlot : list of str
        A list of transects to plot

    groupSuffix : str
        standard transects vs Arctic transects


Combine individual time series into a single data set


    Plots time-series output of transport through transects.

    Attributes
    ----------
    transect : str
        Name of the transect to plot

    transectIndex : int
        The index into the dimension ``nTransects`` of the transect to plot

    controlConfig : mpas_tools.config.MpasConfigParser
        The configuration options for the control run (if any)

    transportGroup : str (with spaces)
        standard transects (``Transport Transects``)
        vs Arctic transects (``Arctic Transport Transects``)


    Performs analysis of the time-series output of Antarctic sub-ice-shelf
    melt rates.


    Computes time-series of Antarctic sub-ice-shelf melt rates.

    Attributes
    ----------
    mpasTimeSeriesTask : ``MpasTimeSeriesTask``
        The task that extracts the time series from MPAS monthly output

    masksSubtask : ``ComputeRegionMasksSubtask``
        A task for creating mask files for each ice shelf to plot

    iceShelvesToPlot : list of str
        A list of ice shelves to plot


    Plots time-series output of Antarctic sub-ice-shelf melt rates.

    Attributes
    ----------
    iceShelf : str
        Name of the ice shelf to plot

    regionIndex : int
        The index into the dimension ``nRegions`` of the ice shelf to plot

    controlConfig : mpas_tools.config.MpasConfigParser
        The configuration options for the control run (if any)


    An analysis task for computing and plotting maps of the Barotropic /
    Subpolar Gyre streamfunction (BSF / SPGSF)

    Attributes
    ----------
    mpas_climatology_task : mpas_analysis.shared.climatology.MpasClimatologyTask
        The task that produced the climatology to be remapped and plotted


    A subtask for computing climatologies of the barotropic /subpolar gyre
    streamfunction from climatologies of normal velocity and layer thickness

    Attributes
    ----------
    min_depth : float
        The minimum depth for integration

    max_depth : float
        The maximum depth for integration

    include_bolus : bool
        Whether to include the bolus velocity in the streamfunction

    include_submesoscale : bool
        Whether to include the submesoscale velocity in the streamfunction


Performs analysis of ocean heat content (OHC) from time-series output.


    Compute and plot vertical profiles of regionally analyzed data.  The
    mean and standard deviation of the data are computed over each region.
    The mean and std. dev. are computed in time (within the requested seasons)
    and this result is plotted as a vertical profile with shading showing
    variability.


    Compute regional statistics on each layer and time point of a set of
    MPAS fields

    Attributes
    ----------
    parentTask : ``OceanRegionalProfiles``
        The main task of which this is a subtask

    startYear, endYear : int
        The beginning and end of the time series to compute

    max_bottom_depth : float
        The maximum bottom depth of cells to include in the profile statistics


    Plot a profile averaged over an ocean region and in time, along with
    variability in both space and time.

    Attributes
    ----------
    parentTask : ``AnalysisTask``
        The parent task of which this is a subtask

    season : str
        The season being plotted

    regionName : str
        The region being plotted

    field : dict
        Information about the field (e.g. temperature) being plotted

    controlconfig : mpas_tools.config.MpasConfigParser
        Configuration options for a control run (if any)


    Plots a time series of the global mean sea surface height relative to a
    reference time.

    Attributes
    ----------
    variableDict : dict
        A dictionary of variables from the time series stats monthly output
        (keys), together with shorter, more convenient names (values)

    timeSeriesFileName : str
        The name of the file where the ssh anomaly is stored

    controlConfig : mpas_tools.config.MpasConfigParser
        Configuration options for a control run (if one is provided)

    filePrefix : str
        The basename (without extension) of the PNG and XML files to write out


    Plot model output at transects and various longitudes around Antarctica,
    compared against the WOA23 climatology


    A class for loading and manipulating WOA transect data

    Attributes
    ----------

    fields : list of dict
        dictionaries defining the fields with associated WOA data


    An analysis task for comparison of sea surface salinity (sss) against
    observations


A subtask for reading and remapping SSS observations


    An analysis task for plotting climatologies of velocity components and
    magnitude


    A subtask for computing climatologies of velocity magnitude from zonal
    and meridional components


    A task for creating and remapping climatologies of MPAS fields sliced
    at a given set of depths

    Attributes
    ----------
    depths : list of {None, float, 'top', 'bot'}
        A list of depths at which the climatology will be sliced in the
        vertical.

    dsSlice : xarray.Dataset
        A dataset containing information needed to index variables at the
        designated depths


    Create T-S Diagrams of the climatology within a given ocean region

    Attributes
    ----------
    mpasClimatologyTask : ``MpasClimatologyTask``
        The task that produced the climatology to be remapped and plotted


    Compute the seasonal climatology for the given observational data set

    Attributes
    ----------
    obsDict : dicts
        Information on the observational data sets

    season : str
        The season to compute the climatology for


    Plots a T-S diagram for a given ocean region

    Attributes
    ----------
    regionGroup : str
        Name of the collection of region to plot

    regionName : str
        Name of the region to plot

    sectionName : str
        The section of the config file to get options from

    controlConfig : mpas_tools.config.MpasConfigParser
        The configuration options for the control run (if any)

    mpasClimatologyTask : ``MpasClimatologyTask``
        The task that produced the climatology to be remapped and plotted

    mpasMasksSubtask : ``ComputeRegionMasksSubtask``
        A task for creating mask MPAS files for each region to plot, used
        to get the mask file name

    obsDicts : dict of dicts
        Information on the observations to compare against

    season : str
        The season to compute the climatology for


    An analysis task for comparison of eddy kinetic energy (eke) against
    observations


    A subtask for computing climatologies of eddy kinetic energy from means of
    velocity and velocity-squared.


A subtask for reading and remapping EKE observations


    An analysis task for comparison of polar and global temperature and
    salinity against WOA23 climatology fields


A subtask for reading and remapping WOA fields to the comparison grid


    Plot model output at transects defined by lat/lon points in a geojson or
    NetCDF file


A class for loading and manipulating geojson transects


A class for loading and manipulating netcdf transects


    An analysis task for comparison of sea surface temperature (sst) against
    observations


A subtask for reading and remapping SST observations


Add velocity magnitude from zonal and meridional components to observations


    An analysis task for comparison of mixed layer depth (mld) against
    observations


    Plot model output at transects and various longitudes around Antarctica,
    compared against SOSE


    A class for loading and manipulating SOSE transect data

    Attributes
    ----------

    fields : list of dict
        dictionaries defining the fields with associated SOSE data


    Plot model output at WOCE transects and compare it against WOCE
    observations


    Plot meridional heat transport from the analysis member output.

    Attributes
    ----------

    mpasClimatologyTask : ``MpasClimatologyTask``
        The task that produced the climatology to be remapped and plotted

    controlconfig : mpas_tools.config.MpasConfigParser
        Configuration options for a control run (if any)


    Plots a time series vs. depth

    Attributes
    ----------

    controlconfig : mpas_tools.config.MpasConfigParser
        Configuration options for a control run (if any)

    regionName : str
        The name of the region to plot

    inFileName : str
        The file containing the time-depth data set to plot

    outFileLabel : str
        The prefix on each plot and associated XML file

    fieldNameInTitle : str
        The name of the field being plotted, as used in the plot title

    mpasFieldName : str
        The name of the variable in the MPAS timeSeriesStatsMonthly output

    unitsLabel : str
        The units of the plotted field, to be displayed on color bars

    sectionName : str
        A section in the config file where the colormap and contour values
        are defined

    regionMaskFile : str
        A geojson file with regions (including one corresponding to
        ``regionName``) that will be used to make an inset

    thumbnailSuffix : str
        The text to be displayed under the thumbnail image, to which the
        region name will be prepended

    imageCaption : str
        The caption when mousing over the plot or displaying it full
        screen

    galleryGroup : str
        The name of the group of galleries in which this plot belongs

    groupSubtitle : str
        The subtitle of the group in which this plot belongs (or blank
        if none)

    groupLink : str
        A short name (with no spaces) for the link to the gallery group

    galleryName : str
        The name of the gallery in which this plot belongs


    An analysis task for comparison of antarctic field against the Southern
    Ocean State Estimate


    An analysis task for comparison of Antarctic melt rates against
    observations


    A subtask for remapping climatologies of Antarctic melt rates and adding

    Attributes
    ----------
    landIceMask : xarray.DataArray
        A mask indicating where there is land ice on the ocean grid (thus,
        where melt rates are valid)

    renameDict : dict
        A dictionary use to rename variables in the climatology


A subtask for reading and remapping Antarctic melt-rate observations


    A subtask for plotting antarctic melt fields if available

    Attributes
    ----------
    doPlot : bool
        Whether the required variable from the climatology is available so that
        a plot should be generated


    Performs analysis of time series of potential temperature anomalies from
    a reference simulation year as a function of depth.


    An analysis task for plotting sea surface fluxes. Observational comparison
    is not supported because no observational datasets are currently available.


A subtask for computing climatologies of heat flux from temperature flux


Plots a histogram of a 2-d ocean variable.


    Fetches weight variables from MPAS output files for each variable in
    variableList.


    Plots a histogram diagram for a given ocean region

    Attributes
    ----------
    regionGroup : str
        Name of the collection of region to plot

    regionName : str
        Name of the region to plot

    sectionName : str
        The section of the config file to get options from

    controlConfig : mpas_tools.config.MpasConfigParser
        The configuration options for the control run (if any)

    mpasClimatologyTask : ``MpasClimatologyTask``
        The task that produced the climatology to be remapped and plotted

    mpasMasksSubtask : ``ComputeRegionMasksSubtask``
        A task for creating mask MPAS files for each region to plot, used
        to get the mask file name

    obsDicts : dict of dicts
        Information on the observations to compare against

    variableList: list of str
        list of variables to plot

    season : str
        The season to compute the climatology for


    This task generates time series plots from output from the conservation
    analysis member. A number of different plot types are supported, as indicated
    in the `plotTypes` config option in the `conservation` section.

    Attributes
    ----------
    config :  mpas_tools.config.MpasConfigParser
        Contains configuration options

    controlConfig :  mpas_tools.config.MpasConfigParser
        Contains configuration options for a control run, if provided

    outputFile : str
        The path to the output file produced by this analysis

    runDirectory : str
        The path to the restart files from the main simulation being analyzed

    historyDirectory : str
        The path to the history files from the main simulation being analyzed

    startYear : int
        The year to start the analysis

    endYear : int
        The year to end the analysis

    inputFiles : list of str
        The paths to all conservation AM files

    mainRunName : str
        The name of the main run from the config file

    plotTypes : list of str
        The plot types requested in the config file

    masterVariableList : dict of key-[list of str] pairs
        Keys are the supported plot types. Entries are lists of the variables
        that are needed to produce that plot type.

    derivedVariableList : dict of key-[list of str] pairs
        Keys are the derived variables. Entries are lists of variables in the
        AM output that are needed to derive that variable.

    xmlFileNames : list of str
        File names for xml output with full path

    filePrefixes : list of str
        File prefixes for xml files

    variableList : dict of key-[list of str] pairs
        Keys are the requested plot types. Entries are lists of the variables
        in the AM output that are needed to produce that plot type.


    Performs analysis of the time-series output of regionoal mean temperature,
    salinity, etc.


    Compute masks for regional and depth mean

    Attributes
    ----------
    masksSubtask : ``ComputeRegionMasksSubtask``
        A task for creating mask files for each region to plot

    regionGroup : str
        The name of the region group being computed (e.g. "Antarctic Basins")

    regionNames : list of str
        The names of the regions to compute


    Compute regional and depth mean at a function of time for a set of MPAS
    fields

    Attributes
    ----------
    startYear, endYear : int
        The beginning and end of the time series to compute

    masksSubtask : ``ComputeRegionMasksSubtask``
        A task for creating mask files for each region to plot

    regionGroup : str
        The name of the region group being computed (e.g. "Antarctic Basins")

    regionNames : list of str
        The names of the regions to compute


    Compute the regional mean of the obs climatology

    Attributes
    ----------


    Plots time-series output of properties in an ocean region.

    Attributes
    ----------
    regionGroup : str
        Name of the collection of region to plot

    regionName : str
        Name of the region to plot

    regionIndex : int
        The index into the dimension ``nRegions`` of the region to plot

    sectionName : str
        The section of the config file to get options from

    controlConfig : mpas_tools.config.MpasConfigParser
        The configuration options for the control run (if any)


    An analysis task for comparison of sea surface height (ssh) against
    observations


Change units from m to cm


A subtask for reading and remapping SSH observations