The class for the flux images.

    The flux images are the drizzled filter images, however transformed
    from counts per second to flux. An according segment of each
    flux image is stored in the fluxcubes.


Central class to take the input and to create the fluxcubes
    for the list of images extracted from the header of the
    drizzled grism image.


Class to intitially handle all DPP files


Multi-Extension FITS Extractor class


Class for the drizzle configuration file


Class for the dummy image


Class for the administration of all aXe input.


This task generates a Grism Object List file using an Input Object List.


Class to create a dispersed image


Class to create a direct image


Class to make a dummy extraction


Configuration File Object


Configuration Beam object


Object for a polynomial with 2D variance


Default header for a configuration file


Header class for the configuration file


Class for a keyword in a configuration file

    This keyword class is a light, but yet versatile
    and important class to strore a keyword entry in a
    configuration file. All important values are
    directly read from the object attributes.


Class for a keyword list

    The keyword list class is a subclass derived from the
    keyword class. In the keyword list class has as an
    additional attribute the keyvalues transformed to a list
    of floats.


Error for unknown trace


Error for unknown dispersion


Error for wrong lengt in KeywordList


Central class to take the input and to create Input Object Lists

    for the list of images extracted from the header of the
    drizzled image.


    Small class to create dummy images for the simulations

    This class creates empty dispersed and direct images as dummies.
    Since all aXe C-executables need the dispersed image as an input,
    such an image must exist for making the simualtions.


Class to wrap drizzle command


Class to median-combine individual drizzles


Class to wrap the blot command


Class for the deriv-command


Class to add poisson noise


Class for the template spectra


General class to shift spectra in flux-redshift range


Class for the image list


Class for one image template


Subclass for lists with magnitude columns

    This class loads ASCII tables and identifies the magnitude colunmns,
    columns which have AB magnitudes as their content.
    The magnitude columns have column names "MAG_?<number>*", with
    "<number>" the associated wavelength of the AB magnitude.

    Moreover there are mechanisms to search for column names and store
    the column index in a dictionary.

    TODO: FINISH UPDATING THIS CLASS FOR AXEIOL BASE


Subclass for model spectra list


Subclass for model object table


General class to get interpolated values


Test class for functions in harmony_service_lib.provenance.


Test Harmony Message utilities.


Dummy class to mock adapter calls, performing a no-op service


    Dummy class to mock adapter calls, performing a no-op service
    that returns multiple STAC catologs instead of one


Dummy class to mock adapter calls and record the input messages


Session which ensures the Authorization header is sent to correct
    servers.

    After instantiating the EarthdataSession, set its `auth` attribute
    to a valid EarthdataAuth instance:

        session.auth = EarthdataAuth(...)

    This lifecycle method on requests.Session is called when handling
    redirect requests.


Custom Earthdata Auth provider to add EDL Authorization headers.


    Abstract base class for Harmony service adapters.  Service implementations
    should inherit from this class and implement the `#invoke(self)` or `#process_item(self, item, source)`
    method to adapt the Harmony message (`self.message`) into a service call

    Services may choose to override methods that do data downloads and result
    staging as well, if they use a different mechanism

    Attributes
    ----------
    message : harmony_service_lib.Message
        The Harmony input which needs acting upon
    logger: Logger
        Logger specific to this request


    Base class for deserialized Harmony message objects

    Attributes
    ----------
    data : dictionary
        The JSON data object / dictionary used to build this object

    properties: list
        A list of properties that are included in string representations


    A collection / granule / variable / coordinateVariable / visualization data source as found in
    the Harmony message "sources" list.

    Attributes
    ----------
    collection : string
        The id of the collection the data source's variables and granules are in
    shortName : string
        The unique short name of the collection as returned by the CMR
    versionId : string
        The version id of the collection as returned by the CMR
    variables : list
        A list of Variable objects for the variables which should be transformed
    coordinateVariables: list
        A list of Variable objects containing the coordinate variables for the
        collection.
    visualizations: list
        A list of objects containing the UMM-Vis data for the collection. This list will be
        empty if the user specifies any variables for subsetting.
    granules : list
        A list of Granule objects for the granules which should be operated on


    A data variable as found in a Harmony source's "variables" list

    Attributes
    ----------
    id : string
        The UMM-Var ID of the variable.
    name : string
        The UMM-Var short name of the variable, typically identifies layer name found in the
        science data file.
    fullPath : string
         The variable's absolute path within the file, including hierarchy.  Derived from
         UMM-Var group path combined with name.
    relatedUrls : list
         A list of RelatedUrl(s) for the variable.
    visualizations: list
        A list of Umm-Vis objects for the variable.


    A related URL describes an external resource or location on the web
    (data access location, project home page, relevant software packages, etc.)

    Attributes
    ----------
    url : string
        Points to the location of the resource described by the RelatedUrl.
    urlContentType : string
        A keyword which describes the content of a link at a high level.
    type : string
        A keyword which specifies the content of a link.
    subtype : string
        A keyword which further specifies the content of a link.
    description : string
        Explains where the link navigates and the type of information it contains.
    format : string
        The format of the data.
    mimeType : string
        The mime type of the data.


    A science granule as found in a Harmony source's "granules" list

    Attributes
    ----------
    id : string
        The CMR Granule ID of the granule
    name: string
        The granule's short name
    url: string
        The URL to the granule, preferentially an S3 URL.  Potentially behind EDL
    bbox : list
        A list of 4 floating point values corresponding to [West, South, East, North]
        coordinates of the granule's spatial MBR
    temporal: Temporal
        The temporal extent of the granule


    Min and max parameters as found in a Harmony message's "format.scaleExtent.[x|y]" objects

    Attributes
    ----------
    min: float
        The min value for the attribute
    max: float
        The max value for the attribute


    Dimension subset parameters as found in a single dimension from the list of the
    Harmony message's "subset.dimensions" field.

    Attributes
    ----------
    name: string
        The name of the dimension
    min: float
        The min value for the dimension
    max: float
        The max value for the dimension


    Scale extent parameters as found in a Harmony message's "format.scaleExtent" object

    Attributes
    ----------
    x: message.MinMax
        The min and max values for the scale extent for the X dimension
    y: message.MinMax
        The min and max values for the scale extent for the Y dimension


    Scale size parameters as found in a Harmony message's "format.scaleSize" object

    Attributes
    ----------
    x: float
        The scale size for the X dimension
    y: float
        The scale size for the Y dimension


    Output CRS information as found in a Harmony message's "format.srs" object

    Attributes
    ----------
    proj4 : string
        The Proj4 representation for output CRS.
    wkt : string
        The WKT information for output CRS.
    epsg : string
        The EPSG designation, if suppplied or derived, for output CRS.


    Output format parameters as found in a Harmony message's "format" object

    Attributes
    ----------
    crs: string
        A proj4 string or EPSG code corresponding to the desired output projection
    srs: message.SRS
        The output CRS information; overlappting information with 'crs'
    isTransparent: boolean
        A boolean corresponding to whether or not nodata values should be set to transparent
        in the output if the file format allows it
    mime: string
        The mime type of the desired output file
    width: integer
        The pixel width of the desired output
    height: integer
        The pixel height of the desired output
    dpi: integer
        The number of pixels per inch in the desired output file, for image output formats
        that support it
    interpolation: string
        The interpolation method
    scaleExtent: message.ScaleExtent
        The scale extent in the x and y dimensions
    scaleSize: message.ScaleSize
        The scale size in the x and y dimensions


    Remote resource

    Attributes
    ----------
    uri : string
        A string of the remote resource location
    type : string
        The resource's content type


    Subsetting parameters as found in a Harmony message's "subset" object

    Attributes
    ----------
    bbox : list
        A list of 4 floating point values corresponding to [West, South, East, North]
        coordinates
    point: list containing 2 floating point values corresponding to longitude and latitude
    shape: RemoteResource
        A reference to a location containing a shapefile
    dimensions: list
        A list of Dimension objects to subset against


    Temporal subsetting parameters as found in a Harmony message's "temporal" object

    Attributes
    ----------
    start : string
        An ISO 8601 datetime string for the earliest time for temporal subsetting
    end : string
        An ISO 8601 datetime string for the latest time for temporal subsetting


    Extra Args parameters as found in a Harmony message's "extraArgs" object
    The value of extra args parameter can be retrieved via ['<parameter>'],
    e.g. message.extraArgs['cut'] will return the value of 'cut' parameter in extraArgs.


    Top-level object corresponding to an incoming Harmony message.  Constructing
    this with a JSON string will deserialize the message into native Python object,
    perform any necessary version interpretation, and add some helpers to make access
    easier.  Generally, this object should be created and allowed to produce its
    child objects rather than directly instantiating Subset, Format, etc objects.
    For maximum compatibility and ease of use, services should prefer using objects
    of this class and their children rather than parsing Harmony's JSON.

    Attributes
    ----------
    version : string
        The semantic version of the Harmony message contained in the provided JSON
    callback : string
        (Deprecated) The URL that services must POST to when their execution is complete.
    stagingLocation : string
        An object store (S3) URL prefix under which services may elect to put their output.
        Services must have write access to the Harmony staging bucket for the deployed
        environment to use this value.  The location will be unique per Harmony request
        but services are responsible for ensuring no name clashes occur within a single
        request.  The prefix will end in a "/" character.
    isSynchronous : bool
        True if a user is awaiting an immediate response, False if the user is expecting
        the service to be performed at a later point.  This may influence prioritization
        of the request and impacts ability to send multi-file responses
    user : string
        The username of the user requesting the service.  If the message is coming from
        Harmony, services can assume that the provided username has been authenticated
    accessToken : string
        The Earthdata Login token for the caller. If present, the token is used as the
        identity for HTTP downloads.
    client : string
        A string indicating the client accessing the service, usually the harmony
        environment, e.g. "harmony-sit"
    requestId : string
        A UUID identifying the originating user request.  This should only be used for
        logging and tracing purposes, as a single user request may produce multiple
        service invocations.
    format: message.Format
        The Harmony message's output parameters
    subset: message.Subset
        The Harmony message's subsetting parameters
    temporal: message.Temporal
        The Harmony message's temporal subsetting parameters
    concatenate: bool
        True if the service should concatenate multiple input files into a single output
        file and false otherwise.
    average: string
        The averaging method to use
    extendDimensions: list
        A list of dimensions to extend.
    pixelSubset : bool
        True if pixel subset should be performed by the service.
    extraArgs: object
        A map of key (string type) and value (any type) pairs indicating the extra arguments
        that should be passed to the worker command


    Layout that adheres to what the Harmony server expects
    when multiple catalogs are output by a service.


