    Post-processing PCA algorithm, compatible with various options.

    Depending on what mode you need, parameters may vary. Check the list below to
    ensure which arguments are required. Currently, four variations of the PCA can be
    called :
        - full-frame PCA
        - annular PCA
        - grid PCA
        - single annulus PCA.
    Some parameters are common to several variations.

    Common parameters
    -----------------
    full_output: bool, optional
        Whether to return the final median combined image only or with other
        intermediate arrays.
    _algo_name: str, optional
        Name of the algorithm wrapped by the object.

    Grid parameters
    ---------------
    range_pcs : None or tuple, optional
        The interval of PCs to be tried. Refer to ``vip_hci.psfsub.pca_grid`` for more
        information.
    mode : {'fullfr', 'annular'}, optional
        Mode for PCA processing (full-frame or just in an annulus).
    fmerit : {'px', 'max', 'mean'}
        The function of merit to be maximized. 'px' is *source_xy* pixel's SNR,
        'max' the maximum SNR in a FWHM circular aperture centered on
        ``source_xy`` and 'mean' is the mean SNR in the same circular aperture.
    plot : bool, optional
        Whether to plot the SNR and flux as functions of PCs and final PCA
        frame or not.
    save_plot: string
        If provided, the pc optimization plot will be saved to that path.
    initial_4dshape : None or tuple, optional
        Shape of the initial ADI+mSDI cube.
    exclude_negative_lobes : bool, opt
        Whether to include the adjacent aperture lobes to the tested location
        or not. Can be set to True if the image shows significant neg lobes.

    Single annulus parameters
    -------------------------
    r_guess : float
        Radius of the annulus in pixels.


    Post-processing LOCI algorithm.

    Parameters
    ----------
    full_output: bool, optional
        Whether to return the final median combined image only or with other
        intermediate arrays.
    _algo_name: str, optional
        Name of the algorithm wrapped by the object.


High-contrast imaging frame (2d array).

    Parameters
    ----------
    data : numpy ndarray
        2d array.
    hdu : int, optional
        If ``cube`` is a String, ``hdu`` indicates the HDU from the FITS file.
        By default the first HDU is used.
    fwhm : float, optional
        The FWHM associated with this dataset (instrument dependent). Required
        for several methods (operations on the cube).


High-contrast imaging dataset class.

    Parameters
    ----------
    cube : str or numpy array
        3d or 4d high-contrast image sequence. If a string is provided, cube is
        interpreted as the path of the FITS file containing the sequence.
    hdu : int, optional
        If ``cube`` is a String, ``hdu`` indicates the HDU from the FITS file.
        By default the first HDU is used.
    angles : list or numpy array, optional
        The vector of parallactic angles.
    wavelengths : list or numpy array, optional
        The vector of wavelengths (to be used as scaling factors).
    fwhm : float, optional
        The FWHM associated with this dataset (instrument dependent). Required
        for several methods (operations on the cube).
    px_scale : float, optional
        The pixel scale associated with this dataset (instrument dependent).
    psf : numpy array, optional
        The PSF template associated with this dataset.
    psfn : numpy array, optional
        Normalized/cropped/centered version of the PSF template associated with
        this dataset.
    cuberef : str or numpy array
        3d or 4d high-contrast image sequence. To be used as a reference cube.


    Post-processing full-frame non-negative matrix factorization algorithm.

    Parameters
    ----------
    delta_rot: int or float or tuple of floats, optional
        Factor for tunning the parallactic angle threshold, expressed in FWHM.
        Due to this parameter being shared between annular and fullframe versions of
        NMF, the annular version is forcefully set by default. If the fullframe
        version is selected, the default value is changed to the fullframe value.
    full_output: bool, optional
        Whether to return the final median combined image only or with other
        intermediate arrays.
    _algo_name: str, optional
        Name of the algorithm wrapped by the object.


Post-processing forward model matching filter algorithm.


    Post-processing LLSG algorithm.

    Parameters
    ----------
    full_output: bool, optional
        Whether to return the final median combined image only or with other
        intermediate arrays.
    _algo_name: str, optional
        Name of the algorithm wrapped by the object.


    Set of parameters for the frame differencing module.

    See the function `frame_diff` below for the documentation.


    Set of parameters for the NMF full-frame algorithm.

    See function `nmf` below for the documentation.


    Set of parameters for the LLSG algorithm.

    See function `llsg` below for the documentation.


    Set of parameters for the median subtraction module.

    See function `median_sub` for documentation.


    Set of parameters for the NMF annular algorithm.

    See function `nmf_annular` below for the documentation.


    Set of parameters for the PCA module.

    See function `pca` below for the documentation.


    Class for SVD decomposition of 2d, 3d or 4d HCI arrays.

    Parameters
    ----------
    data : numpy ndarray
        Input array (2d, 3d or 4d).
    mode : {'fullfr', 'annular'}, optional
        Whether to use the whole frames or a single annulus.
    inrad : None or int, optional
        [mode='annular'] Inner radius.
    outrad : None or int, optional
        [mode='annular'] Outer radius.
    svd_mode : {'lapack', 'arpack', 'eigen', 'randsvd', 'cupy', 'eigencupy',
        'randcupy', 'pytorch', 'eigenpytorch', 'randpytorch'}, str optional
        Switch for the SVD method/library to be used.

        * ``lapack``: uses the LAPACK linear algebra library through Numpy
          and it is the most conventional way of computing the SVD
          (deterministic result computed on CPU).

        * ``arpack``: uses the ARPACK Fortran libraries accessible through
          Scipy (computation on CPU).

        * ``eigen``: computes the singular vectors through the
          eigendecomposition of the covariance M.M' (computation on CPU).

        * ``randsvd``: uses the randomized_svd algorithm implemented in
          Sklearn (computation on CPU), proposed in [HAL09]_.

        * ``cupy``: uses the Cupy library for GPU computation of the SVD as in
          the LAPACK version. `

        * ``eigencupy``: offers the same method as with the ``eigen`` option
          but on GPU (through Cupy).

        * ``randcupy``: is an adaptation of the randomized_svd algorithm,
          where all the computations are done on a GPU (through Cupy). `

        * ``pytorch``: uses the Pytorch library for GPU computation of the SVD.

        * ``eigenpytorch``: offers the same method as with the ``eigen``
          option but on GPU (through Pytorch).

        * ``randpytorch``: is an adaptation of the randomized_svd algorithm,
          where all the linear algebra computations are done on a GPU
          (through Pytorch).

    scaling : {None, "temp-mean", spat-mean", "temp-standard",
        "spat-standard"}, None or str optional
        Pixel-wise scaling mode using ``sklearn.preprocessing.scale``
        function. If set to None, the input matrix is left untouched. Otherwise:

        * ``temp-mean``: temporal px-wise mean is subtracted.

        * ``spat-mean``: spatial mean is subtracted.

        * ``temp-standard``: temporal mean centering plus scaling pixel values
          to unit variance (temporally).

        * ``spat-standard``: spatial mean centering plus scaling pixel values
          to unit variance (spatially).

        DISCLAIMER: Using ``temp-mean`` or ``temp-standard`` scaling can improve
        the speckle subtraction for ASDI or (A)RDI reductions. Nonetheless, this
        involves a sort of c-ADI preprocessing, which (i) can be dangerous for
        datasets with low amount of rotation (strong self-subtraction), and (ii)
        should probably be referred to as ARDI (i.e. not RDI stricto sensu).

    scale_list : numpy ndarray, optional
        Scaling factors to be used for re-scaling the spectral channels and
        aligning the speckles in the case of 4D HCI cubes.

    verbose : bool, optional
        If True intermediate messages and timing are printed.


    Set of parameters for the LOCI algorithm.

    See function `xloci` below for the documentation.


    Set of parameters for the roll subtraction module.

    See function `roll_sub` for documentation.


Set of parameters for the annular PCA module.


    This class implements the bulk of the PACO algorithm as described in
    [FLA18]_. In general, the idea is to take in an ADI stack of images and
    statistically determine if there is a signal above the background in each
    'patch' of the image. This is done by tracing the ark of the hypothesized
    planet through the stack, and comparing this set of patches to a set
    consisting of background only. This is done for each pixel (or sub-pixel)
    location in the image. The output is a signal-to-noise and/or a flux map
    over the field of view. The user can choose to use FullPACO or FastPACO,
    which are described by algorithms 1 and 2 of [FLA18]_. FastPACO has been
    parallelized, and is the recommended usage.

    This output can then be used to compute an unbiased estimate of the flux
    of point sources detected in the image above some user-supplied detection
    threshold.

    Parameters
    ----------
    cube : numpy.ndarray
        3D science frames taken in pupil tracking/ADI mode.
        Dimensions should be (time, x, y), and units should be detector units
        (ie output of SPHERE or GPI reduction pipelines). The data should be
        centered, and have pre-processing already applied (e.g. bad pixel
        correction).
    angles : numpy.ndarray
        List of derotation angles for each frame in degrees. Length of this
        array should be the same as the time axis of the science cube.
    psf : numpy.ndarray
        Unsaturated PSF image. If a cube is provided, the median of the cube
        will be used.
    dit_psf : float, optional
        Integration time of the unsaturated PSF in seconds. The PSF is
        normalised to dit_science/dit_psf/nd_transmission.
    dit_science : float, optional
        Integration time of the science frames in seconds. The PSF is normalised
        to dit_science/dit_psf/nd_transmission.
    nd_transmission : float, optional
        Transmission of an ND filter used to aquire the unsaturated PSF. The PSF
        is normalised to dit_science/dit_psf/nd_transmission.
    fwhm : float, optional
        FWHM of PSF in arcseconds. Default values give 4px radius.
    pixscale : float, optional
        Detector pixel scale in arcseconds per pixel.  Default values give 4px
        radius.
    rescaling_factor : float, optional
        Scaling for sub/super pixel resolution for PACO. Will rescale both the
        science cube and the PSF.
    verbose : bool, optional
        Sets level of printed outputs.


This class implements Algorithm 2 from [FLA18]_.


Implementation of Algorithm 1 from [FLA18]_


    Set of parameters for the FMMF algorithm.

    See function `fmmf` below for the documentation.


    Set of parameters for the ANDROMEDA algorithm.

    See function `andromeda` below for the documentation.


Class for the generation of receiver operating characteristic (ROC) curves.


    Set of parameters for the iterative PCA routine.

    Inherits from PCA_Params.

    See function `ipca` for documentation.


    Set of parameters for the iterative NMF routine.

    Inherits from NMF.

    See function `inmf` for documentation.


    Set of parameters for the roll subtraction routine.

    The class inherits from ROLL_SUB_Params.

    See function `iroll_sub` for documentation.