A JSON log entry formatter.


Redacts sensitive information from logs.


Base class for Harmony exceptions.

    Attributes
    ----------
    message : string
        Explanation of the error
    category : string
        Classification of the type of harmony error
    level : string
        The level of the error, can be 'Error' or 'Warning'.


Class for throwing an exception indicating a Harmony request has been canceled


Class for throwing an exception indicating download failed due to not being able to access the data


Class for throwing an exception indicating the download failed due to a generic 500 internal server error


Class for throwing an exception indicating the error is a fatal error that is specific to a request
    and should not be retried by Harmony.


Class for throwing an exception indicating service found no data to process


Shows an example of what a service adapter implementation looks like


    pyAPES - main model class.
    Combines submodels 'CanopyModel' and 'Soil' and handles data-transfer
    between these model components and writing results.

    Last edit: SL 17.11.2019


r"""Describes interception in multilayer canopy.


r""" Radiation, momentum, CO2 and energy exchange inside plant canopies.


r""" Computes flow and scalar profiles within canopy.


r""" Describes distribution of within canopy radiation.


r"""Seasonal cycle of photosynthetic machinery.

    References:
        Kolari et al. 2007 Tellus.


r"""Describes seasonal cycle of leaf-area index (LAI)


r""" Contains plant-specific properties, state variables and phenological
    functions.


r""" Describes roots of planttype.


r"""Describes forest floor consisting of bryophytes, litter and/or baresoil.


 Represents snow cover-soil-atmosphere interactions with simple
     zero-dimensional degree-day model


Represents bare soil cover-soil-atmosphere interactions


r""" Represents bryophyte community-soil-atmosphere interactions.

    Characteristics of BryoType object are stored in 'properties' dictionary.
    These describes physical characteristics of a bryophyte layer.


 Defines heat and water balance of bryotype object

    Note:
        Class is callable so it can be used with scipy odeint and odesolver


Mock implementation for the boto3 Cognito client class


Mock implementation for the boto3 S3 client class


Provides methods for working with local file system paths.


    Class used to roll up methods related to user authentication to the
    Ingress Service Lambda.


Simple log filter to ensure each unique log message is only logged once.


    Specialization of the BufferingHandler class that submits all buffered log
    records to CloudWatch Logs via an API Gateway endpoint when flushed.

    Notes
    -----
    In order for this handler to communicate with API Gateway, the bearer_token
    and node_id properties must be set on an instance prior to the first
    invocation of the flush() method.


    Customized implementation of a ConfigParser object which sanitizes undesireable
    characters (such as double-quotes) from strings read from the INI config
    before they are returned to the caller.


    Class used to read and parse the INI config file used with the Ingress
    Client.


Provides methods to validate PDS Node identifiers.


Post-installation data extraction.


Base class to hold a classifier and its methods. The derived classes
    encapsulate specific methods, such as classifier optimization.


Uses Support vector machine (SVM) for classification.


Uses k-nearest neighbors vote (KNN) for classification.


Uses Multi-layer Perceptron for classification.


Uses random forest (RF) for classification.


Uses a decision tree (DT) for classification.


Uses boosted decision trees for classification.


Uses boosted random forests for classification.


Uses Gaussian Naive Bayes for classification.


Uses a tree based learning algorithm for classification from LightGBM.


Parametric model as implemented in Newling et al.
    (http://arxiv.org/abs/1010.1005).


Parametric model as implemented in Karpenka et al.
    (http://arxiv.org/abs/1208.1264).


    Empty data set, to fill up with light curves
    (of format astropy.table.Table) in your memory.


Class to read in the PLAsTiCC dataset. This is a simulated LSST catalog.

    Parameters
    ----------
    folder : str
        Folder where simulations are located.
    data_file: str
        Filename of the pandas dataframe which is has the light curve data.
    metadata_file: str
        Filename of the pandas dataframe containing the metadata for the light
        curves.
    mix : Bool, default = False
        If True, randomly permutes the objects when they are read in.


    Class to manage the files from a single dataset. The base class works with
    data from the SPCC. This class can be inherited and overridden to work a
    completely different kind of dataset.
    All this class really needs is a list of object names and a method,
    `get_lightcurve`, which takes an individual object name and returns a
    light curve. Other functions provided here are for plotting and
    convenience.


    Class to read in an LSST simulated dataset, based on OpSim runs and SNANA
    simulations.


    Class to read in the SNANA cadence simulations, which are divided into
    chunks.


Class to read in the SDSS supernovae dataset


Class to read in the SDSS simulations dataset


Generic class to read in SNANA simulation datasets.

    SNANA stores each class in a different folder. Each folder has several
    files containing differenct batches of data.
    This class was prepared for SNANA version TODO

    Parameters
    ----------
    folder : str
        Folder where simulations are located.
    data_file: str
        Filename of the pandas dataframe which is has the light curve data.
    metadata_file: str
        Filename of the pandas dataframe containing the metadata for the light
        curves.
    survey_name : str
        Specifies the name of the survey; needed for output folder name.
    pb_wavelengths : dict
        Mapping between the passband names and their central wavelength. Note
        that `snmachine` has the default some default maps in
        `snmachine.sndata.default_pb_wavelengths`.
    mix : bool, optional
        Default False. If True, randomly permutes the objects when they are
        read in.

    Raises
    ------
    ValueError
        At least one model/folder must be provided in `model_list`.


Generic class to read in any SNANA simulation set.


Class to preprocess data files before reading into `snmachine`.

    Data files from different sources/at different times require a different
    preprocessing. This is an class to deal with it. Since this process is
    very data-specific, each child class has different inputs.


Class to preprocess SNANA data files before reading into `snmachine`.

    Parameters
    ----------
    data_folders : list of str
        List of paths to the folders that contain all the `.FITS` files to
        preprocess.


Base class to define basic functionality for extracting features from
    supernova datasets. Users are not restricted to inheriting from this class,
    but any Features class must contain the functions `extract_features` and
    `fit_sn`.


Calls sncosmo to fit a variety of templates to the data. The number of
    features will depend on the templates chosen (e.g. salt2, nugent2p etc.)


Fits a few options of generalised, parametric models to the data.


Uses wavelets to decompose the data and then reduces dimensionality of
    the feature space using PCA.


Class adapted from `avocado` augmentation [1]_.

    References
    ----------
    .. [1] Boone, Kyle. "Avocado: Photometric classification of astronomical
    transients with gaussian process augmentation." The Astronomical Journal
    158.6 (2019): 257.


Base class outlining the structure for the augmentation of a sndata
    instance. Classes that encapsulate a specific data augmentation procedure
    are derived from this class.


Augment the dataset using the Gaussian Process extrapolation of the
    known events.


Augment the Wide-Fast-Deep (WFD) events in the PLAsTiCC dataset using
    Gaussian Process extrapolation method (see `snaugment.GPAugment`).


Augment the Deep Drilling Field (DDF) events in the PLAsTiCC dataset
    using Gaussian Process extrapolation method (see `snaugment.GPAugment`).


Augment the Wide-Fast-Deep (WFD) events in the LSST-like dataset
    corresponding to the PLAsTiCC-like `baseline_v2.0_10yrs.db` cadence. The
    augmentation uses Gaussian Process extrapolation method (see
    `snaugment.GPAugment`).


Augment the Wide-Fast-Deep (WFD) events in the LSST-like dataset
    corresponding to the `baseline_v2.0_10yrs.db` cadence. The
    augmentation uses Gaussian Process extrapolation method (see
    `snaugment.GPAugment`).


Augment the Wide-Fast-Deep (WFD) events in the LSST-like dataset
    corresponding to the `presto_gap2.5_mix_v2.0_10yrs.db` cadence. The
    augmentation uses Gaussian Process extrapolation method (see
    `snaugment.GPAugment`).


Augment the Wide-Fast-Deep (WFD) events in the LSST-like dataset
    corresponding to the years 1.5 to 3 in the  `baseline_v2.0_10yrs.db`
    cadence. The augmentation uses Gaussian Process extrapolation method (see
    `snaugment.GPAugment`).


Augment the Wide-Fast-Deep (WFD) events in the LSST-like dataset
    corresponding to the years 1.5 to 3 in the `noroll_v2.0_10yrs.db` cadence.
    The augmentation uses Gaussian Process extrapolation method (see
    `snaugment.GPAugment`).


    Derived class that encapsulates data augmentation via Nearest Neighbour
    inspired algorithms such as SMOTE, ADASYN etc.


Gaussian mixture model with K components in D dimensions.

    Attributes:
        amp: numpy array (K,), component amplitudes
        mean: numpy array (K,D), component means
        covar: numpy array (K,D,D), component covariances


Background object to be used in conjuction with GMM.

    For a normalizable uniform distribution, a support footprint must be set.
    It should be sufficiently large to explain all non-clusters samples.

    Attributes:
        amp (float): mixing amplitude
        footprint: numpy array, (D,2) of rectangular volume
        adjust_amp (bool): whether amp will be adjusted as part of the fit
        amp_max (float): maximum value of amp allowed if adjust_amp=True


Class which supports an async version of applying functions to arguments.


    This class mantains the basic information of the sample
    to minimize hardcoded parameters in the test functions

    Everyone is meant to call mysample to obtain information like
         - path to ccd-annotated files   : ccds
         - zero points                   : zp0
         - magnitude limits (recm)       : recm
         - photoz requirements           : phreq
         - extintion coefficient         : extc
         - extintion index               : be
         - mask var eqv. to blacklist_ok : maskname
         - predicted frac exposures      : FracExp
    Current Inputs are: survey, DR, band, localdir)
         survey: DECaLS, MZLS, BASS
         DR:     DR3, DR4
         band:   g,r,z
         localdir: output directory


	Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)

	e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))


    This class mantains the basic information of the sample
    to minimize hardcoded parameters in the test functions

    Everyone is meant to call mysample to obtain information like
         - path to ccd-annotated files   : ccds
         - zero points                   : zp0
         - magnitude limits (recm)       : recm
         - photoz requirements           : phreq
         - extintion coefficient         : extc
         - extintion index               : be
         - mask var eqv. to blacklist_ok : maskname
         - predicted frac exposures      : FracExp
         - footprint poly (in some cases) : polyFoot
    Current Inputs are: survey, DR, band, localdir)
         survey: DECaLS, MZLS, BASS, DEShyb, NGCproxy
         DR:     DR3, DR4, DR5
         band:   g,r,z
         localdir: output directory
         (DEShyb is some DES proxy area; NGC is a proxy of North Gal Cap)


    A subclass of the legacypipe's DECam image-handling class to handle
    different file structures / header cards.


    A subclass of the legacyzpt's DECam image-handling class to handle
    different file structures / header cards.


given a astropy table of a Tractor Catalogue, this object computes
    everything you could need to know for the Tractor Catalogue


a Single_DataSet contains a concatenated tractor catalogue as Astropy table
    with additional columns for mags, masks, target selection, etc


a Matched_DataSet contains a dict of 4 concatenated, matched, tractor catalogue astropy Tables
    each table has additional columns for mags, target selection, masks, etc.


Iterator for looping over subsets of an array


Read and sample from a pre-defined Gaussian mixture model.
    This assumes 'sklearn.mixture.GMM' has already been used to determine MoGs


functions to add Target Selection box to ELG, LRG, etc plot
    add_ts_box -- main functino to call


1 hdf5 with groups /star,qso,elg,lrg,back each being its own data set


Draw randomly from unit sphere & provide 2 masks:
    mask1: inbricks -- indices where ra,dec pts are in LegacySurvey bricks
    mask2: inimages -- union with inbricks and where we have legacy survey imaging data at these ra,dec pts
    Example:
    ran= DesiRandoms(ramin=243.,ramax=246.,dcmin=7.,dcmax=10.,Nran=216000)
    ran.get_randoms()
    # save randoms if file not exist and plot
    ran.save_randoms()
    ran.plot(xlim=(244.,244.1),ylim=(8.,8.1)) #,xlim=(244.,244.+10./360),ylim=(8.,8.+10./360.))


Compute w(theta) from observed ra,dec and random ra,dec
    uses landy szalay estimator: DD - 2DR + RR / RR
    two numerical methods: 1) Yu Feng's kdcount, 2) astroML
    Example:
    ac= Angular_Correlator(gal_ra,gal_dec,ran_ra,ran_dec)
    ac.compute()
    ac.plot()


    A LegacySurveyImage subclass to handle images from the MegaPrime
    camera on CFHT.


 Class used during fitting of the RexGalaxy type -- an ellipse
    type where only the radius is variable, and is represented in log
    space.


This defines the 'REX' galaxy profile -- an exponential profile
    that is round (zero ellipticity) with variable radius.
    It is used to measure marginally-resolved galaxies.

    The real action (what makes it a Rex) happens when it is constructed,
    via, eg,

        rex = RexGalaxy(position, brightness, LogRadius(0.))

    (which happens in oneblob.py)


This defines the 'SIMP' galaxy profile -- an exponential profile
    with a fixed shape of a 0.45 arcsec effective radius and spherical
    shape.  It is used to detect marginally-resolved galaxies.


A little duck-typing class when running on a custom RA,Dec center
    rather than a brick center.


    Used in our LegacySurveyData "write_output" context class, this allows easily
    setting a default "dither_seed" keyword arg for all *write* calls.


    A class describing the contents of a LEGACY_SURVEY_DIR directory --
    tables of CCDs and of bricks, and calibration data.  Methods for
    dealing with the CCDs and bricks tables.

    This class is also responsible for creating LegacySurveyImage
    objects (eg, DecamImage objects), which then allow data to be read
    from disk.


    A LegacySurveyImage subclass to handle images from the Dark Energy
    Camera, DECam, on the Blanco telescope.


    A base class containing common code for the images we handle.

    You probably shouldn't need to directly instantiate this class,
    but rather use the recipe described in the __init__ method.

    Objects of this class represent the metadata we have on an image,
    and are used to handle some of the details of going from an entry
    in the CCDs table to a tractor Image object.


    Class for handling images from the 90prime camera processed by the
    NOIRLab Community Pipeline.


    Class for handling images from the Mosaic3 camera processed by the
    NOIRLab Community Pipeline.


An ellipse (used to represent galaxy shapes) with Gaussian priors
    over softened ellipticity parameters.  This class is used during
    fitting.

    We ALSO place a prior on log-radius, forcing it to be < +5 (in
    log-arcsec); though this gets dynamically adjusted in the oneblob.py code.

    To use this class, subclass it and set the 'ellipticityStd' class
    member.


A DecamImage subclass to add noise to DECam images upon read.


A LegacySurveyImage (via CPImage) subclass to handle images from
    the Dark Energy Camera, DECam, on the Blanco telescope.


    This class maintains a list of the model patches for a set of sources
    in a set of images.


A class for handling coadds of unWISE (and GALEX) images.


A Time subclass that reports overall CPU use, assuming multiprocessing.


 Represents an exception that has occured during a slave process

        Attributes
        ----------
        reason : Exception, or subclass of Exception.
            The underlining reason of the exception.
            If the original exception can be pickled, the type of the exception
            is preserved. Otherwise, a LostExceptionType warning is issued, and
            reason is of type Exception.

        traceback : str
            The string version of the traceback that can be used to inspect the
            error.


Monitoring a group of worker processes


 Asyncrhonized function call via a background process.

        Parameters
        ----------
        function : callable
            the function to call
        *args   : positional arguments
        **kwargs : keyward arguments

        Examples
        --------

        >>> def function(*args, **kwargs):
        >>>    pass
        >>> bg = background(function, *args, **kwargs)
        >>> rt = bg.wait()


        A pool of slave processes for a Map-Reduce operation

        Parameters
        ----------
        backend : ProcessBackend or ThreadBackend
            ProcessBackend is preferred. ThreadBackend can be used in cases where
            processes creation is not allowed.

        np   : int or None
            Number of processes to use. Default (None) is from OMP_NUM_THREADS or
            the number of available cores on the computer. If np is 0, all operations
            are performed on the master process -- no child processes are created.

        Notes
        -----
        Always wrap the call to :py:meth:`map` in a context manager ('with') block.


 Arrays allocated on shared memory.

        The array is stored in an anonymous memory map that is shared between child-processes.


Wrapper class of Dataset class that performs multi-threaded data loading


This class is an abstract base class (ABC) for datasets.

    To create a subclass, you need to implement the following four functions:
    -- <__init__>:                      initialize the class, first call BaseDataset.__init__(self, opt).
    -- <__len__>:                       return the size of dataset.
    -- <__getitem__>:                   get a data point.
    -- <modify_commandline_options>:    (optionally) add dataset-specific options and set default options.


This dataset class can load a set of images specified by the path --dataroot /path/to/data.

    It can be used for generating CycleGAN results only for one side with the model option '-model test'.


A dataset class for paired image dataset.

    It assumes that the directory '/path/to/data/train' contains image pairs in the form of {A,B}.
    During test time, you need to prepare a directory '/path/to/data/test'.


This class includes test options.

    It also includes shared options defined in BaseOptions.


This class includes training options.

    It also includes shared options defined in BaseOptions.


This class defines options used during both training and test time.

    It also implements several helper functions such as parsing, printing, and saving the options.
    It also gathers additional options defined in <modify_commandline_options> functions in both dataset class and model class.


This class implements an image buffer that stores previously generated images.

    This buffer enables us to update discriminators using a history of generated images
    rather than the ones produced by the latest generators.


A Python script for downloading CycleGAN or pix2pix datasets.

    Parameters:
        technique (str) -- One of: 'cyclegan' or 'pix2pix'.
        verbose (bool)  -- If True, print additional information.

    Examples:
        >>> from util.get_data import GetData
        >>> gd = GetData(technique='cyclegan')
        >>> new_data_path = gd.get(save_path='./datasets')  # options will be displayed.

    Alternatively, You can use bash scripts: 'scripts/download_pix2pix_model.sh'
    and 'scripts/download_cyclegan_model.sh'.


This HTML class allows us to save images and write texts into a single HTML file.

     It consists of functions such as <add_header> (add a text header to the HTML file),
     <add_images> (add a row of images to the HTML file), and <save> (save the HTML to the disk).
     It is based on Python library 'dominate', a Python library for creating and manipulating HTML documents using a DOM API.


This class includes several functions that can display/save images and print/save logging information.

    It uses a Python library 'visdom' for display, and a Python library 'dominate' (wrapped in 'HTML') for creating HTML files with images.


Simple undirected graph.

    Note: stores edges; can not store vertices without edges.


This class is an abstract base class (ABC) for models.
    To create a subclass, you need to implement the following five functions:
        -- <__init__>:                      initialize the class; first call BaseModel.__init__(self, opt).
        -- <set_input>:                     unpack data from dataset and apply preprocessing.
        -- <forward>:                       produce intermediate results.
        -- <optimize_parameters>:           calculate losses, gradients, and update network weights.
        -- <modify_commandline_options>:    (optionally) add model-specific options and set default options.


 This TesteModel can be used to generate CycleGAN results for only one direction.
    This model will automatically set '--dataset_mode single', which only loads the images from one collection.

    See the test instruction for more details.


    This class implements the CycleGAN model, for learning image-to-image translation without paired data.

    The model training requires '--dataset_mode unaligned' dataset.
    By default, it uses a '--netG resnet_9blocks' ResNet generator,
    a '--netD basic' discriminator (PatchGAN introduced by pix2pix),
    and a least-square GANs objective ('--gan_mode lsgan').

    CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf


Define different GAN objectives.

    The GANLoss class abstracts away the need to create the target label tensor
    that has the same size as the input.


Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.

    We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)


Define a Resnet block


Create a Unet-based generator


Defines the Unet submodule with skip connection.
        X -------------------identity----------------------
        |-- downsampling -- |submodule| -- upsampling --|


Defines a PatchGAN discriminator


Defines a 1x1 PatchGAN discriminator (pixelGAN)


 This class implements the pix2pix model, for learning a mapping from input images to output images given paired data.

    The model training requires '--dataset_mode aligned' dataset.
    By default, it uses a '--netG unet256' U-Net generator,
    a '--netD basic' discriminator (PatchGAN),
    and a '--gan_mode' vanilla GAN loss (the cross-entropy objective used in the orignal GAN paper).

    pix2pix paper: https://arxiv.org/pdf/1611.07004.pdf