Class used to generate a synthetic disc, inspired from a light version\
    of the GRATER tool (GRenoble RAdiative TransfER) written originally in IDL\
    [AUG99]_, and converted to Python by J. Milli.


Class representing the dust distribution.


Class representing the elliptical dust distribution with 2 Power laws.


    Class representing the scattering phase function (spf).

    It contains the attribute phase_function_calc that implements either a
    single Henyey Greenstein phase function, a double Heyney Greenstein,
    or any custom function (data interpolated from
    an input list of phi, spf(phi)).


Implementation of a scattering phase function with a single Henyey\
    Greenstein function.


Implementation of a scattering phase function with a double Henyey\
    Greenstein function.


Custom implementation of a scattering phase function by providing a list\
        of scattering phase angles and corresponding values of the phase \
        function.


A class to store spectra. This is mainly to provide
        reusable functionality.


    class binary_psr

        This class reads in a parfile (the only option for instantiation) of
            a binary pulsar.  It allows access the calculation of the mean,
            eccentric, and true anomalies, orbital position, radial velocity,
            and predicted spin period as a function of time.


A class to represent a generic pulse profile.


A class to represent a pulse profile made up of
        multiple components.


A class to represent a vector of pulse profiles.
        This can be used to encode intrinsic profile variation,
        or extrisinc smearing/scattering across the band