Terminal progress bar class


Keeps track of all things FFTW + scale related for the WSCMS minor cycle


Class to manage FFTW for WSCMS minor cycle


        This is the factory class for ModelMachine. Basically give it a dictionary containing the components of a model image
        and it instantiates and returns a copy of the correct ModelMachine. Each pickled dictionary should contain a field
        labelling which deconvolution algorithm it corresponds to.


    Interface to ClassModelMachine (in progress)
    GiveModelImage(FreqIn)
        Input:
            FreqIn      = The frequencies at which to return the model image

    ToFile(FileName,DicoIn)
        Input:
            FileName    = The name of the file to write to
            DicoIn      = The dictionary to write to file. If None it writes the current dict in DicoSMStacked to file

    FromFile(FileName)
        Input:
            FileName    = The name of the file to read dict from

    FromDico(DicoIn)
        Input:
            DicoIn      = The dictionary to read in


    This class extends the basic infrastructure set out in ClassFacetMachine to
    split the sky into a Voronoi tesselated sky. The projection, unprojection and resampling logic
    remains the same.


    This is a dictionary like interface to access .npy files on disk
    in the folder specified by cache_dir. These files should be keyed
    on the string pattern in between cache_dir and .npy
    Useful when creating an lru cache with disk spillover
    when the size exceeds some maximum.


    Given a dictionary of MS arrays, infers the number of:
        - timesteps
        - baselines
        - antenna
        - channels

    ASSUMPTIONS:
        1. We're dealing with a single band
        2. We're dealing with a single field
        3. We're dealing with a single observation

    Arguments:
        MS: DDFacet.Data.ClassMS instance
        pointing_sols: DDFacet.Data.PointingProvider associated to MS
        solver_polarization_type: initiate montblanc for linear or circular feeds


    This class contains all information about facets and projections.
    The class is responsible for tesselation, gridding, projection to image,
    unprojection to facets and degridding

    This class provides a basic gridded tesselation pattern.


    Interface to fit frequency axis in model image. All fitting is currently based on some polynomial model in normalised frequencies (v/v_0).
    For the alpha map the fit happens in log space.
        Initialisation:
                ModelCube   = A cube containing the model image with shape [NChannel,NPol,Npix,Npix]
                Freqs       = The gridding frequencies
                Freqsp      = The degridding frequencies
                ref_freq    = The reference frequency
        Methods:
                getFitMask  : Creates a mask to fit models to
                setDesMat   : Creates a design matrix in either log or normal space
                FitAlphaMap : Fits an alpha map to pixels in the model image above a user specified threshold
                EvalAlphaMap: Evaluates the model image from the alpha map
                FitPolyCube : Fits a polynomial to pixels in the model image above a user specified threshhold
                EvalPoly    : Evaluates the polynomial from the computed coefficients
                FitGP       : Fits a Gaussian process to the spectral axis of the model image to pixels above a user specified threshold


    These methods may be called from ClassDeconvMachine
        Init(**kwargs) - contains minor cycle specific initialisations which are only used once
            Input: currently kwargs are minor cycle specific and should be set from ClassDeconvMachine but a
                     ideally a generic interface has these set in the parset somehow.
        Deconvolve() - does joint deconvolution over all the channels/bands.
            Output: return_code - "MaxIter"????
                    continue - whether to continue the deconvolution
                    updated - whether the model has been updated
        GiveModelImage(freq) - returns current model at freq
            Input: freq - tuple of frequencies at which to return the model
            Output: Mod - the current model at freq
        Update(DicoDirty,**kwargs) - updates to minor cycle at the end of each major cycle
            Input:  DicoDirty - updated image dict at start of each major cycle
                    Use kwargs to pass any other minor cycle specific options
        ToFile(fname) - saves dico model to file
            Input: fname - the name of the file to write the dico image to
        FromFile(fname) - reads model dict from file
            Input: fname - the name of the file to write the dico image to


    Currently constructor inputs match those in MSMF, should figure out which are truly generic and put the rest in
    parset's MinorCycleConfig option.
    These methods may be called from ClassDeconvMachine
        Init(**kwargs) - contains minor cycle specific initialisations which are only used once
            Input: currently kwargs are minor cycle specific and should be set from ClassDeconvMachine but a
                     ideally a generic interface has these set in the parset somehow.
        Deconvolve() - does joint deconvolution over all the channels/bands.
            Output: return_code - "MaxIter"????
                    continue - whether to continue the deconvolution
                    updated - whether the model has been updated
        GiveModelImage(freq) - returns current model at freq
            Input: freq - tuple of frequencies at which to return the model
            Output: Mod - the current model at freq
        Update(DicoDirty,**kwargs) - updates to minor cycle at the end of each major cycle
            Input:  DicoDirty - updated image dict at start of each major cycle
                    Use kwargs to pass any other minor cycle specific options
        ToFile(fname) - saves dico model to file
            Input: fname - the name of the file to write the dico image to
        FromFile(fname) - reads model dict from file
            Input: fname - the name of the file to write the dico image to


helper class for MergeIsland


    This class is essentially a wrapper around a single HMP machine. It initializes an HMP machine
    with very specific settings, then uses it deconvolve (init) SSD islands.

    The class is initialized once in the main process (to populate the HMP basis function cache),
    then re-initialized in the workers on a per-island basis.


A timer context manager

    Used as

    >>> with Timer() as t: print("Do things")
    >>> t.msecs


Make non circular convolution with fft


Read image and meta-data from TIFF, STK, LSM, and FluoView files.

    TiffFile instances must be closed using the close method, which is
    automatically called when using the 'with' statement.

    Attributes
    ----------
    pages : list
        All TIFF pages in file.
    series : list of Records(shape, dtype, axes, TiffPages)
        TIFF pages with compatible shapes and types.
    micromanager_metadata: dict
        Extra MicroManager non-TIFF metadata in the file, if exists.

    All attributes are read-only.

    Examples
    --------
    >>> tif = TiffFile('test.tif')
    ... try:
    ...     images = tif.asarray()
    ... except Exception as e:
    ...     print(e)
    ... finally:
    ...     tif.close()


A TIFF image file directory (IFD).

    Attributes
    ----------
    index : int
        Index of page in file.
    dtype : str {TIFF_SAMPLE_DTYPES}
        Data type of image, colormapped if applicable.
    shape : tuple
        Dimensions of the image array in TIFF page,
        colormapped and with one alpha channel if applicable.
    axes : str
        Axes label codes:
        'X' width, 'Y' height, 'S' sample, 'P' plane, 'I' image series,
        'Z' depth, 'C' color|em-wavelength|channel, 'E' ex-wavelength|lambda,
        'T' time, 'R' region|tile, 'A' angle, 'F' phase, 'H' lifetime,
        'L' exposure, 'V' event, 'Q' unknown, '_' missing
    tags : TiffTags
        Dictionary of tags in page.
        Tag values are also directly accessible as attributes.
    color_map : numpy array
        Color look up table, if exists.
    mm_uic_tags: Record(dict)
        Consolidated MetaMorph mm_uic# tags, if exists.
    cz_lsm_scan_info: Record(dict)
        LSM scan info attributes, if exists.
    imagej_tags: Record(dict)
        Consolidated ImageJ description and metadata tags, if exists.

    All attributes are read-only.


A TIFF tag structure.

    Attributes
    ----------
    name : string
        Attribute name of tag.
    code : int
        Decimal code of tag.
    dtype : str
        Datatype of tag data. One of TIFF_DATA_TYPES.
    count : int
        Number of values.
    value : various types
        Tag data as Python object.
    value_offset : int
        Location of value in file, if any.

    All attributes are read-only.


Sequence of image files.

    Properties
    ----------
    files : list
        List of file names.
    shape : tuple
        Shape of image sequence.
    axes : str
        Labels of axes in shape.

    Examples
    --------
    >>> ims = TiffSequence("test.oif.files/*.tif")
    >>> ims = ims.asarray()
    >>> ims.shape
    (2, 100, 256, 256)


Dictionary with attribute access.

    Can also be initialized with numpy.core.records.record.


Dictionary of TiffTags with attribute access.


Real emulate real float builtin number with mutability

    Implements numbers.Real abstract interace
    >>> R = Real(1.0)
    >>> R
    1.0
    >>> isinstance(R, numbers.Real)
    True
    >>> R.real is R
    True
    >>> R.imag is int(0)
    True
    >>> R.conjugate() is R
    True
    >>> complex(R)
    (1+0j)

    Underlying float builtin value is accessible
    >>> type(R.value) is type(2.0)
    True

    Since Real is mutable, left operator update the value
    >>> S = R + 2
    >>> S
    3.0
    >>> S is R
    True
    >>> R += 1
    >>> R
    4.0
    >>> type(R)
    <class '__main__.Real'>

    However, right operator imply float conversion
    >>> S = 2 + R
    >>> S
    6.0
    >>> S is R
    False
    >>> type(S) is type(2.0)
    True

    Of course, addition is possible only with numbers (at least
    Complex from numbers module)
    >>> R + "1"
    Traceback (most recent call last):
       ...
    TypeError: ...


    This is a helper class to dump and load clean solutions from a pickle file. For writing, it maintains a singleton
    version of itself. For reading, it will bootstrap itself from a dump file (so it's entirely self-contained, and
    does not need importing DDFacet or anything)

    Usage, for writing:
        # repeat at every minor cycle
        CleanSolutionsDump.init(filename, "a", "b", "c")    # only inits the first time, if necessary
        CleanSolutionsDump.write(a, b, c)

    Usage, for reading (in e.g. ipython _without_ needing to import anything)
        import cPickle
        fobj = open(filename)
        dump = cPickle.load(fobj)
        dump.read(fobj)

        pylab.plot(dump.a, dump.b)

    Note that after reading, dump.a and dump.b and dump.c will be arrays of shape (NMinorCycle,...), where ...
    is the shape of the a, b, c components passed to write()


Exception that captures item loading errors


Base class for helper class used to defer loading of SharedDict items until they are actually requested


A default writer logs messages to a logger


LogFilter augments the event by a few new attributes used by our formatter


    # CacheManager

    This is a simple disk-based cache management class. Usage is as follows:

        cache = CacheManager("/cache/directory")

    This creates a cache based on the specified path. Directory is created if it doesn't exist.
    If you create CacheManager with reset=True, the contents of the directory are deleted.

    Typically, you would use the cache in the following pattern:

        path, valid = cache.checkCache("foo", hashvalue)
        if valid:
            ## your data is on disk and good, load it from "path". E.g.
            data = numpy.load(path)
        else:
            ## your data must be recomputed. Recompute it and save it to "path".
            data = expensiveComputation()
            numpy.save(path, data)
            cache.saveCache("foo")  # mark the cache as valid

    So: checkCache() returns a path to the item (/cache/directory/foo, in this case), and a flag telling
    you if the saved item is valid. The item is considered valid if /cache/directory/foo exists, **and**
    /cache/directory/foo.hash exists, **and** contains the same value as the supplied "hashvalue". Thus,
    if hashvalue has changed w.r.t. the stored hash, then the cache is invalid.

    Hashvalue may be any Python object supporting the comparison operator (for example, a dict).
    Typically, this would be a dict of parameters any changes in which should cause the data item
    to be recomputed.

    The saveCache("foo") call is vitally important! The cache manager cannot know by itself when
    you've successfully written to the cache. By calling saveCache(), you're telling it that your data
    has been safely written to /cache/directory/foo. The cache manager then takes the hashvalue you
    supplied in the previous checkCache() call, and saves it to /cache/directory/foo.hash.

    # Using cache manager in DDFacet

    DDFacet caches the following data items:

        * W-kernels & other facet-related data

        * BDA mappings for gridding and degridding, flags, Jones matrices

    Each MS has a top-level cache named mspath.ddfcache, and per-chunk caches named
    mspath.ddfcache/Fx:Dy:n:m, where F is field ID, D is DDID, and n:m are row numbers.
    The per-chunk caches are used when iterating over MSs during gridding/degridding.

    Each ClassMS object has an ms.maincache attribute, and an ms.cache attribute.
    The former corresponds to that MS's top-level cache. The latter corresponds to
    the cache of the current chunk being iterated over.

    The ClassVisServer object has a VS.maincache an a VS.cache attribute. VS.maincache
    points to the maincache of the first MS in the list. This is used to cache facet data.
    VS.cache points to the cache of the current chunk of the current MS being iterated over.
    This is used to cache the various mappings.

    To form up hashvalues, the global dict (GD) object is very convenient. Sections of GD
    that influence a particular cache item are used as the hashvalue in each case.

    Running with DeleteDDFProducts=1 causes all caches to be reset.


Implements a condition variable that is a counter. Typically used to keep track of the number of pending jobs
    of a particular type, and to block until all are complete


    Converts between correlations (predominantly used in visibility space) and Stokes
    parameters (used in image space). This transformation can be done before or after Fourier inversion (Fourier transform
    preserves addition).
    Args:
        MSDataDescriptor: Correlation descriptor taken from POLARIZATION MS2.0 table, CORR_TYPE field
        FITSPolDescriptor: Descriptor for required polarizations in FITS files (can be IQUV string or list of
                           correlations (and/or polarizations)
    Raises:
        ValueError if the Measurement set doesn't contain supported constants (see StokesTypes)
        ValueError if one of requested polarizations are not supported
        ValueError if requested polarizations is not a stokes string or list
    Post conditions:
        self._MSDataDescriptor are the correlations specified as per input arg (as defined in Stokes.h in casacore)
        self._MScorrLabels are the string identifiers of the input MS correlations
        self._gridMSCorrMapping is the mapping between the Stokes.h correlation identifiers and the index in the visibility
                                array (or grid cube)
        self._FITSstokesList are the Stokes parameters passed to the initializer
        self._FITSstokesSliceLookup is a mapping between the Stokes.h identifier of the polarization and the FITS
                                polarization slice.
        self._stokesExpr is the correlation to stokes dependency resolution (as defined in StokesDependencies) for
                                converting gridded visibilities to gridded stokes, for each required stokes component
        self._corrExpr is the stokes to correlation dependency resolution (as defined in CorrelationDependencies) for
                                converting gridded stokes to gridded visibilities, for each correlation in the measurement
                                CORR_TYPE field


 Automated assurance test: reference FITS file regression (abstract class)
        Input:
            Accepts a set of reference images (defined in define_image_list),
            input measurement set and parset file.

            The parset file can be a subset of available
            options since DDFacet reads all values from the default parset. The
            overrides should specify an input measurement set or set of measurement
            sets.

            !!!Note: each measurement set should only be the name of the measurement
            !!!set since the tests must be portable. The names are automatically updated
            !!!to be relative to the data directory specified via environment variable
            !!!below.

            The parset should contain all the options that are to be tested in t
            he test case, but should not specify the output
            image file prefix, as this is overridden according to the filename
            rules below. Use setParsetOption to set a configuration option.

            Input filename convention:
                1. Input files directory: Set environment variable "DDFACET_TEST_DATA_DIR"
                                        (defaults to current directory)
                2. Reference image name: [TestClassName].[ImageIdentifier].fits
                3. Parset file: [TestClassName].parset.cfg

        Output filename convention:
            1. Output files directory: Set environment variable "DDFACET_TEST_OUTPUT_DIR"
                                        (defaults to tmp)
            2. Run-produced image name: [TestClassName].run.[ImageIdentifier].fits
            3. DDFacet logfiles: [TestClassName].run.out.log and [TestClassName].run.err.log
            4. Parset with default overrides, including image prefixes: [TestClassName].run.parset.conf
            5. Diff map as computed with fitstool.py with filename [TestClassName].diff.[ImageIdentifier].fits

        Tests cases:
            Tests the output of DDFacet against the reference images. Currently
            we are only testing the following:
                1. max (ref-output)^2 <= tolerance
                2. Mean Squared Error <= tolerance
                3. Parse the logs of the reference images and compare runtime against current test case runtime


        Automated assurance test for ddfacet predict option
        Finds parset with the name TestFacetPredict.parset.cfg and executes a predict
        Compares the amplitude and phase differences between a DFT (Meqtrees) and a facet-based degridding
        with a source close to the facet centre. With and without beam enabled.
        Input:
            TestFacetPredict.parset.cfg in DDFACET_TEST_INPUT_DIR
        Output
            Amplitude plots of the visibilities for comparison
            [classname].run.parset into DDFACET_TEST_OUTPUT_DIR


    A dictionary that also provides access via attributes.

    Additional methods update_values and update_None provide
    control over whether new keys are added to the dictionary
    when updating, and whether an attempt to add a new key is
    ignored or raises a KeyError.

    The Bunch also prints differently than a normal
    dictionary, using str() instead of repr() for its
    keys and values, and in key-sorted order.  The printing
    format can be customized by subclassing with a different
    str_ftm class attribute.  Do not assign directly to this
    class attribute, because that would substitute an instance
    attribute which would then become part of the Bunch, and
    would be reported as such by the keys() method.

    To output a string representation with
    a particular format, without subclassing, use the
    formatted() method.


Parse the line-pair for checks in gsw_check_functions.


container for model parameters. contains fs, A, alpha, mustar, beta parameters.


a sample of subhaloes


modified dictionary that works using ".key"


Handles teslakit hourly data split in multiple netCDF4 files


auxiliar object for handling teslakit files paths


database for MDA-SWAN-RBF methodology


Stores hydrograph data


    KMA - DWTs Climate Emulator

    Fit Waves extremes model (GEV, Gumbel, Weibull distributions) and DWTs series
    Simulate (probabilistic) a new dataset of Waves from a custom DWTs series

    This custom emulator uses Waves data divided by families (sea, swell_1,
    swell_2, ...), each family is defined by 3 variables: Hs, Tp, Dir

    Some configuration parameters:

    A chromosomes methodology for statistical fit is available, it will handle
    on/off probabilities for each different waves family combination.

    Aditional variables, outside of waves families, can be given to the emulator.

    A variable has to be selected as the PROXY to calculate storms max. (default: AWL)

    User can manually set a variable for an empircal / weibull / gev distribution.


    tesla-kit custom dataset handler

    used for 3D dataset (lon,lat,time) and related
    statistical classification calculations and figures.


AutoRegressive Logistic Model Wrapper


simulatiom log - records and stores detail info for each time step and n_sim


overfit filter for alr outlayer outputs.


	Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)
	e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))


SWAN numerical model input/output


SWAN numerical model input/output - STATIONARY cases


SWAN numerical model input/output - NON STATIONARY cases


SWAN numerical model mesh


SWAN numerical model project parameters, grids and information


SWAN numerical model wrap for multi-case handling


SWAN numerical model wrap for STATIONARY multi-case handling


SWAN numerical model wrap for NON STATIONARY multi-case handling


Class for computed PDR Model Sets. :class:`ModelSet` provides interface to a directory containing the model FITS files and the ability to query details about.

    :param name: identifying name, e.g., 'wk2006'
    :type name: str

    :param z:  metallicity in solar units.
    :type z: float

    :param medium:  medium type, e.g. 'constant density', 'clumpy', 'non-clumpy'
    :type medium: str

    :param mass: maximum clump mass (for KosmaTau models).  Default:None (appropriate for Wolfire/Kaufman models)
    :type mass: float

    :param modelsetinfo: For adding user specified ModelSet, this parameter
        specifies the file with information about the ModelSet. It can be a
        pathname to an externalt tabular file in an astropy-recognized or an
        astropy Table object.  If an external tabular file, its format should
        be give by the `format` keyword. The columns are:

        .. code-block:: python

           ['PDR code','name', 'version','path','filename','medium','z','mass','description']

        `z` and `mass` should be floats, the rest should be strings.
        The `name`, `version`, `medium`, `z`, and `mass` columns contain
        the values available in the input ModelSet as described above. `PDR
        code` is the originator of the code e.g., "KOSMA-tau", `version`
        is the code version, `path` is the full-qualified pathname to
        the FITS files, `filename` is the tabular file which contains
        descriptions of individual FITS files.  This must also be in
        the format specified by the `format` keyword.  `description`
        is a description of the input ModelSet.

    :type modelsetinfo: str or :class:`~astropy.table.Table`

    :param format: If `modelsetinfo` is a file, give the
        format of file. Must be `an astropy recognized Table format.
        <https://docs.astropy.org/en/stable/io/unified.html#built-in-readers-writers>`_
        e.g., ascii, ipac, votable. Default is `IPAC format
        <https://docs.astropy.org/en/stable/api/astropy.io.ascii.Ipac.html#astropy.io.ascii.Ipac>`_
    :type format: str

    :raises ValueError: If model set not recognized/found.