A class for input parameters for the spd plots.


    A class for reading in single pulse files.

    A quick description of each item in the class:

     data_zerodm
        A 2D freq-vs-time array around the pulse, not dedispersed (zero-DM'd data)
     data_zerodm_dedisp
        A 2D freq-vs-time array around the pulse, dedispersed (zero-DM'd data)
     data_nozerodm
        A 2D freq-vs-time array around the pulse, not dedispersed (non-zero-DM'd data)
     data_nozerodm_dedisp
        A 2D freq-vs-time array around the pulse, dedispersed (non-zero-DM'd data)

     spfiles
        PRESTO single pulse files for the DM-vs-time scatterplot
     dmVt_this_dms
        DM values for this pulse in the DM-vs-time scatterplot
     dmVt_this_times
        Time values for this pulse in the DM-vs-time scatterplot
     dmVt_this_sigmas
        Sigma values (determining point size) for this pulse in the DM-vs-time scatterplot
     dmVt_this_widths
        box car values for this pulse.

     dmsweep_delays
        Delays corresponding to frequencies for drawn-in dispersion sweep
     dmsweep_freqs
        Frequencies corresponding to delays for drawn-in dispersion sweep

     filename
        Name of the observation file that was analyzed
     telescope
        Which telescope was used
     ra
        Right ascension as hh:mm:ss.s string
     dec
        Declination as dd:mm:ss.s string
     ra_deg
        Right ascension in degrees
     dec_deg
        Declination in degrees
     mjd
        Observation MJD
     total_obs_time
        Total duration of the observation this pulse was found in, in seconds
     rank
        Single pulse sifting rank
     tsamp
        Sampling time of raw data in seconds
     best_dm
        Best determined dispersion measure for this event
     sigma
        Significance of this event
     pulse_peak_sample
        The sample number in the full dedispersed time series at which this event peaked
     pulse_peak_time
        The time in seconds in the full dedispersed time series at which this event peaked
     pulsewidth_bins
        The width of the boxcar filter used to optimally detect this event, in number of bins
     pulsewidth_seconds
        The width of the boxcar filter used to optimally detect this event, in seconds
     nsamp
        The number of original time series samples included in the (possibly downsampled) waterfall plot
     waterfall_duration
        The total duration of the dedispersed waterfall plot
     waterfall_start_time
        The time (in seconds) in the full dedispersed time series at which the waterfall plot begins
     waterfall_tsamp
        Sampling time of the waterfall plot in seconds
     waterfall_nbins
        The number of samples across the dedispersed waterfall plot
     waterfall_nsubs
        The number of frequency bins across the waterfall plot
     waterfall_prededisp_nbins
        The number of samples prior to dedispersing and cutting off the ends of the waterfall plot
     min_freq
        The lowest frequency plotted
     max_freq
        The highest frequency plotted
     sweep_duration
        The total duration of the dispersed pulse across the band
     sweep_start_time
        The time at which to start plotting the dispersed reference line


Define single pulse group


A PRESTO FFT file (i.e. with suffix '.fft') and associated metadata


A PRESTO stack of FFT power spectra, normalized as chi^2/2


An individual stack candidate.


Candidates from a stack search of power spectra.


    class obs_info(fits_filenm)
        A class describing the observation and the analysis.


    class dedisp_plan(lodm, dmstep, dmsperpass, numpasses, numsub, downsamp)
       A class describing a de-dispersion plan for prepsubband in detail.


    class obs_info(fil_filenm)
        A class describing the observation and the analysis.


The Resids object contains the following information
        about TEMPO residuals:
            bary_TOA
            bary_freq
            numTOAs
            orbit_phs
            postfit_phs
            postfit_sec
            prefit_phs
            prefit_sec
            uncertainty
            weight


    class dedisp_plan(lodm, dmstep, dmsperpass, numpasses, numsub, downsamp)
        A class describing a de-dispersion plan for prepsubband in detail.


Process hub for creating plots.

    Class that carries the input dictionary (pid) and directs
    the program to accomplish plotting tasks.

    Args:
        **kwargs (dict): Combination of all input dictionaries to have their information
            stored as attributes.

    Keyword Arguments:
        plot_info (dict): Dictionary containing all the individual plot info.
        sharex, sharey (bool, optional): Applies sharex, sharey as used in ``plt.subplots()``.
            See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html
            Default is True.
        figure_width/figure_height (float, optional): Dimensions of the figure set with
            ``fig.set_size_inches()`` from matplotlib. Default is 8.0 for each.
        bottom (float, optional): Sets position of bottom of subplots in figure coordinates.
            Default is 0.1.
        top (float, optional): Sets position of top of subplots in figure coordinates.
            Default is 0.85.
        left (float, optional): Sets position of left edge of subplots in figure coordinates.
            Default is 0.12.
        right (float, optional): Sets position of right edge of subplots in figure coordinates.
            Default is 0.79.
        wspace (float, optional): The amount of width reserved for space between subplots,
           It is expressed as a fraction of the average axis width. Default is 0.3.
        hspace (float, optional): The amount of height reserved for space between subplots,
           It is expressed as a fraction of the average axis width. Default is 0.3.
        snr_input (dict): kwargs for :class:`gwsnrcalc.gw_snr_calculator.SNR`.

    Attributes:
        total_mass (1D array of floats): Total mass of each binary.
        mass_ratio (1D array of floats): Mass ratio of each binary.
        m1 (1D array of floats): Mass 1 of each binary.
        m2 (1D array of floats): Mass 2 of each binary.
        z_or_dist (1D array of floats): Redshift or distance of each binary.
        spin_1 (1D array of floats): Spin of mass 1 of each binary.
        spin_2 (1D array of floats): Spin of mass 2 of each binary.
        start_time (1D array of floats): Start time in years before merger of each binary.
        total_mass (1D array of floats): End time in years before merger of each binary.
        dist_type (str): Which type of distance measure is used. Options are `redshift`,
            `luminosity_distance`, or `comoving_distance`.
        value_classes (obj): Class :class:`bowie.plotutils.readdata.PlotVals` that
            holds data.
        final_dict (dict): Dictionary with SNR results.
        Note: All kwargs above are added as attributes.


Label contains the methods inherited by SinglePlot.

    These methods are used by SinglePlot class to add configuration
    information pertaining to the labels dict involved in plot creation.

    All attributes are appended to the LabelContainer class.
    The LabelContainer class is contained in the label attribute
    in the SinglePlot class.


Holds all of the attributes related to the label dictionary.

    This class is used to store the information when methods from Label class
    are called by the SinglePlot class.

    Attributes:
        xlabel/ylabel (str, optional): x,y label for specific plot.
        title (str, optional): Title for specific plot.
        xlabel_fontsize/ylabel_fontsize (float, optional): Sets fontsize for x,y label for specific
            plot. Default is 20.
        title_fontsize (float, optional): Sets fontsize for y label for specific
            plot. Default is 20.
        x_tick_label_fontsize/y_tick_label_fontsize (float, optional): Sets fontsize for x,y tick
            labels for specific
            plot. Default is 14.


 Limits contains the methods inherited by SinglePlot.

    These methods are used by SinglePlot class to add configuration
    information pertaining to the limits dict involved in plot creation.

    All attributes are appended to the LimitsContainer class.
    The LimitsContainer class is contained in the limits attribute
    in the SinglePlot class.


Holds all of the attributes related to the limits dictionary.

    This class is used to store the information when methods from Limits class
    are called by the SinglePlot class.

    Attributes:
        xlims,ylims (len-2 list of floats): REQUIRED. x,y limits for specific plot.
            If ``xscale,yscale == log``, the xlims/ylims must be log10 of the actual desired values.
            Ex. for 1e4 to 1e8, xlims would be ``[4.0, 8.0]``.
        dx,dy (float): Required. Spacing of x and y ticks.
            If ``xscale,yscale == log``, then dx,dy is a log10 value. See examples.
        xscale,yscale (str): Choices are `lin` for linear spacing or `log`
            for log (base 10) spacing.
            Default is `lin`.
        reverse_x_axis,reverse_y_axis (bool, optional): Reverses the tick
            marks on the x,y axis.
            Default is ``False``.


Legend contains the methods inherited by SinglePlot.

    These methods are used by SinglePlot class to add configuration
    information pertaining to the legend dict involved in plot creation.

    All attributes are appended to the LegendContainer class.
    The LegendContainer class is contained in the legend attribute
    in the SinglePlot class.


Holds all of the attributes related to the add_legend dictionary.

    This class is used to store the information when methods from Legend class
    are called by the SinglePlot class.

    Attributes:
        labels (list of str): String representing each item in plot that
            will be added to the legend.
        legend_kwargs (dict): Stores kwargs for ``ax.legend()``.


 Extra contains the methods inherited by SinglePlot.

    These methods are used by SinglePlot class to add configuration
    information pertaining to the extra dict involved in plot creation.

    All attributes are appended to the ExtraContainer class.
    The ExtraContainer class is contained in the extra attribute
    in the SinglePlot class.

    The associated methods in Extra class as well as the attributes
    in the ExtraContainer class detail the options related to
    extra customization of plots.


Holds all of the attributes related to the extra dictionary.

    This class is used to store the information when methods from Extra class
    are called by the SinglePlot class.

    Attributes:
        add_grid (bool, optional): Adds gridlines to plots. Overrides setting from "general".
            Default is True.
        contour_vals (list of floats, optional): Provides contour values for Waterfall plot only.
            Default is [0.,10,20,50,100,200,500,1000,3000,1e10].
        snr_contour_value (float, optional): Adds contour for a specific value for
            Waterfall plot. Color is white.
            For Ratio and Horizon plots, this overrides the SNR_CUT for a custom value.
        order_contour_lines (bool, optional): This only applies to ratio plots.
            This will show contour lines at each order of magnitude ratio. Default is False.
        show_loss_gain (bool, optional): Toggle loss/gain contours on and off.
            Only applies to Ratio plots. Default is True.
        ratio_comp_value (float, optional): This sets the minimum SNR necessary
            for both configurationsin a ratio plot to show the ratio contours.
            (rho_1>ratio_comp_value & rho_2>ratio_comp_value) in order to display the contour.
            Default is same value as loss/gain contour (which defaults to SNR_CUT).


 DataImport contains the methods inherited by SinglePlot.

    These methods are used by SinglePlot class to add data for each plot.
    This class allows for file import as well as indexing to files that
    have already been imported.


Holds all of the attributes related to a dataset.

    This class holds file information for each file imported as an added
    dataset. It does not take index information, which is added to the GeneralContainer class.

    The attributes associated with DataImportContainer can override GeneralContainer values.
    However, the GeneralContainer is used to set these values if it applies to
    all or most of the plots.

    Attributes:
        file_name (str, optional): Name (path) for file.
            Required if reading from a file (at least one).
            Required if file_name is not in "general". Must be ".txt" or ".hdf5".
            Can include path from working directory.
        label (str, optional): Column label in the dataset corresponding to desired SNR value.
            Required if reading from a file (at least one).
        x_column_label/y_column_label (str, optional): Column label from input file identifying
            x/y values. This can override setting in "general". Default
            is `x`/`y`.


Add information for each singular plot.

    Each plot has special information stored in its dictionary.
    See above documentation for this information.

    SinglePlot inherits methods from Label, Limits, Legend, Extra, and DataImport.
    It uses the methods to store values in the respective Container classes.

    Attributes:
        type (str): Which type of plot. Currently supporting `Ratio`, `Watefall`,
            `Horizon`.
        file (list of obj): List of DataImportContainer objects with information on which
            dataset to use.
        label (obj): LabelContainer holding informaiton pertaining to labels of the plot.
            Default is empty container or ``{}``.
        limits (obj): LimitsContainer holding information pertaining to limits of the plot.
            Default is empty container or ``{}``.
        legend (obj): LegendContainer holding information pertaining to legend for the plot.
            Default is empty container or ``{}``.
        extra (obj): ExtraContainer holding information pertaining to extra
            information for the plot.
            Default is empty container or ``{}``.


Holds all of the attributes related to the figure dictionary.

    This class is used to store the information when methods from Figure class
    are called by the MainContainer class.

    Attributes:
        show_figure (bool, optional): Use ``plt.show()`` function from matplotlib to show plot.
            Do not use this in Jupyter Notebook. Use the magic command: ``%matplotlib inline``.
            Default is False.
        save_figure (bool, optional): Use ``fig.savefig()`` function from matplotlib
            to save figure. Default is False.
        output_path (str, optional): Path from the working directory to save the figure,
            including file name and extension. Required if ``save_figure == True``.
        savefig_kwargs (dict, optional): Additional kwargs for ``fig.savefig()``.
        subplots_adjust_kwargs (dict, optional): Kwargs for sizing with ``plt.subplots_adjust()``.
        spacing (str, optional): This sets the general spacing of the plot configuration.
            Choices are `wide` or `tight` (``hspace = wspace = 0.0``). Tight spacing will cut
            off the outer labels on each axis due to axes contacting each other.
            Default is `wide`.
        fig_x_label/fig_y_label (str, optional): Overall figure label on the left and bottom.
            Called with ``fig.text()`` from matplotlib.
        fig_x_label_kwargs, fig_y_label_kwargs (dict, optional):
            Kwargs for ``fig.text()``.
        fig_title (str, optional): Overall figure title. Produced with ``fig.suptitle()``
            from matplotlib.
        fig_title_kwargs (dict, optional): Kwargs for `fig.suptitle``.
        figure_width/figure_height (float, optional): Dimensions of the figure set with
        ``fig.set_size_inches()`` from matplotlib. Default is 8.0 for each.
        colorbars (obj): ColorbarContainer object carrying information for the colorbars.


 General contains the methods inherited by MainContainer.

    These methods are used by MainContainer class to add information that applies
    to all plots. Many of its settings pertaining to plots
    can be overriden with methods in SinglePlot.


Holds all of the attributes related to the general dictionary.

    This class is used to store the information when methods from General class
    are called by the MainContainer class.

    Args:
        nrows, ncols (int): Number of rows/columns of plots present in the figure.
            These determine the number of plots to create.
        sharex, sharey (bool, optional): Applies sharex, sharey as used in ``plt.subplots()``.
            See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html
            Default is True.

    Attributes:
        num_rows, num_cols (int): Number of rows/columns of plots present in the figure.
        xlims/ylims (len-2 list of floats): Sets the x,y limits of the plots.
            Can be overridden for specific plots. If xscale/yscale == log,
            the xlims/ylims must be log10 of the actual desired values.
            Ex. for 1e4 to 1e8, xlims would be [4.0, 8.0].
            Required if xlims/ylims are not specified for every specific plot.
        dx, dy (float): Spacing of x and y ticks. If xscale/yscale == log,
            the dx/dy is a log10 value. See examples. Required if limits are not
            set for each specific plot.
        xscale/yscale (str, optional): Choices are lin for linear spacing or log for
            log (base 10) spacing. Default is `lin`.
        tick_label_fontsize (float, optional): Sets fontsize for both x and y
            tick labels on the plots. This can be overridden for individual plots.
            Default is 14.
        x_tick_label_fontsize/y_tick_label_fontsize (float, optional): Sets fontsize fot
            x/y tick labels. This overrides `tick_label_fontsize` and
            can be overridden for specific plots. Default is 14.
        WORKING_DIRECTORY (str, optional): Working directory for file export and retrieval.
            Default is ``'.'``.
        SNR_CUT (float, optional): The SNR cut for a detectable signal. Usually between 1-10.
            Default is 5.0.
        switch_backend (str, optional): Use for switching backend of matplotlib.
            Use if running codes in parallel. Typical string value is "agg".
        file_name (str, optional): File name for input SNR grids. Can be overridden by
            specific plot. Required if no file names are given in "plot_info" dictionaries.
        x_column_label/y_column_label (str, optional): Column label from input file
            identifying x/y values. This can be overrided in the file_dicts for specific files.
            Default is `x`/`y`.
        sharex, sharey (bool, optional): Applies sharex, sharey as used in ``plt.subplots()``.
            See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html
            Default is True.
        add_grid (bool, optional): Adds gridlines to all plots. Can be overridden
            for specific plots. Default is True.
        reverse_x_axis, reverse_y_axis (bool, optional): Reverses the tick marks on the x/y axis.
            Can be overridden for specific plots. Default is False.


Main class for creating input dictionary to ``make_plot.py``.

    This class creates a pythonic way to add information to the input dictionary
    to ``make_plot.py``. It creates and can read out this dictionary.

    MainContainer inherits methods from General class so that it can add
    general dictionary information to GeneralContainer class

    The ``__init__`` function is similar to a call to ``plt.subplots()``.

    # TODO: make default on sharing to False?

    Args:
        nrows/ncols (int): Number of rows/columns of plots present in the figure.
            This is passed into the general dictionary. These determine the number of
            plots to create.
        sharex/sharey (bool, optional): Applies sharex, sharey as used in ``plt.subplots()``.
            See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html
            Default is True.
        print_input (bool, optional): If True, print the dictionary created by MainContainer
            class after it is completed.

    Attributes:
        total_plots (int): `nrows`*`ncols`.
        general (obj): GeneralContainer class for holding information for general dictionary.
        ax (obj or list of objects): SinglePlot object for holding information pertaining
            to specific plots. If there is more than one plot in the figure, this will
            be a list of SinglePlot objects of ``len=total_plots``.
        print_input (bool, optional): If True, print the dictionary created by MainContainer
            class after it is completed.


Base class for the subclasses designed for creating the plots.

    All of the plot types inherit this class and its methods. The __init__ method
    is the same for all plots. Each plot_type in :mod:`bowie.plotutils.plottypes`
    has its own ``make_plot`` method and associated methods for creating the plot.

    Args:
        fig (obj): Figure environment for the plots.
        axis (obj): Axis object representing specific plot.
        xvals/yvals/zvals (list of 2D arrays of floats): List of x,y,z-value
            arrays for the plot.

    Keyword Arguments:
        plot_type (str): String representing the plot type.
        SNR_CUT (float): SNR cut for detectability or another desired value.
        xlims/ylims (len-2 list of floats): Limits for the x/y axis. If
            ``xscale/yscale == 'log'``, these values are the log10 of the limits.
        dx/dy (float): Amount to increment for tick labels. If log10 of values,
            then dx/dy repesents increments in log10.
        xscale/yscale (str): `lin` for linear scale. `log` for log10 scale.
        title/xlabel/ylabel (str, optional): String for title/xlabel/ylabel for specific plot.
        title_kwargs/xlabel_kwargs/ylabel_kwargs: Kwargs for call to add string labelling to plot.
        x_tick_label_fontsize/y_tick_label_fontsize (int, optional): Tick label fontsize
            for x/y axis. Default is 14.
        tick_label_fontsize (int, optional): Tick label fontsize for both x and y axes.
            If not None, this will set both axis in one go to the same value.
            Default is None.
        reverse_x_axis/reverse_y_axis (bool, optional): If True, reverse the order
            of the ticks along each axis from ascending to descending. Default is False.
        spacing (str, optional): Spacing of plots. `wide` indicates spaced out plots
            (``hspace = 0.3`` and ``wspace = 0.3`` in subplots_adjust).
            All the tick labels will show. If `tight`, no space between plots
            in the figure (``hspace = 0.0`` and ``wspace = 0.0`` in subplots_adjust).
            In this case, the edge tick labels are cut off for clarity. Default is `wide`.
        add_grid (bool, optional): If True, add a grid to the specific plot. Default is True.
        colorbar (obj, optional): Object of type
            :class:`bowie.plotutils.baseplot.FigColorbar`. This houses information for the
            colorbar for the associated plot type. Default is None.
        colormap (str, optional): String represented the the colormap choice through python's
            predefined colormaps. This is for ratio plots. Default is `coolwarm`.
        loss_gain_status (bool, optional): If True, show the loss gain contours.
            This only applies to :class:`bowie.plotutils.plottypes.Ratio` plot.
            Default is True.
        snr_contour_value (float, optional): This will set the value for contours in plots.
            In :class:`bowie.plotutils.plottypes.Ratio` plots, this sets the value for
            loss/gain contours and minimal value for ratio contours (overrides SNR_CUT). For
            :class:`bowie.plotutils.plottypes.Horizon` plots this sets the value
            for the horizon contours. For :class:`bowie.plotutils.plottypes.Waterfall`
            plots, this will add an additional contour in white. Default is None.
        order_contour_lines (bool, optional): Show dashed lines at each order of magnitude
            within the ratio contours. Default is False.
        ratio_comp_value (float, optional): If not None, this value is used as the minimum
            value for the ratio contours. If None, this value will be `SNR_CUT` or
            `snr_contour_value` if given. In other words, it will be the
            same as loss/gain contour maximum. Default is None.
        legend_kwargs (dict, optional): kwargs for call to ax.legend(). Default is {}.
        legend_labels (list of str, optional): Labels for the curves in the legend.
            If calling legend, these are required. Default is [].
        add_legend (bool, optional): If True, add legend.
        contour_vals (list or array of floats): Contour values to use for
            :class:`bowie.plotutils.plottypes.Waterfall`. Default is
            np.array([0., 10, 20, 50, 100, 200, 500, 1000, 3000, 1e10]).
            Default kwarg value is [].

    Attributes:
        comparison_value (float): Value to use for contour comparisons. This will either
            be SNR_CUT or snr_contour_value.
        Note: all args and kwargs become attributes.


Create colorbars

    This class holds and creates colorbars for the plots shown. It has default values
    for each plot that can be replaced by passing kwargs.

    Args:
        fig (obj): Figure object for adding the colorbar.
        plot_type (str): String representing the plot type for this colorbar.

    Keyword Arguments:
        cbar_ticks (list or array of floats, optional): List or array representing
            the ticks to be shown on the colorbar. Default kwarg is []. If ``cbar_ticks == []``,
            the default for each plot type is used. For Waterfall it is
            [0., 10, 20, 50, 100, 200, 500, 1000, 3000, 1e10]. For Ratio plots,
            it is [-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0].
        cbar_tick_labels (list of str, optional): List of strings corresponding to the labels
            for the cbar_ticks. Default is []. In this case, default for each plot type is used.
            Waterfall plots default to [0., 10, 20, 50, 100, 200, 500, 1000, 3000].
            Ratio plots default to [-2.0, -1.0, 0.0, 1.0, 2.0].
        cbar_ticks_fontsize (int, optional): Fontsize for colorbar ticks. Default is 15.
        cbar_label_fontsize (int, optional): Label fontsize for the colorbar. Default is 20.
        cbar_pos (int, optional): Describes defined positions (axes) for the colorbar.
            Default positions are 1-5. {'1': [0.83, 0.49, 0.03, 0.38],
            '2': [0.83, 0.05, 0.03, 0.38], '3': [0.05, 0.92, 0.38, 0.03],
            '4': [0.47, 0.92, 0.38, 0.03], '5': [0.83, 0.1, 0.03, 0.8]}. Default is 1 for Waterfall
            and 2 for Ratio. Default value for kwarg is 'use_default'.
        cbar_axes (len-4 list of floats, optional): Custom axes for colorbar. This overrides any
            entry to ``cbar_pos``. Default is []. In this case, it will default to
            axes for ``cbar_pos`` value.
        cbar_orientation (str, optional): Vertical or horizontal orientation for the colorbar.
            Default is vertical if the bar is thinner than it is tall.
            If it is wider than it is tall, default is horizontal. Default value for kwarg is None.
        cbar_label_pad (float, optional): Label padding of colorbar label. Default is None.
            This means -60 for horizontal and 10 for vertical. # TODO check these numbers.

    Attributes:
        cbar_ax (obj): Axes object on the figure for the colorbar.
        cbar_var (str): String representing the axis of the colorbar to add labels to.
            For horizontal this is 'x' and for vertical it is 'y'.
        Note: all args and kwargs are added as attributes.


Create Waterfall plot.

    Waterfall is a subclass of :class:`bowie.plotutils.baseplot.CreateSinglePlot`.

    Waterfall creates an snr filled contour plot similar in style to those seen in
    the LISA proposal. Contours are displayed at snrs of 10, 20, 50, 100, 200,
    500, 1000, and 3000 and above. If lower contours are needed, adjust 'contour_vals' kwarg.

    Contour_vals needs to start with zero and end with a higher value than the max in the data.
    Contour_vals needs to be a list of max length 9 including zero and max value.


Create a ratio plot.

    Ratio is a subclass of :class:`bowie.plotutils.baseplot.CreateSinglePlot`.

    Ratio creates a filled contour plot comparing snrs from two different data sets.
    Typically, it is used to compare sensitivty curves and/or varying binary parameters.
    It takes the snr of the first dataset and divides it by the snr from the second dataset.
    Additionally, a Loss/Gain contour is plotted. Loss/Gain contour is based on SNR_CUT
    but can be overridden with 'snr_contour_value' kwarg. A gain indicates
    the first dataset reaches the snr threshold while the second does not.
    A loss is the opposite.

    Attributes:
        comp1/comp2 (2D array of floats): Comparison and control datasets respectivley.


Create Horizon plots.

    Horizon is a subclass of :class:`bowie.plotutils.baseplot.CreateSinglePlot`.

    Horizon plots snr contour lines for a designated SNR value. The defaul is SNR_CUT,
    but can be overridden with `snr_contour_value`. Horizon can make as many
    curves as the user prefers and will plot a legend to label those curves.
    It can only contour one snr value.


    This class is designed to carry around the data for each plot as an attribute of self.

    Args:
        x_arr_list/y_arr_list/z_arr_list (list of 2D arrays of floats): List of gridded,
            2D datasets representing the x/y/z-values.


Read in the data from txt or hdf5.

    This class reads in data. The information is transferred to the read in methods
    that work for .txt, .csv, and .hdf5.

    Keyword Arguments:
        WORKING_DIRECTORY (str): Path to working directory.
        file_name (str): File name for output file.
        label (str): Label for column of data in file that will be the z value (SNR).
        xlims/ylims (len-2 list of floats): x/y min value followed by max value.
            Default is `lin` for linear. If log, the limits should be log of values.
        dx/dy (float): increments in x and y.
        xscale/yscale (string, optional): scaling for axes. Either 'log' or 'lin'.
            Default is `lin`.
        x_column_label/y_column_label (str, optional): Column label within the file for x and y.

    Attributes:
        file_type (str): File extension. Either `hdf5`, `txt`, or `csv`.
        xvals/yvals/zvals (2D array of floats): Values received from files.
        x_append_value/y_append_value/z_append_value (2D array of floats): The value to append
            to data lists. This can be log10 values for x/y if ``xcale/yscale == log10``.
            For z values, it will just be zvals.


Main class for SNR calculations.

    This class performs gravitational wave SNR calculations with a matched
    filtering approach. It can generate SNRs for single sources or arrays of sources.
    It can run in parallel or on a single processor.

    Args:
        ecc (bool, optional): If True, use the eccentric SNR calculator. If False,
            use PhenomDWaveforms. (For future usage.) Default is False.
        **kwargs (dict): kwargs to be added to ParallelContainer, PhenomDWaveforms, and
            SensitivityContainer.

    Keyworkd Arguments:
        signal_type (scalar or list of str, optional): Phase of snr.
            Options are 'all' for all phases;
            'ins' for inspiral; 'mrg' for merger; or 'rd' for ringdown. Default is 'all'.
        prefactor (float, optional): Factor to multiply snr (not snr^2) integral values by.
            Default is 1.0.

    Attributes:
        snr_function (obj): Function object representing the snr function to use.
            This is form future use with other snr calculations.
        phenomdwave (obj): :class:`gwsnrcalc.utils.pyphenomd.PhenomDWaveforms`
            object for storing initial kwargs and passing to snr function.
        Note: All kwargs are stored as attributes.
        Note: Attributes are inherited from inherited classes.


Sensitivity curve analysis

    This prepares the sensitivity side of the SNR calculation.
    It takes all the inputs and converts them to characterstic strain.

    Keyword Arguments:
        sensitivity_curves (scalar or list of str or single or list of lists, optional):
            String that starts the .txt file containing the sensitivity curve in
            folder 'noise_curves/' or list of ``[f_n, asd_n]``
            in terms of an amplitude spectral density. It can be a single one of these
            values or a list of these values. A folder string with absolute path to a sensitivity
            curve .txt file can also be input.
            Default is [`LPA`] (LISA Phase A).
        add_wd_noise (str or bool, optional): Options are `yes`, `no`, `True`, `False`,
            `Both`, True, or False. `yes`, `True`, or True
            will exclusively calculate with the wd noise.
            `no`, `False`, or False will exclusively calculate without the wd noise.
            `Both` will calculate with and without wd noise.
            Default is `Both`.
        wd_noise (str or list, optional): If string,
            read the wd noise from `noise_curves` folder or absolute path to file.
            If list, must be ``[f_n_wd, asd_n_wd]``.
            Default is Hils-Bender estimation (Bender & Hils 1997) by Hiscock et al. 2000.
        noise_type_in (str, optional): Type of noise curve passed in.
            Options are `ASD`, `PSD`, or `char_strain`.
            All sensitivity curves must have same noise type.
            Also, their amplitude column must have this same string as its label.
            Default is `ASD`.
        wd_noise_type_in (str, optional): Type of wd noise curve passed in.
            Options are `ASD`, `PSD`, or `char_strain`.
            Amplitude column must have this same string as its label.
            Default is `ASD`.

    Attributes:
        noise_interpolants (dict): Dictionary carrying scipy.interpolate.interp1d objects.
            These are the interpolations used to calculate the SNR.
        Note: All Keyword Arguments are added as attributes.


Generate phenomd waveforms

    PhenomDWaveforms is a class that takes binary parameters as inputs, and adds
    characteristic strain waveforms as attributes to self.

    Keyword Arguments:
        dist_type (str, optional): Which type of distance is used. Default is 'redshift'.
            This is stored as an attributed.
        num_points (int, optional): Number of points to use in the waveform.
            The frequency points are log-spaced. Default is 8192. This is stored as an attributed.

    Attributes:
        freqs (1D or 2D array of floats): Frequencies corresponding to the waveforms.
            Shape is (num binaries, num_points) if 2D.
            Shape is (num_points,) if 1D for one binary.
        hc (1D or 2D array of floats): Characteristic strain of the waveforms.
            Shape is (num binaries, num_points) if 2D.
            Shape is (num_points,) if 1D for one binary.
        fmrg: (scalar float or 1D array of floats): Merger frequency of each binary separating
            inspiral from merger phase. (0.014/M) Shape is (num binaries,) if more than one binary.
        fpeak: (scalar float or 1D array of floats): Peak frequency of each binary separating
            merger from ringdown phase. (0.014/M) Shape is (num binaries,) if more than one binary.
        z (float or 1D array of floats): Redshift equivalent of the z_or_dist given.
        dist (float or 1D array of floats): Luminosity distance equivalent of the z_or_dist given.
        remove_axis (bool): Remove axis based on if it is one or more than one binary.
        length (int): Number of binaries.
        Note: All args from :meth:`gwsnrcalc.utils.pyphenomd.PhenomDWaveforms.__call__`
                are stored as attributes.
        Note: All kwargs from above are stored as attributes.

    Raises:
        ValueError: dist_type is not one of the three options.


Generate eccentric inspiral waveforms

    EccentricBinaries is a class that takes binary parameters as inputs, and adds
    characteristic strain waveforms as attributes to self.

    Keyword Arguments:
        dist_type (str, optional): Which type of distance is used. Default is 'redshift'.
            This is stored as an attributed.
        num_points (int, optional): Number of points to use in the waveform.
            The frequency points are log-spaced. Default is 8192. This is stored as an attributed.
        initial_cond_type (str, optional): Initial value representing the start of evolution.
            Options are `time`, `frequency`, or `separation`. Default is time.
        n_max (int, optional): Maximum number of higher order harmonics to analyze in the SNR.
            Default is 100.

    Attributes:
        freqs (1D or 2D array of floats): Frequencies corresponding to the waveforms.
            Shape is (num binaries, num_points) if 2D.
            Shape is (num_points,) if 1D for one binary.
        hc (1D or 2D array of floats): Characteristic strain of the waveforms.
            Shape is (num binaries, num_points) if 2D.
            Shape is (num_points,) if 1D for one binary.
        z (float or 1D array of floats): Redshift equivalent of the z_or_dist given.
        dist (float or 1D array of floats): Luminosity distance equivalent of the z_or_dist given.
        f0 (float, 1D array of floats, or None): Initial orbital frequencies.
            If ``initial_cond_type == 'frequency'``, initial values are stored here. Optional.
            Default is None.
        a0 (float, 1D array of floats, or None): Initial orbital semi-major axes.
            If ``initial_cond_type == 'separation'``, initial values are stored here. Optional.
            Default is None.
        t_start (float, 1D array of floats, or None): Initial times before merger.
            If ``initial_cond_type == 'time'``, initial values are stored here. Optional.
            Default is None.
        e_vals (2D array of floats): Eccentricity values over time.
        a_vals (2D array of floats): Semi-major axis values over time.
        t_vals (2D array of floats): Time values corresponding to e_vals and a_vals.
        freqs_orb (2D array of floats): Orbital frequencies over time.
        n (2D array of ints): Radiation mode values.
        ef (1D array of floats): Final eccentricity for each binary.
        remove_axis (bool): Remove axis based on if it is one or more than one binary.
        length (int): Number of binaries.
        Note: All args from :meth:`gwsnrcalc.utils.pyphenomd.PhenomDWaveforms.__call__`
                are stored as attributes.
        Note: All kwargs from above are stored as attributes.

    Raises:
        ValueError: dist_type is not one of the three options.
        ValueError: initial_cond_type is not one of the three options.


Run SNR calculation in parallel.

    Calculate in parallel using multiprocessing module.
    This can be easily adaptable to other parallel functions.

    Keyword Arguments:
        length (int): Number of binaries to process.
        num_processors (int or None, optional): If None, run on single processor.
            If -1, use ```multiprocessing.cpu_count()`` to determine cpus to use.
            Otherwise, this is the number of processors to use. Default is -1.
        num_splits (int, optional): Number of binaries to run for each process. Default is 1000.
        verbose (int, optional): Notify each time ``verbose`` processes finish.
            If -1, then no notification. Default is -1.
        timer (bool, optional): If True, time the parallel process. Default is False.

    Attributes:
        args (list of tuple): List of arguments to passes to the parallel function.
        Note: All kwargs above are stored as attributes.


    Class designed for reading out files in .txt files or hdf5 compressed files.

    FileReadOut will export all of the contour data to a file and file type
    of the user's choice. It will include all supplemental information for reference
    back to the file at a later point in time.

    Args:
        xvals/yvals (1D array): The x/y values for the contour data.
        output_dict (dict): The output of the SNR calculations. This is the dictionary
            returned by ``gwsnrcalc.gw_snr_calculator.snr``.
        **kwargs (dict): Combination of the `general`, `output_info`, and `generate_info`
            dictionaries from pid. These kwargs are stored as attributes.

    Keyword Arguments:
        output_file_name (str): Path and name of output file in relation to working directory.
        x_col_name (str, optional): Column label for x column in output file. Default is `x`.
        y_col_name (str, optional): Column label for y column in output file. Default is `y`.
        added_note (str, optional): Add note to output file. Default is ''.

    Attributes:
        output_file_type (str): Type of file. Must be `hdf5` or `txt`.
        Note: All args above are added as attributes.
        Note: All kwargs above are added as attributes.
        Note: kwargs from :class:`gwsnrcalc.genconutils.genprocess.GenProcess`
            are also included for readout information. These are stored as attributes.


Holds all of the attributes related to the generate_info dictionary.

    This class is used to store the information when methods from Generate class
    are called by the MainContainer class.

    Attributes:
        Note: Attributes represent the kwargs from
            :class:`gwsnrcalc.genconutils.genprocess.GenProcess`.


 Generate contains the methods inherited by MainContainer.

    These methods are used by MainContainer class to add generation specific
    information to the generate_info dict.

    All attributes are appended to the GenerateContainer class.
    The GenerateContainer class is contained in the generate_info attribute
    in the MainContainer class.


Holds all of the attributes related to the sensitivity_input dictionary.

    This class is used to store the information when methods from Input class
    are called by the MainContainer class.

    Attributes:
        Note: Attributes represent the kwargs from
            :class:`gwsnrcalc.utils.sensitivity.SensitivityContainer`.


 Input contains the methods inherited by MainContainer.

    These methods are used by MainContainer class to add noise curve
    information.

    All attributes are appended to the SensitivityInputContainer class.
    The SensitivityInputContainer class is contained in the sensitivty_input attribute
    in the MainContainer class.


Holds all of the attributes related to the output_info dictionary.

    This class is used to store the information when methods from Output class
    are called by the MainContainer class.

    Attributes:
        Note: Attributes represent the kwargs from
            :class:`gwsnrcalc.genconutils.readout.FileReadOut`.


 Output contains the methods inherited by MainContainer.

    These methods are used by MainContainer class to add
    information pertaining to the output of the grid creation.

    All attributes are appended to the OutputContainer class.
    The OutputContainer class is contained in the output_info attribute
    in the SinglePlot class.


Holds all of the attributes related to the parallel_input dictionary.

    This class is used to store the information when methods from ParallelInput class
    are called by the MainContainer class.

    Attributes:
        Note: Attributes represent the kwargs from
            :class:`gwsnrcalc.utils.parallel.ParallelContainer`.


General contains the methods inherited by MainContainer.

    These methods are used by MainContainer class to add information that applies
    to parallel generation. This information is stored in a ParallelInputContainer
    class object.


Holds all of the attributes related to the snr_input dictionary.

    This class is used to store the information when methods from SNRInput class
    are called by the MainContainer class.

    Attributes:
        Note: Attributes represent the kwargs from :class:`gwsnrcalc.gw_snr_calculator.SNR`.


 General contains the methods inherited by MainContainer.

    These methods are used by MainContainer class to add information that applies
    to all plots or the figure as a whole. Many of its settings pertaining to plots
    can be overriden with methods in SinglePlot.


Holds all of the attributes related to the general dictionary.

    This class is used to store the information when methods
    are called by the MainContainer class.

    Attributes:
        WORKING_DIRECTORY (str, optional): Working directory for file export and retrieval.
            Default is ``'.'``.


Main class for creating input dictionary to ``generate_contour_data.py``.

    This class creates a pythonic way to add information to the input dictionary
    to ``generate_contour_data.py``. It creates and can read out this dictionary.

    MainContainer inherits methods from Generate, SensitivityInput, SNRInput,
    ParallelInput, and Output classes so that it can
    add respective dictionary information to MainContainer class.

    Args:
        print_input (bool, optional): If True, print the dictionary created by MainContainer
            class after it is completed.

    Attributes:
        general (obj): GeneralContainer class for holding information for general dictionary.
        generate_info (obj): GenerateContainer class for holding information
            for generate_info dictionary.
        sensitivity_input (obj): InputContainer class for holding information for
            sensitivty_input dictionary.
        snr_input (obj): SNRInputContainer class for holding information for
            snr_input dictionary.
        parallel_input (obj): ParallelInputContainer class for holding information for
            parallel_input dictionary.
        output_info (obj): OutputContainer class for holding information for output_info dictionary.
        print_input (bool, optional): If True, print the dictionary created by MainContainer
            class after it is completed.


Direct the contour generation process.

    Class that carries the input information and directs the program to accomplish generation tasks.

    Args:
        **kwargs (dict): Combination of all input dictionaries to have their information
            stored as attributes.

    Keyword Arguments:
        xscale/yscale (str): `lin` for linear scale or `log` for log10 scaling.
        xlow/xhigh/ylow/yhigh (float): Low/high value for x/y.
        num_x/num_y (int): Number of x/y points in contour.
        xval_name/yval_name (str): Name of the x/y quantity.
        xval_unit/yval_unit(str): Units for x/y quantity.
        parameters: All the parameters (args) for the specific waveform generator.
            For both circular and eccentric, this will include start_time, m1, m2,
            redshift (or luminosity_distance or comoving_distance). For circular with will
            also include spin_1, spin_2, and end_time. For eccentric this will
            additionally include eccentricity and observation time.
        sensitivty_input (dict): kwargs for
            :class:`gwsnrcalc.utils.sensitivity.SensitivityContainer`.
        snr_input (dict): kwargs for :class:`gwsnrcalc.gw_snr_calculator.SNR`.

    Attributes:
        final_dict (dict): Dictionary with SNR results.
        Note: All kwargs above are added as attributes.


Tests for resampling influence function.


    Main class containing the ensemble of simulations
    (rows are timesteps)


Exceptions are documented in the same way as classes.

    The __init__ method may be documented in either the class level
    docstring, or as a docstring on the __init__ method itself.

    Either form is acceptable, but the two should not be mixed. Choose one
    convention to document the __init__ method and be consistent with it.

    Note:
        Do not include the `self` parameter in the ``Args`` section.

    Args:
        msg (str): Human readable string describing the exception.
        code (Optional[int]): Error code.

    Attributes:
        msg (str): Human readable string describing the exception.
        code (int): Exception error code.


The summary line for a class docstring should fit on one line.

    If the class has public attributes, they may be documented here
    in an ``Attributes`` section and follow the same formatting as a
    function's ``Args`` section. Alternatively, attributes may be documented
    inline with the attribute's declaration (see __init__ method below).

    Properties created with the ``@property`` decorator should be documented
    in the property's getter method.

    Attribute and property types -- if given -- should be specified according
    to `PEP 484`_, though `PEP 484`_ conformance isn't required or enforced.

    Attributes:
        attr1 (str): Description of `attr1`.
        attr2 (Optional[int]): Description of `attr2`.

    .. _PEP 484:
       https://www.python.org/dev/peps/pep-0484/


Indexer that allows fast range queries with geographical coordinates


Provide data for different reference ellipsoids.

    The following models are covered:

        * SphericalEarth     (radius set as constants.earth_radius)
        * WGS84
        * SphericalVenus     (radius same as used in ARTS)
        * SphericalMars      (radius same as used in ARTS)
        * EllipsoidMars
        * SphericalJupiter   (radius same as used in ARTS)

    Examples:
        >>> e = ellipsoidmodels()

    .. Ported from atmlab. Original author: Patrick Eriksson


A mapping object for environment variables.

    See module docstring of :mod:`typhon.environment` for more information.


Helper class for IntervalTree.


Tree to implement fast 1-dimensional interval searches.

    Based on the description in Wikipedia
    (https://en.wikipedia.org/wiki/Interval_tree#Centered_interval_tree)
    and the GitHub repository by tylerkahn
    (https://github.com/tylerkahn/intervaltree-python).

    Examples:
        Check 1000 intervals on 1000 other intervals:

    .. code-block:: python

        import numpy as np
        from typhon.trees import IntervalTree

        intervals = np.asarray([np.arange(1000)-0.5, np.arange(1000)+0.5]).T
        tree = IntervalTree(intervals)
        query_intervals = [[i-1, i+1] for i in range(1000)]
        results = tree.query(query_intervals)


    Interface to version 2.1 of SRTM30 digital elevation model.

    The data set has a resolution of about 1 km and covers all land masses
    except Antarctica.


Handle matplotlib stylesheets shipped with typhon.

    This handler serves several purposes:

        1. Return the absolute path to a typhon stylesheet:

        >>> from typhon.plots import styles
        >>> styles.get('typhon')
        '/PATH/typhon/typhon/plots/stylelib/typhon.mplstyle'

        or for backwards compatibility:

        >>> styles('typhon')
        '/PATH/typhon/typhon/plots/stylelib/typhon.mplstyle'

        2. Use style settings from a typhon stylesheet:

        >>> styles.use('typhon')

        You can also get/use several styles at a time:

        >>> styles.use(['typhon', 'typhon-dark'])

    Parameters:
        name (str): Style name.

    Returns:
        str: Absolute path to stylesheet.


Creates logarithmic hectopascal labels for pascal input.

    This class can be used to create axis labels on the hectopascal scale for
    values plotted in pascals. It is handy in combination with plotting in
    logscale.

    Examples:

    .. plot::
        :include-source:

        import numpy as np
        import matplotlib.pyplot as plt
        import typhon
        from typhon.plots import (set_yaxis_formatter, HectoPascalLogFormatter)

        p = typhon.math.nlogspace(1000e2, 0.1e2, 50)  # pressue in Pa

        fig, ax = plt.subplots()
        ax.semilogy(np.exp(p / p[0]), p)
        ax.invert_yaxis()
        set_yaxis_formatter(typhon.plots.HectoPascalLogFormatter())

        plt.show()

    See also:
            :func:`~typhon.plots.HectoPascalFormatter`
                Creates hectopascal labels for pascal input.


ASTER L1B image object.


Should be raised if someone runs a non-trained retrieval product


Retrieval that can be trained with data and stored to json files

    This is basically a wrapper around the scikit-learn estimator and trainer
    classes and makes it possible to save the trained models as json file.

    To save this object to a json file, the additional package json_tricks is
    required.


r"""
    Quantile Regression Neural Network (QRNN)

    This class provides a high-level implementation of  quantile regression
    neural networks. It can be used to estimate quantiles of the posterior
    distribution of remote sensing retrievals.

    The :class:`QRNN`` class uses an arbitrary neural network model, that is
    trained to minimize the quantile loss function

    .. math::
            \mathcal{L}_\tau(y_\tau, y_{true}) =
            \begin{cases} (1 - \tau)|y_\tau - y_{true}| & \text{ if } y_\tau < y_\text{true} \\
            \tau |y_\tau - y_\text{true}| & \text{ otherwise, }\end{cases}

    where :math:`x_\text{true}` is the true value of the retrieval quantity
    and and :math:`x_\tau` is the predicted quantile. The neural network
    has one output neuron for each quantile to estimate.

    The QRNN class provides a generic QRNN implementation in the sense that it
    does not assume a fixed neural network architecture or implementation.
    Instead, this functionality is off-loaded to a model object, which can be
    an arbitrary regression network such as a fully-connected or a
    convolutional network. A range of different models are provided in the
    typhon.retrieval.qrnn.models module. The :class:`QRNN`` class just
    implements high-level operation on the QRNN output while training and
    prediction are delegated to the model object. For details on the respective
    implementation refer to the documentation of the corresponding model class.

    .. note::

      For the QRNN implementation :math:`x` is used to denote the input
      vector and :math:`y` to denote the output. While this is opposed
      to inverse problem notation typically used for retrievals, it is
      in line with machine learning notation and felt more natural for
      the implementation. If this annoys you, I am sorry.

    Attributes:
        backend(``str``):
            The name of the backend used for the neural network model.
        quantiles (numpy.array):
            The 1D-array containing the quantiles :math:`\tau \in [0, 1]`
            that the network learns to predict.
        model:
            The neural network regression model used to predict the quantiles.


r"""
    The quantile loss function

    This function object implements the quantile loss defined as

    .. math::

        \mathcal{L}(y_\text{pred}, y_\text{true}) =
        \begin{cases}
        \tau \cdot |y_\text{pred} - y_\text{true}| & , y_\text{pred} < y_\text{true} \\
        (1 - \tau) \cdot |y_\text{pred} - y_\text{true}| & , \text{otherwise}
        \end{cases}

    as a training criterion for the training of neural networks. The loss criterion
    expects a vector :math:`\mathbf{y}_\tau` of predicted quantiles and the observed
    value :math:`y`. The loss for a single training sample is computed by summing the losses
    corresponding to each quantiles. The loss for a batch of training samples is
    computed by taking the mean over all samples in the batch.


    Quantile regression neural network (QRNN)

    This class implements QRNNs as a fully-connected network with
    a given number of layers.


    Wrapper class for the quantile error loss function. A class is used here
    to allow the implementation of a custom `__repr` function, so that the
    loss function object can be easily loaded using `keras.model.load`.

    Attributes:

        quantiles: List of quantiles that should be estimated with
                   this loss function.


    This Keras sample generator takes the noise-free training data
    and adds independent Gaussian noise to each of the components
    of the input.

    Attributes:

        x_train: The training input, i.e. the brightness temperatures
                 measured by the satellite.
        y_train: The training output, i.e. the value of the retrieval
                 quantity.
        x_mean: A vector containing the mean of each input component.
        x_sigma: A vector containing the standard deviation of each
                 component.
        batch_size: The size of a training batch.


    This Keras sample generator is similar to the training generator
    only that it returns the whole validation set and doesn't perform
    any randomization.

    Attributes:

        x_val: The validation input, i.e. the brightness temperatures
                 measured by the satellite.
        y_val: The validation output, i.e. the value of the retrieval
                 quantity.
        x_mean: A vector containing the mean of each input component.
        x_sigma: A vector containing the standard deviation of each
                 component.


    The LRDecay class implements the Keras callback interface and reduces
    the learning rate according to validation loss reduction.

    Attributes:

        lr_decay: The factor c > 1.0 by which the learning rate is
                  reduced.
        lr_minimum: The training is stopped when this learning rate
                    is reached.
        convergence_steps: The number of epochs without validation loss
                           reduction required to reduce the learning rate.


r"""
    Quantile Regression Neural Network (QRNN)

    This class implements quantile regression neural networks and can be used
    to estimate quantiles of the posterior distribution of remote sensing
    retrievals.

    Internally, the QRNN uses a feed-forward neural network that is trained
    to minimize the quantile loss function

    .. math::
            \mathcal{L}_\tau(y_\tau, y_{true}) =
            \begin{cases} (1 - \tau)|y_\tau - y_{true}| & \text{ if } y_\tau < y_\text{true} \\
            \tau |y_\tau - y_\text{true}| & \text{ otherwise, }\end{cases}

    where :math:`x_\text{true}` is the expected value of the retrieval quantity
    and and :math:`x_\tau` is the predicted quantile. The neural network
    has one output neuron for each quantile to estimate.

    For the training, this implementation provides custom data generators that
    can be used to add Gaussian noise to the training data as well as adversarial
    training using the fast gradient sign method.

    This implementation also provides functionality to use an ensemble of networks
    instead of just a single network to predict the quantiles.

    .. note:: For the QRNN I am using :math:`x` to denote the input vector and
              :math:`y` to denote the output. While this is opposed to typical
              inverse problem notation, it is inline with machine learning
              notation and felt more natural for the implementation. If this
              annoys you, I am sorry. But the other way round it would have
              annoyed other people and in particular me.

    Attributes:

        input_dim (int):
            The input dimension of the neural network, i.e. the dimension of the
            measurement vector.

        quantiles (numpy.array):
            The 1D-array containing the quantiles :math:`\tau \in [0, 1]` that the
            network learns to predict.

        depth (int):
            The number layers in the network excluding the input layer.

        width (int):
            The width of the hidden layers in the network.

        activation (str):
            The name of the activation functions to use in the hidden layers
            of the network.

        models (list of keras.models.Sequential):
            The ensemble of Keras neural networks used for the quantile regression
            neural network.


Keras data loader that batches a given dataset of numpy arryas.


    This Keras sample generator takes a generator for noise-free training data
    and adds independent Gaussian noise to each of the components of the input.

    Attributes:
        training_data: Data generator providing the data
        sigma_noise: A vector containing the standard deviation of each
                 component.


    This Keras sample generator takes the noise-free training data
    and adds independent Gaussian noise to each of the components
    of the input.

    Attributes:
        training_data: Training generator to use to generate the input
            data
        input_gradients: Keras function to compute the gradients of the
            network
        eps: The perturbation factor.


r"""
    Base class for Keras models.

    This base class provides generic utility function for the training, saving
    and evaluation of Keras models.

    Attributes:
        input_dimensions (int): The input dimension of the neural network, i.e.
            the dimension of the measurement vector.
        quantiles (numpy.array): The 1D-array containing the quantiles
            :math:`\tau \in [0, 1]` that the network learns to predict.

        depth (int):
            The number layers in the network excluding the input layer.

        width (int):
            The width of the hidden layers in the network.

        activation (str):
            The name of the activation functions to use in the hidden layers
            of the network.

        models (list of keras.models.Sequential):
            The ensemble of Keras neural networks used for the quantile regression
            neural network.


Keras implementation of fully-connected networks.


    Basic building block of a UNet. Consists of a convolutional
    layer followed by an activation layers and an optional batch
    norm layer.

    Args:
        features_in(:code:`int`): Number of features of input
        features_out(:code:`int`): Raw number of output features of the
            layer not including skip connections.
        batch_norm(:code:`bool`): Whether or not to include a batch norm
            layer.
        kernel_size(:code:`int`): Kernel size to use for the conv. layer.
        activation(:code:`activation`): Activation to use after conv. layer.
        skip_connection(:code:`bool`): Whether to include skip connections, i.e.
            to include input in layer output.


A block bundles a set of layers.


A downsampling block reduces the input resolution by applying max-pooling.


An upsampling block increases the input resolution by transposed convolution.


Pytorch implementation of the UNet architecture for image segmentation.


Batches an un-batched dataset.


Pytorch implementation of a fully-connected QRNN model.


Retrieval of IWP from passive radiometers

    Examples:
    .. code-block:: python

        import pandas as pd
        from typhon.retrieval import SPAREICE

        # Create a SPARE-ICE object with the standard weights
        spareice = SPAREICE()

        # Print the required input fields
        print(spareice.inputs)

        # If you want to know the input fields for the each component, IWP
        # regressor and ice cloud classifier, you can get them like this:
        print(spareice.iwp.inputs)  # Inputs from IWP regressor
        print(spareice.ice_cloud.inputs)  # Inputs from ice cloud classifier

        # If you have yur own input data, you can use :meth:`retrieve` to run
        # SPARE-ICE on it.
        data = pd.DataFrame(...)
        retrieved = spareice.retrieve(data)

        # If your data directly comes from collocations between MHS and AVHRR,
        # you can use ::meth:`convert_collocated_data` to make it SPARE-ICE
        # compatible.
        collocations = Collocator().collocate(mhs_data, avhrr_data, ...)
        standardized_data = self.standardize_collocations(collocations)
        retrieved = spareice.retrieve(standardized_data)


r"""
    Bayesian Monte Carlo Integration

    This class implements methods for solving Bayesian inverse problems using
    Monte Carlo integration. The method uses a data base of atmospheric states
    :math:`x_i` and corresponding observations :math:`\mathbf{y}_i`, which are
    used to compute integrals of the posterior distribution by means of
    importance sampling:

    .. math::

        \int_a^b f(x') p(x' | \mathbf{y}) \: dx' \approx
        \sum_{a \leq x_i \leq b} \frac{w_i(\mathbf{y}) f(x)}
        {\sum_j w_j(\mathbf{y})}.

    The method assumes that measurement uncertainties can be described by a
    multivariate Gaussian distribution with covariance matrix $\mathbf{S}_o$,
    so that the weights :math:`w_i(\mathbf{y})` are given by

    .. math::
        w_i(\mathbf{y}) = \exp
        \{ -\frac{1}{2} (\mathbf{y} - \mathbf{y}_i)^T
        \mathbf{S}_o^{-1} (\mathbf{y} - \mathbf{y}_i) \}.

    The measurements in the database :code:`y` is assumed to be given as an
    array of shape :code:`(n, m)`, where n is the number of cases in the
    database. Currently only scalar retrievals are supported, which means that
    :code:`x` is assumed to a n-element vector containing the retrieval
    quantities corresponding to the observations in :math:`\mathbf{y}`.

    Attributes

        x: numpy.array, shape = (n,)
           The retrieval quantity corresponding to the atmospheric states represented
           in the data base.

        y: numpy.array, shape = (n, m)
           The measured or simulated brightness temperatures corresponding to the
           atmospheric states represented in the data base.

        s_o: numpy.array, shape = (m, m)
           The covariance matrix describing the measurement uncertainty.

        n: int
           The number of entries in the retrieval database.

        m: int
           The number of channels in a single measurement :math:`\mathbf{y}_i`.

        pc1: numpy.array, shape = (m, )
            The eigenvector corresponding to the smallest eigenvalue of the
            observation uncertainty covariance matrix. Along this vector the
            entries in the database will be ordered, which can be used to
            accelerate the retrieval.

        pc1_e: float
            The smallest eigenvalue of the observation uncertainty covariance
            matrix.

        pc1_proj: numpy.array, shape (n, )
            The projections of the measurements in `y` onto `pc1` along which
            the database entries are ordered.


Random walk jumping function for MCMC.


    The MCMC class represents an ongoing MCMC simulation. An MCMC object can be
    used to run a given number of MC steps, test the results for convergence
    and perform further calculations if necessary.


Testing the spectroscopy functions.


Testing the geographical functions.


Testing the GeoIndex functions.


Testing the nonlte functions.


Testing the environment handler.


Testing the geodetic functions.


Testing the atmosphere functions.


Testing the typhon.physics.em functions.


Testing the typhon.physics.thermodynamics functions.


Testing common mathematical functions.


Testing array related mathematical functions.


Testing the cm functions.


Testing the plot functions.


Testing the collocation functions.


Testing the fileset methods.


Test filesystem-NetCDF file handler.


Testing the latex functions.


Testing the typhon.utils functions.


Mixing for frequency/wavelength/wavenumber neutrality

    Best to use pint ureg quantities at all times.


Respresents a spectral response function

    TODO: representation of uncertainties


Like xarray.DataArray, but transfers units


Provide a simple time profiling utility

    Parameters:
        verbose (bool): Print measured duration after stopping the timer.
        info (str): Allows to add additional information to output.
            The given string is printed before the measured time.
            If `None`, default information is added depending on the use case.

    Returns:
        datetime.timedelta: The duration between start and end time.

    Examples:
        Timer in with statement:

        >>> import time
        >>> with Timer():
        ...     time.sleep(1)
        elapsed time: 0:00:01.003186

        Timer as object (allows to store :class:`datetime.timedelta`):

        >>> import time
        >>> t = Timer().start()
        >>> time.sleep(1)
        >>> dt = t.stop()
        elapsed time: 0:00:01.004756

        As function decorator:

        >>> @Timer()
        ... def own_function(s):
        ...     import time
        ...     time.sleep(s)
        >>> own_function(1)
        own_function: 0:00:01.004667

        Use it in format strings:

        >>> from typhon.utils import Timer
        >>> timer = Timer().start()
        >>> print(f"{timer} elapsed")
        0:00:00.000111 hours elapsed


Should be raised if the files of a fileset do not have the same internal
    structure but it is required.


Should be raised if no files were found by the :meth:`find`
    method.


Should be raised if no file handler is specified in a fileset object but
    a handler is required.


Should be raised if a placeholder was found that cannot be filled.


Should be raised if a placeholder was found that was not defined before.


Should be raised if the regex of a placeholder is broken.


Should be raised if two filesets could not be aligned to each other.


Provide methods to handle a set of multiple files

    For more examples and an user guide, look at this tutorial_.

    .. _tutorial: http://radiativetransfer.org/misc/typhon/doc-trunk/tutorials/fileset.html

    Examples:

        FileSet with multiple files:

        .. code-block:: python

            from typhon.files import FileSet

            # Define a fileset consisting of multiple files:
            files = FileSet(
                path="/dir/{year}/{month}/{day}/{hour}{minute}{second}.nc",
                name="TestData",
                # If the time coverage of the data cannot be retrieved from the
                # filename, you should set this to "handler" and giving a file
                # handler to this object:
                info_via="filename"
            )

            # Find some files of the fileset:
            for file in files.find("2017-01-01", "2017-01-02"):
                # Should print the path of the file and its time coverage:
                print(file)

        FileSet with a single file:

        .. code-block:: python

            # Define a fileset consisting of a single file:
            file = FileSet(
                # Simply use the path without placeholders:
                path="/path/to/file.nc",
                name="TestData2",
                # The time coverage of the data cannot be retrieved from the
                # filename (because there are no placeholders). You can use the
                # file handler get_info() method with info_via="handler" or you
                # can define the time coverage here directly:
                time_coverage=("2007-01-01 13:00:00", "2007-01-14 13:00:00")
            )

        FileSet to open MHS files:

        .. code-block:: python

            from typhon.files import FileSet, MHS_HDF

            # Define a fileset consisting of multiple files:
            files = FileSet(
                path="/dir/{year}/{month}/{day}/{hour}{minute}{second}.nc",
                name="MHS",
                handler=MHS_HDF(),
            )

            # Find some files of the fileset:
            for file in files.find("2017-01-01", "2017-01-02"):
                # Should print the path of the file and its time coverage:
                print(file)

    References:
        The FileSet class is inspired by the implemented dataset classes in
        atmlab_ developed by Gerrit Holl.

        .. _atmlab: http://www.radiativetransfer.org/tools/


Base file handler class.

    This can be used alone or with the :class:`~typhon.files.fileset.FileSet`
    classes. You can either initialize specific *reader* ,*info* or *writer*
    functions or you can inherit from this class and override its methods. If
    you need a very specialised and reusable file handler class, you should
    consider following the second approach.


Container of information about a file (time coverage, etc.)

    This is a simple object that holds the path and name, time coverage and
    further attributes of a file. It fulfills the os.PathLike protocol, i.e.
    you can use it as filename argument for the most python functions.

    See this Example:

    .. code-block:: python

        # Initialise a FileInfo object that points to a file
        file_info = FileInfo(
            path="path/to/a/file.txt",
            # The time coverage of the file (needed by Dataset classes)
            times=[datetime(2018, 1, 1), datetime(2018, 1, 10)],
            # Additional attributes:
            attr={},
        )

        with open(file_info) as file:
            ...

        # If you need to access the path or other attributes directly, you can
        # do it like this:
        file_info.path   # "path/to/a/file.txt"
        file_info.times  # [datetime(2018, 1, 1), datetime(2018, 1, 10)]
        file_info.attr   # {}


File handler that can read / write data from / to a CSV file

    A CSV file is file containing data separated by commas (or by any other
    delimiter).


File handler that can read data from a HDF4 file


File handler for SEVIRI level 1.5 HDF files


File handler that can load / store xarray.Dataset from / to NetCDF4

    This file handler can also handle pseudo groups in :class:`xarray.Dataset`
    objects.


File handler for reading NetCDF files via alternate file systems.

    Alternative to the NetCDF file handler for reading files from
    alternative file systems, such as remote file systemss.  Does not
    support writing or multi-group files.

    Usage example with fileset::

        fs = FileSet(
                path=(
                    "noaa-goes16/GLM-L2-LCFA/{year}/{doy}/{hour}/"
                    "OR_GLM-L2-LCFA_G16_s{year}{doy}{hour}{minute}{second}*_"
                    "e{end_year}{end_doy}{end_hour}{end_minute}{end_second}*_c*.nc"),
                fs=s3fs.S3FileSystem(anon=True),
                handler=FSNetCDF())

        finf = fs.find_closest(datetime.datetime(2021, 11, 10, 10))
        fs.read(finf)


File handler that can save matplotlib.figure objects to a file.

    This is a specialised file handler object that can just store
    matplotlib.figure objects. It cannot read from a file nor get the time
    coverage from one. This is designed for having a simple plot dataset as
    output.


Base class for handling TOVS satellite data converted with AAPP tools


File handler for MHS level 1C HDF files


File handler for AVHRR GAC level 1C HDF files


File handler for TROPOMI data using Satpy reader


File handler for CloudSat data in HDF4 files.


File handler that can read data from HOAPS NetCDF4 files.

    This object handles HOAPS V3.3 NetCDF4 files such as they are
    compatible with :mod:`typhon.collocations`, i.e.:

    * convert the content of the *time* variable to numpydtetime64 objects.

    Examples:

        Draw a world map with all measurements of OceanRAIN:

        .. :code-block:: python3

            from typhon.files import FileSet, HOAPS

            hoaps = FileSet(
                name="HOAPS",
                path=".../HOAPS_v3.3/{year}-{month}/hoaps-s.f16.{year}-{month}-{day}.nc",
                handler=HOAPS(),
                # This extracts the field *asst*:
                read_args={
                    "fields": ["asst"],
                },
                # The path of HOAPS files does not provide the end of the
                # file's time coverage. Hence, we set it here explicitly:
                time_coverage="1 day",
            )

            print(hoaps["2013"])


Wrapper for SatPy readers

    SatPy provides many readers for different satellite files. With this
    simple wrapper class, you can use them with typhon's FileSet without
    requiring any extra code!

    Warnings:
        At the moment, this wrapper works for retrieving fields with the
        same resolution only. Latitudes and longitudes are not retrieved.


File handler that can read data from OceanRAIN NetCDF4 files.

    This object handles OceanRAIN V1.0 NetCDF4 files such as they are
    compatible with :mod:`typhon.collocations`, i.e.:

    * rename *latitude* and *longitude* field to *lat* and *lon*.
    * convert the content of the *time* variable to numpydtetime64 objects.

    Examples:

        Draw a world map with all measurements of OceanRAIN:

        .. :code-block:: python3

            from typhon.files import FileSet, OceanRAIN
            from typhon.plots import worldmap

            # Create a Dataset object that points to the files:
            ocean_rain = FileSet(
                "OceanRAIN_1.0/OceanRAIN__W__{ship}_{ship_id}__UHAM-ICDC__v1_0.nc",
                handler=OceanRAIN(),
                info_via="both",
            )

            # Create a figure:
            fig = plt.figure(figsize=(12, 12))
            ax = None

            # This iterates through all files from OceanRAIN and plots them:
            for file, data in ocean_rain.icollect(return_info=True):
                label = f"{file.attr['ship']} ({data['lat'].size} mins)"

                # We only plot every 1000th point to draw the worldmap faster:
                ax, plot = worldmap(
                    data["lat"][::1000], data["lon"][::1000], ax=ax,
                    s=6, label=label, background=True
                )

            # Add a nice legend
            handles, labels = ax.get_legend_handles_labels()
            ax.legend(
                handles, labels, bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                ncol=2, borderaxespad=0., #mode="expand",
            )
            fig.show()


    From a specific file, read followings;
    Transition frequency
    number of energy levels
    energy levels
    degeneracies
    Einstein's A coeff
    transition tag (upper and lower level for each transition)


Outlier filter based on Median Absolute Deviation


Generic, abstract class for any kind of filtering.

    Implementations of this class are intended to be used between and
    after each orbit file is read by Dataset.read_period.  One important
    implementation for this class are the various OverlapFilter
    implementations, that make sure overlaps are removed.  This can either
    be done after each orbit or when all orbits have been read.

    Different filters may need different meta-information that needs to be
    provided by specific Dataset._read implementations.  For example, the
    FirstlineDBFilter needs a header name (or the entire header from which
    to extract this).  Each filterer can state what keyword arguments need
    to be passed on to the reading routine using the args_to_reader
    attribute.

    Moments in filtering that this class takes is responsible for:

    - Before the first orbit is read: .reset()
    - After each orbit is read. .filter(...)
    - After the last orbit is read: .finalise(...)

    You can also use this class for validation, i.e. to check that data
    are correct and if they aren't, raise an exception, if they are,
    return data as-is.


Throw out bad (masked) times.


Force scanlines to be in the proper sequence without duplicates

    This is for handling time sequence and duplicate issues within a
    single orbit file.  The two have to be in one filter because the
    application of the latter relies on the application of the first.
    I suppose one could conceivably want to remove time sequence problems
    but keep duplicate scanlines.


Apply HIRS flags and raise error in case of failure


Apply masking based on calibration count filter for HIRS


Apply masking to PRT counts when they are outliers


Implementations to feed into firstline filtering

    This is used in tovs HIRS reading routine.


Do not filter firstlines at all


Choose best between overlaps.

    Currently works only for HIRS.


Functionality in common with all ATOVS.

    Designed as mixin.


Read early HIRS such as documented in POD guide.

    Methods are mostly as for HIRS class.


Sole implementation of HIRSPOD


Read IASI from EUMETSAT EPS L1C

    This class depends on the Common Data Access Toolbox (CODA).

    http://stcorp.nl/coda/

    Reading data requires that in TYPHONRC, the variables 'tmpdir' and
    'tmpdirb' are set in [main].


Mixin for any TOVS collocated dataset.  Different because of scanlines.

    Should be mixed in before Dataset


HIRS-HIRS collocations from Brockmann Consult

    A.k.a. MMD05


Superclass for any datafile problems

    Upon reading a large amounts of data, some files will contain
    problems.  When processing a year of data, we don't want to fail
    entirely when one orbit file fails.  But if there is a real bug
    somewhere, we probably do want to fail.  Therefore, the typhon dataset
    framework is optionally resilient to datafile related errors, but only
    if those derive from DataFileError.

    Therefore, users implementing their own reading routine may wish to
    catch errors arising from corrupted data, and raise an exception
    derived from DataFileError instead.  That way, typhon knows that a
    problem is due to corrupted data and not due to a bug.


Raised when the requested information cannot be obtained from the file

    See DataFileError for more information.


Raised when data is not how it should be.

    See DataFileError for more information.


Represents a dataset.

    This is an abstract class.  More specific subclasses are
    SingleFileDataset and MultiFileDataset.

    To add a dataset, subclass one of the subclasses of Dataset, such as
    MultiFileDataset, and implement the abstract methods.

    Dataset objects have a limited number of attributes.  To limit the
    occurence of bugs, dynamically setting non-pre-existing attributes is
    limited.  Attributes can be set either by passing keyword arguments
    when creating the object, or by setting the appropriate field in your
    typhon configuration file (such as .typhonrc).  The configuration
    section will correspond to the object name, the key to the attribute,
    and the value to the value assigned to the attribute.  See also
    :mod:`typhon.config`.

    Attributes:

        start_date (datetime.datetime or numpy.datetime64):
            Starting date for dataset.  May be used to search through ALL
            granules.  WARNING!  If this is set at a time t_0 before the
            actual first measurement t_1, then the collocation algorith (see
            CollocatedDataset) will conclude that there are 0 collocations
            in [t_0, t_1], and will not realise if data in [t_0, t_1] are
            actually added later!
        end_date (datetime.datetime or numpy.datetime64):
            Similar to start_date, but for ending.
        name (str):
            Name for the dataset.  Used to make sure there is only a
            single dataset with the same name for any particular dataset.
            If a dataset is initiated with a pre-exisitng name, the
            previous product is called.
        aliases (Mapping[str, str]):
            Aliases for field.  Dictionary can be useful if you want to
            programmatically loop through the same field for many different
            datasets, but they are named differently.  For example, an alias
            could be "ch4_profile".
        unique_fields (Container[str]):
            Set of fields that make any individual measurement unique.  For
            example, the default value is {"time", "lat", "lon"}.
        related (Mapping[str, Dataset]):
            Dictionary whose keys may refer to other datasets with related
            information, such as DMPs or flags.


Represents a dataset where all measurements are in one file.