r"""Measurement represents one or more observations of a given spectral
    line or continuum.  It is made up of a value array, an
    uncertainty array, units, and a string identifier. It is based
    on :class:`astropy.nddata.CCDData`.  It can represent a single pixel
    observation or an image.   Mathematical operations using Measurements
    will correctly propagate errors.

    Typically, Measurements will be instantiated from a FITS file by using the the :func:`read` or :func:`make_measurement` methods.  For a list of recognized spectral line identifiers, see :meth:`~pdrtpy.modelset.Modelset.supported_lines`.

    :param data:  The actual data contained in this :class:`Measurement` object.
        Note that the data will always be saved by *reference*, so you should
        make a copy of the ``data`` before passing it in if that's the desired
        behavior.
    :type data: :class:`numpy.ndarray`-like

    :param uncertainty: Uncertainties on the data. If the uncertainty is a :class:`numpy.ndarray`, it assumed to be, and stored as, a :class:`astropy.nddata.StdDevUncertainty`.  Required.
    :type uncertainty: :class:`astropy.nddata.StdDevUncertainty`, \
            :class:`astropy.nddata.VarianceUncertainty`, \
            :class:`astropy.nddata.InverseVariance` or :class:`numpy.ndarray`

    :param unit: The units of the data.  Required.
    :type unit: :class:`astropy.units.Unit` or str

    :param identifier: A string indicating what this is an observation of, e.g., "CO_10" for CO(1-0)
    :type identifier: str

    :param title: A formatted string (e.g., LaTeX) describing this observation that can be used for plotting. Python r-strings are accepted, e.g., r'$^{13}$CO(3-2)'  would give :math:`^{13}{\rm CO(3-2)}`.
    :type title: str

    :param bmaj: [optional] beam major axis diameter. This will be converted to degrees for storage in FITS header
    :type  bmaj: :class:`astropy.units.Quantity`

    :param bmin: [optional] beam minor axis diameter. This will be converted to degrees for storage in FITS header
    :type  bmin: :class:`astropy.units.Quantity`

    :param bpa: [optional] beam position angle. This will be converted to degrees for storage in FITS header
    :type  bpa: :class:`astropy.units.Quantity`

    :raises TypeError: if beam parameters are not Quantities

    Measurements can also be instantiated by the **read(\\*args, \\**kwargs)**,
    to create an Measurement instance based on a ``FITS`` file.
    This method uses :func:`fits_measurement_reader` with the provided
    parameters.  Example usage:

    .. code-block:: python

       from pdrtpy.measurement import Measurement

       my_obs = Measurement.read("file.fits",identifier="CII_158")
       my_other_obs = Measurement.read("file2.fits",identifier="CO2_1",
                                        unit="K km/s",
                                        bmaj=9.3*u.arcsec,
                                        bmin=14.1*u.arcsec,
                                        bpa=23.2*u.degrees)

    By default image axes with only a single dimension are removed on read.  If you do not want this behavior, used `read(squeeze=False)`. See also: :class:`astropy.nddata.CCDData`.


This class implements the progress bar interface but does nothing


Base class for plotting.

    :param tool:  Reference to a :mod:`~pdrtpy.tool` object or `None`.  This is used for classes that inherit from PlotBase and are coupled to a specific tool, e.g. :class:`~pdrtpy.plot.LineRatioPlot` and :class:`~pdrtpy.tool.LineRatioFit`.
    :type tool: Any class derived from :class:`~pdrtpy.tool.toolbase.ToolBase`


ExcitationPlot creates excitation diagrams using the results of :class:`~pdrtpy.tool.h2excitationfit.H2ExcitationFit`. It can plot the observed excitation diagram with or without fit results, and allows averaging over user-given spatial areas.


ModelPlot is a tool for exploring sets of models.  It can plot individual intensity or ratio models, phase-space diagrams, and optionally overlay observations.   Units are seamlessly transformed, so you can plot in Habing units, Draine units, or any conformable quantity.  ModelPlot does not require model fitting with :class:`~pdrtpy.tool.lineratiofit.LineRatioFit` first.

    :Keyword Arguments:

    The methods of this class can take a variety of optional keywords.  See the general `Plot Keywords`_ documentation.


LineRatioPlot plots the results of :class:`~pdrtpy.tools.lineratiofit.LineRatioFit`.  It can plot maps of fit results, observations with errors on top of models, chi-square and confidence intervals and more.

    :Keyword Arguments:

    The methods of this class can take a variety of optional keywords.  See the general `Plot Keywords`_ documentation


    Base class for creating excitation fitting tools for various species.

    Parameters
    ----------
    molecule : `~pdrtpy.molecule.BaseMolecule`
        The molecule whose transitions will be fit.
    measurements : :class:`~pdrtpy.measurement.Measurement` or dict, optional.
        Input measurements to be fit. If input is a dictionary of measurements, the keys must Measurement identifiers. The default is None.


LineRatioFit is a tool to fit observations of intensity ratios to a set of PDR models. It takes as input a set of observations with errors represented as :class:`~pdrtpy.measurement.Measurement` and  :class:`~pdrtpy.modelset.ModelSet` for the models to which the data will be fitted. The observations should be spectral line or continuum intensities.  They can be spatial maps or single pixel values. They should have the same spatial resolution.

    The models to be fit are stored as intensity ratios. The input observations will be use to create ratios that correspond to models. From there a minimization fit is done to determine the density and radiation field that best fit the data. At least 3 observations are needed in order to make at least 2 ratios. With fewer ratios, no fitting can be done. More ratios generally means better determined density and radiation field, assuming the data are consistent with each other.

    Once the fit is done, :class:`~pdrtpy.plot.LineRatioPlot` can be used to view the results.

    :param modelset: The set of PDR models to use for fitting.
    :type modelset: :class:`~pdrtpy.modelset.ModelSet`

    :param measurements: Input measurements to be fit.
    :type measurements: list or dict of :class:`~pdrtpy.measurement.Measurement`. If dict, the keys should be the Measurement *identifiers*.


Base class object for PDR Toolbox tools.  This class implements a simple
    interface with a run method.  Tools will generally do some set up
    such as reading in observational data before run() can be invoked.


test the CO Excitation fitting tools


test the H2Excitation tool


TOA testing class


Tim testing class


Paramaeter testing class


Par testing class


    def getParameterFlags(self, tag):
        #If a parameter has flags, return all of the possible values as a list
        if tag in self.paramnames:
            ind = self.getInd(tag)
            retval = []
            for i in ind:
                retval.append(self.paramlist[i].getFlagValue())
            if len(retval) == 1:
                return retval[0]
            return np.array(retval)
        return None


Benchmark nifty-ls versus astropy's FFT-based implementation.


This class should implement all the actual
  computation done by your module.  The interface
  should be such that other python code can import
  this class and make use of the functionality without
  requiring an instance of the Widget


This is the test case for your scripted module.


Describe a set of sample data associated with one or multiple URIs and filenames.


Manage the slicer.modules.sampleDataSources dictionary.
  The dictionary keys are categories of sample data sources.
  The BuiltIn category is managed here.  Modules or extensions can
  register their own sample data by creating instances of the
  AstroSampleDataSource class.  These instances should be stored in a
  list that is assigned to a category following the model
  used in registerBuiltInSampleDataSources below.


A. NIESSNER: INLINE HACK TO ldtk.LDPSet


tests the `user_input()` function


tests the init_params() function


tests the `typecase_check()` function


tests the round_to_2() function


tests the get_val() function

    NOTE: this could be changed to a private method. The callers are all
    internal to this module


tests the `add_sign()` function

    NOTE: this could be changed to a private method. The callers are all
    internal to this module


tests the process_lat_long() function


tests the find() function


Server handles serving docs by dynamically remapping to the build directory.


Our faked object for testing.


Simulate file-like object access without seek.


r"""Provide custom attributes and methods on xarray DataArrays for MetPy functionality.

    This accessor provides several convenient attributes and methods through the ``.metpy``
    attribute on a DataArray. For example, MetPy can identify the coordinate corresponding
    to a particular axis (given sufficient metadata):

        >>> import xarray as xr
        >>> from metpy.units import units
        >>> temperature = xr.DataArray([[0, 1], [2, 3]] * units.degC, dims=('lat', 'lon'),
        ...                            coords={'lat': [40, 41], 'lon': [-105, -104]})
        >>> temperature.metpy.x
        <xarray.DataArray 'lon' (lon: 2)> Size: 16B
        array([-105, -104])
        Coordinates:
          * lon      (lon) int64 16B -105 -104
        Attributes:
            _metpy_axis:  x,longitude


Provide the unit-wrapped .loc indexer for data arrays.


Provide custom attributes and methods on XArray Datasets for MetPy functionality.

    This accessor provides parsing of CF grid mapping metadata, generating missing coordinate
    types, and unit-/coordinate-type-aware operations.

        >>> import xarray as xr
        >>> from metpy.cbook import get_test_data
        >>> ds = xr.open_dataset(get_test_data('narr_example.nc', False)).metpy.parse_cf()
        >>> print(ds['metpy_crs'].item())
        Projection: lambert_conformal_conic


Provide the unit-wrapped .loc indexer for datasets.


Manages exporting of symbols from the module.

    Grabs a reference to `globals()` for a module and provides a decorator to add
    functions and classes to `__all__` rather than requiring a separately maintained list.
    Also provides a context manager to do this for instances by adding all instances added
    within a block to `__all__`.


A class for issuing deprecation warnings for MetPy users.

    In light of the fact that Python builtin DeprecationWarnings are ignored
    by default as of Python 2.7 (see link below), this class was put in to
    allow for the signaling of deprecation, but via UserWarnings which are not
    ignored by default. Borrowed with love from matplotlib.

    https://docs.python.org/dev/whatsnew/2.7.html#the-future-for-python-2-x


Provide a generic function registry.

    This provides a class to instantiate, which then has a `register` method that can
    be used as a decorator on functions to register them under a particular name.


Represent a product stored in an AWS S3 bucket.


Facilitate access to a data store on AWS S3.


Access data from the NEXRAD Level 3 archive in AWS.

    These data consist of processed data from NWS NEXRAD, including:
    * Single elevation moment data
    * Estimated precipitation data
    * Feature detection (e.g. tornadoes, mesocyclones, hail)


Access data from the NEXRAD Level 2 archive in AWS.

    These data consist of complete volumes (i.e. multiple elevation cuts) from NWS NEXRAD.


Access data from the NOAA GOES archive in AWS.

    This consists of individual GOES image files stored in netCDF format, across a variety
    of sectors, bands, and modes.


Access data from the NOAA/CIRA Machine-Learning Weather Prediction archive in AWS.

    This consists of individual model runs stored in netCDF format, across a variety
    a collection of models (Aurora, FourCastNet, GraphCast, Pangu) and initial conditions
    (GFS or IFS).


r"""Handle reading the NEXRAD Level 2 data and its various messages.

    This class attempts to decode every byte that is in a given data file.
    It supports both external compression, as well as the internal BZ2
    compression that is used.

    Attributes
    ----------
    stid : str
        The ID of the radar station
    dt : `~datetime.datetime`
        The date and time of the data
    vol_hdr : `collections.namedtuple`
        The unpacked volume header
    sweeps : list[tuple]
        Data for each of the sweeps found in the file
    rda_status : `collections.namedtuple`, optional
        Unpacked RDA status information, if found
    maintenance_data : `collections.namedtuple`, optional
        Unpacked maintenance data information, if found
    maintenance_data_desc : dict, optional
        Descriptions of maintenance data fields, if maintenance data present
    vcp_info : `collections.namedtuple`, optional
        Unpacked VCP information, if found
    clutter_filter_bypass_map : dict, optional
        Unpacked clutter filter bypass map, if present
    rda : dict, optional
        Unpacked RDA adaptation data, if present
    rda_adaptation_desc : dict, optional
        Descriptions of RDA adaptation data, if adaptation data present

    Notes
    -----
    The internal data structure that things are decoded into is still to be
    determined.


Convert packed integer data into physical units.


Maps packed integers to floats using a scale and offset from the product.


Mapper for digital velocity products.


Mapper for digital spectrum width products.


Mapper for precipitation array products.


Mapper for digital storm precipitation products.


Mapper for digital VIL products.


Mapper for digital echo tops products.


Maps packed integers to floats using a scale and offset from the product.

    Also handles special data flags.


Mapper for hydrometeor classification products.

    Handles assigning string labels based on values.


Mapper for eddy dissipation rate products.


Mapper for legacy products.


r"""Handle reading the wide array of NEXRAD Level 3 (NIDS) product files.

    This class attempts to decode every byte that is in a given product file.
    It supports all the various compression formats that exist for these
    products in the wild.

    Attributes
    ----------
    metadata : dict
        Various general metadata available from the product
    header : `collections.namedtuple`
        Decoded product header
    prod_desc : `collections.namedtuple`
        Decoded product description block
    siteID : str
        ID of the site found in the header, empty string if none found
    lat : float
        Radar site latitude
    lon : float
        Radar site longitude
    height : float
        Radar site height AMSL
    product_name : str
        Name of the product contained in file
    max_range : float
        Maximum kilometer range of the product, taken from the NIDS ICD
    map_data : `DataMapper`
        Class instance mapping data int values to proper floating point values
    sym_block : list, optional
        Any symbology block packets that were found
    tab_pages : list, optional
        Any tabular pages that were found
    graph_pages : list, optional
        Any graphical pages that were found

    Notes
    -----
    The internal data structure that things are decoded into is still to be
    determined.


Handle XDR-formatted Level 3 NEXRAD products.


GEMPAK file type.


Data management library data types.


GRIB packing type.


Base class for GEMPAK files.

    Reads ubiquitous GEMPAK file headers (i.e., the data management portion of
    each file).


Subclass of GempakFile specific to GEMPAK gridded data.


Subclass of GempakFile specific to GEMPAK sounding data.


Subclass of GempakFile specific to GEMPAK surface data.


Look up station information from multiple sources.

    This class follows the `Mapping` protocol with station ID as the key. This makes it
    possible to e.g. iterate over all locations and get all of a certain criteria:

    >>> import metpy.io
    >>> conus_stations = [s for s in metpy.io.station_info if s.startswith('K')]
    >>> conus_stations[:3]
    ['KEET', 'K8A0', 'KALX']


Parse bytes using :class:`Struct` but provide named fields.


Parse bytes using :class:`Struct` but provide named fields using dictionary access.


Map values to specific strings.


Breaks an integer into a specified number of True/False bits.


Convert an integer to a string for each bit.


Use a Struct as a callable to unpack a bunch of bytes as a list.


Holds bytes from a buffer to simplify parsing and random access.


r"""Represents projection values in GINI files.


A class that handles reading the GINI format satellite images from the NWS.

    This class attempts to decode every byte that is in a given GINI file.

    Notes
    -----
    The internal data structures that things are decoded into are subject to change.


Entry point for direct reading of GINI data into Xarray.


Map integer values to font code points.


Provides validation of attribute names when set by user.


Provides modification layer on HasTraits for declarative classes.


Collects panels and set complete figure related settings (e.g., size).


Set figure related elements for an individual panel.

    Parameters that need to be set include collecting all plotting types
    (e.g., contours, wind barbs, etc.) that are desired to be in a given panel.
    Additionally, traits can be set to plot map related features (e.g., coastlines, borders),
    projection, graphics area, and title.


Represent common traits for subsetting data.


The highest level class related to plotting 2D data.

    This class collects all common methods no matter whether plotting a scalar variable or
    vector. Primary settings common to all types of 2D plots include those for data subsets.


Defines the common elements of 2D scalar plots for single scalar value fields.

    Most of the other traits here are for one or more of the specific plots. Currently this
    allows too many options for `ContourPlot` since it does not user image_range, for
    example. Similar issues for `ImagePlot` and `FilledContourPlot`.


Represents common contour traits.


Represent common colorfill traits.


Make raster image using `~matplotlib.pyplot.imshow` for satellite or colored image.


Make contour plots by defining specific traits.


Make color-filled contours plots by defining appropriate traits.


Make raster plots by defining relevant traits.


Defines common elements for 2D vector plots.

    This class collects common elements including the field trait, which is a tuple argument
    accepting two strings, for plotting 2D vector fields.


Make plots of wind barbs on a map with traits to refine the look of plotted elements.


The highest level class related to plotting observed surface and upperair data.

    This class collects all common methods no matter whether plotting a upper-level or
    surface data using station plots.

    List of Traits:
      * level
      * time
      * fields
      * locations (optional)
      * time_window (optional)
      * formats (optional)
      * colors (optional)
      * plot_units (optional)
      * vector_field (optional)
      * vector_field_color (optional)
      * vector_field_length (optional)
      * vector_plot_units (optional)
      * reduce_points (optional)
      * fontsize (optional)


Plot collections of Shapely objects and customize their appearance.


Plot Surface Analysis Features.

    This class visualizes Surface Analysis features, including the parsed WPC Surface
    Analysis bulletins processed by the `parse_wpc_surface_bulletin()` function.


A simple interface to MetPy-included shapefiles.


Fail if a CartoPy attribute is accessed.


Handle parsing CF projection metadata.


Perform Skew transform for Skew-T plotting.

    This works in pixel space, so is designed to be applied after the normal plotting
    transformations.


r"""Make x-axis ticks for Skew-T plots.

    This class adds to the standard :class:`matplotlib.axis.XTick` dynamic checking
    for whether a top or bottom tick is actually within the data limits at that part
    and draw as appropriate. It also performs similar checking for gridlines.


r"""Make an x-axis that works properly for Skew-T plots.

    This class exists to force the use of our custom :class:`SkewXTick` as well
    as provide a custom value for interval that combines the extents of the
    upper and lower x-limits from the axes.


r"""Make a set of axes for Skew-T plots.

    This class handles registration of the skew-xaxes as a projection as well as setting up
    the appropriate transformations. It also makes sure we use our instances for spines
    and x-axis: :class:`SkewSpine` and :class:`SkewXAxis`. It provides properties to
    facilitate finding the x-limits for the bottom and top of the plot as well.


r"""Make Skew-T log-P plots of data.

    This class simplifies the process of creating Skew-T log-P plots in
    using matplotlib. It handles requesting the appropriate skewed projection,
    and provides simplified wrappers to make it easy to plot data, add wind
    barbs, and add other lines to the plots (e.g. dry adiabats)

    Attributes
    ----------
    ax : `matplotlib.axes.Axes`
        The underlying Axes instance, which can be used for calling additional
        plot functions (e.g. `axvline`)


r"""Make Emagram plots of data.

    Emagram plots are T log-P thermodynamic diagrams. They differ from SkewT
    in that the T axis is not skewed. This class is derived from the SkewT class and
    has the same capabilities for plotting data, wind barbs, dry and saturated
    adiabats, and mixing ratio lines.

    Attributes
    ----------
    ax : `matplotlib.axes.Axes`
        The underlying Axes instance, which can be used for calling additional
        plot functions (e.g. `axvline`)


r"""Make a hodograph of wind data.

    Plots the u and v components of the wind along the x and y axes, respectively.

    This class simplifies the process of creating a hodograph using matplotlib.
    It provides helpers for creating a circular grid and for plotting the wind as a line
    colored by another value (such as wind speed).

    Attributes
    ----------
    ax : `matplotlib.axes.Axes`
        The underlying Axes instance used for all plotting


Handle plotting a collection of text.

    Text Collection plots text with a collection of similar properties: font, color,
    and an offset relative to the x,y data location.


Make a standard meteorological station plot.

    Plots values, symbols, or text spaced around a central location. Can also plot wind
    barbs as the center of the location.


r"""Make a layout to encapsulate plotting using `StationPlot`.

    This class keeps a collection of offsets, plot formats, etc. for a parameter based
    on its name. This then allows a dictionary of data (or any object that allows looking
    up of arrays based on a name) to be passed to `plot()` to plot the data all at once.

    See Also
    --------
    StationPlot


r"""Different plotting types for the layout.

        Controls how items are displayed (e.g. converting values to symbols).


Provide base functionality for plotting fronts as a patheffect.

    These are plotted as symbol markers tangent to the path.


Provide base functionality for plotting strengthening fronts as a patheffect.

    These are plotted as symbol markers tangent to the path.


Provide base functionality for plotting weakening fronts as a patheffect.

    These are plotted as symbol markers tangent to the path.


A line-based PathEffect which draws a path with a scalloped style.

    The spacing, length, and side of the scallops can be controlled. This implementation is
    based off of :class:`matplotlib.patheffects.TickedStroke`.


Draw a path as a cold front, with (default blue) pips/triangles along the path.


Draw a path as a strengthening cold.


Draw a path as a weakening cold front.


Draw a path as a dryline with (default brown) scallops along the path.


Draw a path as a warm front with (default red) scallops along the path.


Draw a path as a strengthening warm front.


Draw a path as a weakening warm front.


Draw an occluded front with (default purple) pips and scallops along the path.


Draw a strengthening occluded front.


Draw a weakening occluded front.


A line-based PathEffect which draws a path with a sawtooth-wave style.

    This line style is frequently used to represent a ridge axis.


Squall line path effect.


Draw a stationary front as alternating cold and warm front segments.


Draw a strengthening stationary front.


Draw a weakening stationary front..


r"""Manages the collection of color tables.

    Provides access to color tables, read collections of files, and generates
    matplotlib's Normalize instances to go with the colortable.


Visit nodes of the AST looking for violations.


Flake8 plugin class to check MetPy style/best practice.


Benchmark moist thermo functions in time using Airspeed Velocity and xarray datasets.

    Uses ASV's benchmarking format to load in data and run benchmarks to measure time
     performance


 Plot a time series of meteorological data from a particular station as a
    meteogram with standard variables to visualize, including thermodynamic,
    kinematic, and pressure. The functions below control the plotting of each
    variable.
    TO DO: Make the subplot creation dynamic so the number of rows is not
    static as it is currently.


 Work in progress.
    TODO: merge James' code


    An object that contains photometric data and analysis results.

    Attributes:
        x(float list): time data.
        y(float list): magnitude or flux data.
        yerr(float list): error or uncertainty in each y-data.
        period(float): detected period of the object. None by default.
        period_err(float): estimated uncertainty in detected period.
        amplitude(float): peak-to-peak ydata range (not best-fit function).
        amplitude_err(float): quadrature of yerr for y.max() and y.min().
        label(str): label for the photdata object.
        band(str): name of the filter for the photometric data.
        epoch(float): time of maxima, estimated from the datapoint nearest to a maximum
        meanmag(float): mean magnitude (assuming y-value is in mag)
        multiprocessing(bool): toggles multiprocessing option.


 An object that generates and plots the periodogram.

    Attributes:
        photdata (PIPS.photdata): the photdata object that contains the photometric data to construct periodograms.
        periods (numpy array): a list of period values at which the periodogram is evaluated.
        power (numpy array): a list of periodogram values.
        kwargs (dict): arguments to be passed to specific methods of periodograms.
        mode (str): the periodogram mode. Internal flagging purpose only.


    visualization tool to help statistical analysis.

    variables:

    functions:
        to_pandas(photdata_array)
        plot_scatter(df,xcol,ycol,args=None)
        plot_periodogram(photdata_array)
        plot_amplitude_spectrum(df)
        plot_OC(df)


    A descriptor to wrap around metadata dictionaries.

    Lets classes reference self.x instead of self.metadata['x'],


    Compute properties of structures in a position-position-velocity (PPV)
    cube.

    Parameters
    ----------
    structure : :class:`~astrodendro.structure.Structure` instance
        The structure to compute the statistics for
    metadata : dict
         Key-value pairs of metadata


    Compute properties of structures in a position-position (PP) cube.

    Parameters
    ----------
    structure : :class:`~astrodendro.structure.Structure` instance
        The structure to compute the statistics for
    metadata : dict
         Key-value pairs of metadata


    Apply the spectral clustering to find the best
    cloud segmentation out from a dendrogram.

    Parameters
    -----------

    dendrogram: 'astrodendro.dendrogram.Dendrogram' instance
        The dendrogram to clusterize.

    catalog: 'astropy.table.table.Table' instance
        A catalog containing all properties of the dendrogram
        structures. Generally generated with ppv_catalog module.

    header: 'astropy.io.fits.header.Header' instance
        The header of the fits data the dendrogram was
        generated from. Necessary to obtain the assignment cubes.

    criteria: list of strings
        Clustering criteria referred to the structure properties
        in the catalog (default ['volume', 'luminosity']).

    user_k: int
        The expected number of clusters, if not provided
        it will be guessed automatically through the eigenvalues
        of the unsmoothed affinity matrix.

    user_ams: numpy array
        User provided affinity matrix. Whether this is not
        furnish it is automatically generated through the
        volume and/or luminosity criteria.

    user_scalpars: list of floats
        User-provided scaling parameters to smooth the
        affinity matrices.

    user_iter: int
        User-provided number of k-means iterations.

    save_isol_leaves: bool
        Consider the isolated leaves (without parent)
        as individual 'clusters'. Useful for low
        resolution data where the beam size
        corresponds to the size of a Giant
        Molecular Cloud.

    save_clust_leaves: bool
        Consider unclustered leaves as individual
        'clusters'. This keyword will not include
        the isolated leaves without parents.

    save_all_leaves: bool
        Trigger both save_isol_leaves and
        save_clust_leaves.

    save_branches: bool
        Retain all isolated branches usually discarded
        by the cluster analysis.

    save_all: bool
        Trigger all save_isol_leaves,
        save_clust_leaves, and save_branches.

    rms: int or float
        Noise level of the observation. Necessary to
        calculate the scaling parameter above a certain
        signal-to-noise ratio.

    s2nlim: int or float
        Signal-to-noise limit above which the
        scaling parameter is calculated. Needed
        only if rms is not np.nan.

    blind: bool
        Show the affinity matrices.
        Matplotlib required.

    locscaling: bool
        Smooth the affinity matrices using a local
        scaling technique. This does not work well ...

    Return
    -------

    clusters: list
        The dendrogram branch indexes corresponding to the
        identified clusters

    catalog: 'astropy.table.table.Table' instance
        The input catalog updated with dendrogram structure
        parent, ancestor, number of leaves, and type
        ('T', trunks or branches without parent; 'B', branches
        with parent; 'L', leaves).

    affmats: numpy array
        The affinity matrices calculated by the algorithm

    escalpars: list
        Estimated scaling parameters for the different
        affinity matrixes

    silhouette: float
        Silhouette of the best cluster configuration

    clusters_asgn: astropy.io.fits.hdu.image.PrimaryHDU
        Assignment cube generated by the 'cluster'-type
        structures.

    trunks_asgn: astropy.io.fits.hdu.image.PrimaryHDU
        Assignment cube generated by the 'trunk'-type
        structures.

    leaves_asgn: astropy.io.fits.hdu.image.PrimaryHDU
        Assignment cube generated by the 'leaf'-type
        structures.


A shim that allows a backend to be swapped at runtime.
    Taken from prysm.mathops with permission from Brandon Dube


dummy class to trick msgpack


########################### GENERAL RAY TRACING METHODS ###########################


    Photo-z Gaussian process, with physical kernel and mean function.

    Args:
        bandCoefAmplitudes: ``numpy.array`` of size (numBands, numCoefs)
            describint the amplitudes of the Gaussians approximating the
            photometric filters.
        bandCoefPositions: ``numpy.array`` of size (numBands, numCoefs)
            describint the positions of the Gaussians approximating the
            photometric filters.
        bandCoefWidths: ``numpy.array`` of size (numBands, numCoefs)
            describint the widths of the Gaussians approximating the
            photometric filters.
        lines_pos: ``numpy.array`` of SED line positions
        lines_width: ``numpy.array`` of SED line widths
        var_C: GP variance for SED continuum correlations.
            Should be a ``float`, preferably between 1e-3 and 1e2.
        var_L: GP variance for SED line correlations.
            Should be a ``float`, preferably between 1e-3 and 1e2.
        alpha_T: GP lengthscale for smoothness of time correlations.
            Should be a ``float`.
        alpha_C: GP lengthscale for smoothness of SED continuum correlations.
            Should be a ``float`, preferably between 1e1 and 1e4.
        alpha_L: GP lengthscale for smoothness of SED line correlations.
            Should be a ``float`, preferably between 1e1 and 1e4.
        redshiftGridGP: redshift grid (array) for computing the GP.
        use_interpolators (Optional): ``boolean`` indicating if the GP
            should be used for all predictions,
            or if an interpolation scheme should be used (default: ``True``)
        lambdaRef (Optional): Pivot space for the SEDs
            (``float``, default: ``4.5e3``)
        g_AB (Optional): AB photometric normalization constant
            (``float``, default: ``1.0``)


    Photo-z Gaussian process, with physical kernel and mean function.

    Args:
        f_mod_interp: grid of interpolators of size (num templates, num bands)
            called as ``f_mod_interp[it, ib](z)``
        bandCoefAmplitudes: ``numpy.array`` of size (numBands, numCoefs)
            describint the amplitudes of the Gaussians approximating the
            photometric filters.
        bandCoefPositions: ``numpy.array`` of size (numBands, numCoefs)
            describint the positions of the Gaussians approximating the
            photometric filters.
        bandCoefWidths: ``numpy.array`` of size (numBands, numCoefs)
            describint the widths of the Gaussians approximating the
            photometric filters.
        lines_pos: ``numpy.array`` of SED line positions
        lines_width: ``numpy.array`` of SED line widths
        var_C: GP variance for SED continuum correlations.
            Should be a ``float`, preferably between 1e-3 and 1e2.
        var_L: GP variance for SED line correlations.
            Should be a ``float`, preferably between 1e-3 and 1e2.
        alpha_C: GP lengthscale for smoothness of SED continuum correlations.
            Should be a ``float`, preferably between 1e1 and 1e4.
        alpha_L: GP lengthscale for smoothness of SED line correlations.
            Should be a ``float`, preferably between 1e1 and 1e4.
        redshiftGridGP: redshift grid (array) for computing the GP.
        use_interpolators (Optional): ``boolean`` indicating if the GP
            should be used for all predictions,
            or if an interpolation scheme should be used (default: ``True``)
        lambdaRef (Optional): Pivot space for the SEDs
            (``float``, default: ``4.5e3``)
        g_AB (Optional): AB photometric normalization constant
            (``float``, default: ``1.0``)


Power law luminosity function


Double Schechter luminosity function


    Mean function of photoz GP, based on a library of templates.

    Args:
        f_mod_interp: grid of interpolators of size (num templates, num bands)
            called as ``f_mod_interp[it, ib](z)``


    (Deprecated)
    Mean function of photoz GP, based on a power law model.