        Calls the model wrapped in this :class:`~ModelLink` subclass at
        emulator iteration `emul_i` for model parameter values `par_set` and
        returns the data points corresponding to `data_idx`.

        This method is called with solely keyword arguments.

        This is an abstract method and must be overridden by the
        :class:`~ModelLink` subclass.

        Parameters
        ----------
        %(emul_i)s
        par_set : dict of :class:`~numpy.float64`
            Dict containing the values for all model parameters corresponding
            to the requested model realization(s). If model is single-called,
            dict item is formatted as ``{par_name: par_val}``. If multi-called,
            it is formatted as ``{par_name: [par_val_1, par_val_2, ...,
            par_val_n]}``.
        data_idx : list of tuples
            List containing the user-defined data point identifiers
            corresponding to the requested data points.

        Returns
        -------
        data_val : 1D or 2D array_like or dict
            Array containing the data values corresponding to the requested
            data points generated by the requested model realization(s). If
            model is multi-called, `data_val` is of shape ``(n_sam, n_data)``.
            If dict, it has the identifiers in `data_idx` as its keys with
            either scalars or 1D array_likes as its values.

        Note
        ----
        If this model is multi-called, then the parameter sets in the provided
        `par_set` dict will be sorted in order of parameter name (e.g., sort on
        first parameter first, then on second parameter, etc.).


    Converts the provided `model_data` into a full data dict, taking into
    account all formatting options, and returns it.

    This function can be used externally to check how the provided `model_data`
    would be interpreted when provided to the
    :class:`~prism.modellink.ModelLink` subclass. Its output can be used for
    the 'model_data' input argument.

    Parameters
    ----------
    model_data : array_like, dict or str
        Anything that can be converted to a dict that provides model data
        information.

    Returns
    -------
    data_dict : dict
        Dict with the provided `model_data` converted to its full format.


    Converts the provided `model_parameters` into a full parameters dict,
    taking into account all formatting options, and returns it.

    This function can be used externally to check how the provided
    `model_parameters` would be interpreted when provided to the
    :class:`~prism.modellink.ModelLink` subclass. Its output can be used for
    the 'model_parameters' input argument.

    Parameters
    ----------
    model_parameters : array_like, dict or str
        Anything that can be converted to a dict that provides model parameters
        information.

    Returns
    -------
    par_dict : dict
        Dict with the provided `model_parameters` converted to its full format.


int: Polynomial order used in this :obj:`~PolyLink` instance.


        Sets up the projection viewing area dock widget after it has been
        initialized.

        This function is mainly responsible for enabling the
        :class:`~prism._gui.widgets.OverviewDockWidget` to properly interact
        and control the projection figures that have been drawn.


        Saves the current view of the viewing area to file.

        %(qt_slot)s


        Special :meth:`~PyQt5.QtWidgets.QWidget.closeEvent` event that
        automatically performs some clean-up operations before the viewing area
        closes.


        Creates the top-level toolbar of the viewing area, primarily used for
        manipulating the area subwindows.


        Sets up the main window after it has been initialized.

        This function is mainly responsible for initializing all other widgets
        that are required to make the GUI work, and connecting them together.


        Creates the top-level menubar of the main window.

        Other widgets can modify this menubar to add additional actions to it.


        Creates the bottom-level statusbar of the main window, primarily used
        for displaying extended descriptions of actions.


        Displays a small section with information about the GUI.

        %(qt_slot)s


        Opens the API reference documentation of the GUI in a webbrowser.

        %(qt_slot)s


        Special :meth:`~PyQt5.QtWidgets.QWidget.closeEvent` event that
        automatically performs some clean-up operations before the main window
        closes.


        Sets the requested :class:`~prism._projection.Projection` attribute
        `name` to `value` on all ranks.


        Calls the requested :class:`~prism._projection.Projection` attribute
        `name` using the provided `args` and `kwargs` on the controller rank.


        Calls the requested :class:`~prism._projection.Projection` attribute
        `name` using the provided `args` and `kwargs` on all ranks.


        Creates and shows a dialog containing the output of the
        :meth:`~prism.Pipeline.details` method for all emulator iterations.

        %(qt_slot)s


        Sets up the exception dialog after it has been initialized.

        This function is mainly responsible for gathering all required
        information; formatting it; and drawing the dialog.


Formats the exception provided during initialization and returns it.


Formats the traceback provided during initialization and returns it.


        Creates a special box for the exception dialog that contains the
        traceback information and returns it.


        Toggles the visibility of the traceback box and updates the dimensions
        of the exception dialog accordingly.

        %(qt_slot)s


        Updates the dimensions of the exception dialog depending on its current
        state (traceback box visibility).


        Sets up the overview list after it has been initialized.

        This function is mainly responsible for creating the list; adding the
        items to it; and setting some properties.

        Parameters
        ----------
        hcubes_list : list of str
            List of projection hypercube names that must be used to initialize
            this overview list with.
        statustip : str
            The statustip that will be displayed in the statusbar whenever this
            overview list is hovered.
        context_menu : function
            The function that must be called whenever the context menu is
            requested.
        activated : function
            The function that must be called whenever an item in this overview
            list is activated. This corresponds to the default action.


        Sets up the progress dialog after it has been initialized.

        This function is mainly responsible for preparing the dialog to be
        opened and the `func` function to be executed.

        Parameters
        ----------
        label : str
            The label that is used as the description of what operation is
            currently being executed.
        func : function
            The function that must be called iteratively using the arguments
            provided in `iterables`.
        iterables : positional arguments
            All iterables that must be used to call `func` with.


        Opens the progress dialog and starts the execution of the requested
        operation.

        Returns
        -------
        result : bool
            Whether or not the operations ended successfully, which can be used
            by other functions to determine if it should continue.


Qt slot that raises a provided exception.


        Terminates all currently running threads besides the main thread (on
        all MPI ranks) and returns control to the main thread.

        This function is the sole way to abort the operation.

        %(qt_slot)s


        Provides the global system tracer function that automatically
        terminates this thread if its :attr:`~killed` attribute is set to
        *True*.


Executes the operations whenever this thread is started.


    All workers defined in the provided `pipeline_obj` create a
    :obj:`~TracedWorkerThread` object and use it to listen for calls from the
    controller rank.

    Parameters
    ----------
    pipeline_obj : :obj:`~prism.Pipeline` object
        The :class:`~prism.Pipeline` object all created worker threads must
        use. This is required for entering the proper worker mode.


    Creates an instance of the :class:`~ExceptionDialog` class and shows it.

    Parameters
    ----------
    parent : :obj:`~PyQt5.QtWidgets.QWidget` object or None
        The parent widget for this dialog or *None* for no parent.

    Optional
    --------
    args : positional arguments
        The positional arguments that must be passed to the constructor of
        the :class:`~prism._gui.widgets.helpers.ExceptionDialog` class.
    kwargs : keyword arguments
        The keyword arguments that must be passed to the constructor of the
        :class:`~prism._gui.widgets.helpers.ExceptionDialog` class.


        Special :meth:`~PyQt5.QtCore.QObject.childEvent` event that
        automatically connects the default modified signal of any widget that
        becomes a child of this widget.


        Connect the default modified signal of the provided `box` to this
        widget's :attr:`~modified` signal.


        Special :meth:`~PyQt5.QtWidgets.QWidget.closeEvent` event that
        automatically performs some clean-up operations before the overview
        dock widget closes.


        Sets up the projection overview dock widget after it has been
        initialized.

        This function is mainly responsible for creating the different overview
        lists and menus that allow the user to manipulate projection figures.


        Creates the context (right-click) menu for the 'Drawn' overview list.

        This menu contains all actions that are available for drawn projection
        figures.


        Shows the 'Drawn' context menu, giving the user access to its actions.

        %(qt_slot)s


        Creates the context (right-click) menu for the 'Available' overview
        list.

        This menu contains all actions that are available for created (but not
        drawn) projection figures.


        Shows the 'Available' context menu, giving the user access to its
        actions.

        %(qt_slot)s


        Creates the context (right-click) menu for the 'Unavailable' overview
        list.

        This menu contains all actions that are available for non-existing
        projection figures.


        Shows the 'Unavailable' context menu, giving the user access to its
        actions.

        %(qt_slot)s


        Retrieves the projection figures requested in the provided `list_items`
        and shows them in the projection viewing area.

        %(qt_slot)s

        %(optional)s


        Retrieves the projection figures requested in the provided `list_items`
        and closes their :obj:`~matplotlib.figure.Figure` objects.

        %(qt_slot)s

        %(optional)s


        Retrieves the projection figures requested in the provided `list_items`
        and draws them, creating their :class:`~matplotlib.figure.Figure`
        instances.

        If the `auto_show` option is *True*, drawn figures will be shown
        automatically as well.

        %(qt_slot)s

        %(optional)s


        Draws the projection figure requested in the provided `list_item`,
        creating its :class:`~matplotlib.figure.Figure` instance.

        This function is used iteratively by :meth:`~draw_projection_figures`.

        Parameters
        ----------
        list_item : :obj:`~PyQt5.QtWidgets.QListWidgetItem` object
            The item that contains the requested projection figure.


        Retrieves the projection figures requested in the provided `list_items`
        and delete them, permanently removing their corresponding projection
        data.

        %(qt_slot)s

        %(optional)s
        skip_warning : bool. Default: False
            Whether or not to skip showing the warning asking the user if they
            are sure they want to permanently delete all items in `list_items`.
            If *True*, the answer is taken to be *True*.


        Retrieves the projection figures requested in the provided `list_items`
        and creates them, calculating their corresponding projection data.

        %(qt_slot)s

        %(optional)s


        Creates the projection figure requested in the provided `list_item`,
        calculating its projection data.

        This function is used iteratively by
        :meth:`~create_projection_figures`.

        Parameters
        ----------
        list_item : :obj:`~PyQt5.QtWidgets.QListWidgetItem` object
            The item that contains the requested projection figure.


        Retrieves the projection figures requested in the provided `list_items`
        and saves their :obj:`~matplotlib.figure.Figure` objects.

        %(qt_slot)s

        %(optional)s
        choose : bool. Default: False
            Whether or not the user is allowed to choose where the projection
            figure is saved to.
            If *False*, it uses the default filename as defined by
            :meth:`~prism.Pipeline._Projection__get_fig_path`.


        Retrieves the projection figures requested in the provided `list_items`
        and saves their :obj:`~matplotlib.figure.Figure` objects, asking the
        user where to save each one.

        This function basically calls :meth:`~save_projection_figures` with
        `choose` set to *True*.

        %(qt_slot)s

        %(optional)s


        Retrieves the projection figures requested in the provided `list_items`
        and redraws them, closing and recreating their
        :obj:`~matplotlib.figure.Figure` objects.

        This function is basically a combination of
        :meth:`~close_projection_figures` and :meth:`~draw_projection_figures`.

        %(qt_slot)s

        %(optional)s


        Retrieves the projection figures requested in the provided
        `list_items`, draws their :obj:`~matplotlib.figure.Figure` objects and
        saves them afterward.

        This function is basically a combination of
        :meth:`~draw_projection_figures` and :meth:`~save_projection_figures`.

        %(qt_slot)s

        %(optional)s


        Retrieves the projection figures requested in the provided `list_items`
        and recreates them, permanently removing their corresponding projection
        data and recalculating it.

        This function is basically a combination of
        :meth:`~delete_projection_figures` and
        :meth:`~create_projection_figures`.

        %(qt_slot)s

        %(optional)s


        Retrieves the projection figures requested in the provided
        `list_items`, calculates their projection data and draws their
        :obj:`~matplotlib.figure.Figure` objects afterward.

        This function is basically a combination of
        :meth:`~create_projection_figures` and
        :meth:`~draw_projection_figures`.

        %(qt_slot)s

        %(optional)s


        Retrieves the projection figures requested in the provided
        `list_items`, calculates their projection data, draws their
        :obj:`~matplotlib.figure.Figure` objects and saves them afterward.

        This function is basically a combination of
        :meth:`~create_projection_figures`; :meth:`~draw_projection_figures`
        and :meth:`~save_projection_figures`.

        %(qt_slot)s

        %(optional)s


        Retrieves the projection figure requested in the provided `list_item`,
        gathers its properties and shows a details dialog listing them.

        This function is used for projections in the 'Drawn' list.

        %(qt_slot)s

        %(optional)s


        Retrieves the projection figure requested in the provided `list_item`,
        gathers its properties and shows a details dialog listing them.

        This function is used for projections in the 'Available' list.

        %(qt_slot)s

        %(optional)s


        Creates and shows a details dialog for the projection figure requested
        in the provided `list_item`.

        Parameters
        ----------
        list_item : :obj:`~PyQt5.QtWidgets.QListWidgetItem` object
            The item that contains the requested projection figure.


        Creates a progress dialog with the given `label`, and executes the
        requested `func` using the provided `iterables`.

        Depending on the current settings, this function will either create a
        :obj:`~prism._gui.widgets.helpers.ThreadedProgressDialog` object that
        allows the user to abort the operation (but is slower), or a static
        dialog that cannot be interrupted.

        Parameters
        ----------
        label : str
            The label that is used as the description of what operation is
            currently being executed.
        func : function
            The function that must be called iteratively using the arguments
            provided in `iterables`.
        iterables : positional arguments
            All iterables that must be used to call `func` with.

        Returns
        -------
        result : bool
            Whether or not the operations ended successfully, which can be used
            by other functions to determine if it should continue.


        Sets up the color box entry after it has been initialized.

        This function is mainly responsible for creating the color wheel and
        color label, that allow the user to quickly cycle through different
        color options.


        Creates a special label that shows the currently selected or hovered
        color, and returns it.


        Creates a combobox that holds all default colors accepted by matplotlib
        and returns it.


        Converts a provided matplotlib color `color` to a
        :obj:`~PyQt5.QtGui.QColor` object.

        Parameters
        ----------
        color : str
            The matplotlib color that must be converted.
            If `color` is a float string, an error will be raised, as Qt5 does
            not accept those.

        Returns
        -------
        qcolor : :obj:`~PyQt5.QtGui.QColor` object
            The instance of the :class:`~PyQt5.QtGui.QColor` class that
            corresponds to the provided `color`.


        Converts a provided :obj:`~PyQt5.QtGui.QColor` object `color` to a
        matplotlib color.

        Parameters
        ----------
        qcolor : :obj:`~PyQt5.QtGui.QColor` object
            The instance of the :class:`~PyQt5.QtGui.QColor` class must be
            converted to a matplotlib color.

        Returns
        -------
        color : str
            The corresponding matplotlib color.
            The returned `color` is always written in HEX.


        Creates a :obj:`~PyQt5.QtGui.QPixmap` object consisting of the given
        `color` with the provided `size`.

        Parameters
        ----------
        color : str
            The matplotlib color that must be used for the pixmap.
        size : tuple
            The width and height dimension values of the pixmap to be created.

        Returns
        -------
        pixmap : :obj:`~PyQt5.QtGui.QPixmap` object
            The instance of the :class:`~PyQt5.QtGui.QPixmap` class that was
            created from the provided `color` and `size`.


        Shows the colorwheel picker dialog to the user, allowing for any color
        option to be selected.

        %(qt_slot)s


        Creates a :obj:`~PyQt5.QtGui.QIcon` object of the given `cmap` with the
        provided `size`.

        Parameters
        ----------
        cmap : :obj:`~matplotlib.colors.Colormap` object or str
            The colormap for which an icon needs to be created.
        size : tuple
            A tuple containing the width and height dimension values of the
            icon to be created.

        Returns
        -------
        icon : :obj:`~PyQt5.QtGui.QIcon` object
            The instance of the :class:`~PyQt5.QtGui.QIcon` class that was
            created from the provided `cmap` and `size`.


        Qt slot that checks a provided `cmap` and shows an error message if
        `cmap` is a terrible colormap.


        Sets up the non-standard default box entry after it has been
        initialized.

        This function is mainly responsible for creating the type combobox and
        allowing for different field boxes to be used for different value
        types.


        Creates a field box for the provided type `value_type` and replaces the
        current field box with it.

        %(qt_slot)s

        Parameters
        ----------
        value_type : {'bool'; 'float'; 'int'; 'str'}
            The string that defines what type of field box is requested.


Creates the field box for values of type 'bool' and returns it.


Creates the field box for values of type 'float' and returns it.


Creates the field box for values of type 'int' and returns it.


Creates the field box for values of type 'str' and returns it.


        Special :meth:`~PyQt5.QtWidgets.QWidget.closeEvent` event that makes
        sure that all dialogs will be closed related to the options menu, and
        discards all changes made.


        Sets up the options dialog after it has been initialized.

        This function is mainly responsible for initializing all option entries
        that the GUI has, and creating a database for them. It also creates the
        layout of the options dialog.


        Creates a new :class:`~OptionsEntry` instance, using the provided
        `name`, `box` and `default`, and registers it in the options dialog.

        Parameters
        ----------
        name : str
            The name of this options entry.
        box : :obj:`~PyQt5.QtWidgets.QWidget` object
            The widget that will hold the values of this entry.
        default : object
            The default value of this entry.


        Creates a new options tab with the given `name` and adds the groups
        defined in `groups_list` to it.

        This function acts as a base function called by `create_tab_`
        functions.

        Parameters
        ----------
        name : str
            The name of this options tab.
        groups_list : list of str
            A list containing the names of all option groups that need to be
            added to this tab.

        Returns
        -------
        tab : :obj:`~PyQt5.QtWidgets.QWidget` object
            The created options tab.
        name : str
            The name of this options tab as provided with `name`.
            This variable is mainly returned such that it is easier to pass tab
            names between functions.


        Creates a new option group with the given `name` and adds the options
        defined in `options_list` to it.

        This function acts as a base function called by `create_group_`
        functions.

        Parameters
        ----------
        name : str
            The name of this option group.
        options_list : list of str
            A list containing the names of all options that need to be added to
            this group.

        Returns
        -------
        group : :obj:`~PyQt5.QtWidgets.QGroupBox` object
            The created option group.


Creates the 'General' tab and returns it.


Creates the 'Appearance' tab and returns it.


Creates the 'Projection grid' group and returns it.


Creates the 'Projection keywords' group and returns it.


Creates the 'Interface' group and returns it.


Creates the 'Fonts' group and returns it.


        Creates the 'text_fonts' option and returns it.

        This option allows for the fonts used in the GUI to be modified.


        Creates the 'dpi' option and returns it.

        This option allows for the DPI used in the GUI to be modified.


        Creates the 'auto_tile' option and returns it.

        This option sets whether the projection subwindows are automatically
        tiled.


        Creates the 'auto_show' option and returns it.

        This option sets whether the projection subwindows are automatically
        shown whenever created.


        Creates the 'progress_dialog' option and returns it.

        This option sets whether a threaded progress dialog is used for some
        operations.


        Creates the 'proj_res' option and returns it.

        This option sets the value of the 'proj_res' projection parameter.


        Creates the 'proj_depth' option and returns it.

        This option sets the value of the 'proj_depth' projection parameter.


        Creates the 'align' option and returns it.

        This option sets the value of the 'align' projection parameter.


        Creates the 'show_cuts' option and returns it.

        This option sets the value of the 'show_cuts' projection parameter.


        Creates the 'smooth' option and returns it.

        This option sets the value of the 'smooth' projection parameter.


        Creates the 'use_par_space' option and returns it.

        This option sets the value of the 'use_par_space' projection parameter.


        Creates the 'full_impl_rng' option and returns it.

        This option sets the value of the 'full_impl_rng' projection parameter.


        Creates the 'kwargs_dicts' option and returns it.

        This option allows for the
        :class:`~prism._gui.widgets.preferences.KwargsDictDialog` to be shown
        to the user.
        This dialog is able to set the values of all 'XXX_kwargs' projection
        parameters.


        Creates the button box that is shown at the bottom of the options
        dialog and registers it in the provided `window_layout`.


        Saves all current values of all option entries.

        Option entries that affect projection parameters are automatically
        modified as well.

        %(qt_slot)s


        Qt slot that enables the save button at the bottom of the options
        dialog.
        The save button is enabled if at least one change has been made to any
        option entry.


        Qt slot that disables the save button at the bottom of the options
        dialog.
        The save button is disabled whenever no changes have been made to any
        option entry.


        Resets the saved and current values of all option entries back to their
        default values.

        %(qt_slot)s


        Discards the current values of all option entries and sets them back to
        their saved values.

        %(qt_slot)s


        Sets up the options entry after it has been initialized.

        This function is mainly responsible for making sure that the current
        and saved values of this entry are set to its default value.


str: The name of this options entry.


        :obj:`~PyQt5.QtWidgets.QWidget` object: The widget box that contains
        this options entry.


object: The default value of this options entry.


object: The currently saved value of this options entry.


Qt slot that saves the current value of this options entry.


        Qt slot that resets the current value of this options entry to its
        default value.


        Qt slot that discards the current value and sets it back to its saved
        value.


        Sets up the box layout after it has been initialized.

        This function is mainly responsible for initializing the
        :class:`~KwargsDictDialog` class and binding it.


        Adds a new kwargs dict to the box layout, by calling the
        :meth:`~KwargsDictDialog.add_page` method using the provided `args` and
        `kwargs`.


        Sets up the kwargs dict dialog after it has been initialized.

        This function is mainly responsible for setting up the layout of the
        dialog, and making sure that new kwargs dict pages can be added.


        Initializes a new :obj:`~KwargsDictDialogPage` object with name `name`
        and adds it to this dialog.

        Parameters
        ----------
        name : str
            The name that this kwargs dict page will have.
        option_key : str
            The name of the options entry that this page will create.
            The value of `option_key` must correspond to the name the
            associated dict has in the :meth:`~prism.Pipeline.project` method.
        tooltip : str
            The tooltip that must be used for this kwargs dict page.

        %(optional)s


        Sets up the kwargs dict page after it has been initialized.

        This function is mainly responsibe for creating the layout of the page;
        determining what entry types are available; and preparing for the user
        to add entries.


        Adds a new editable entry to the kwargs dict page, which allows for the
        user to edit the contents of the kwargs dict.

        %(qt_slot)s


        Removes the editable entry associated with the provided `kwargs_box`.

        %(qt_slot)s

        Parameters
        ----------
        kwargs_box : \
            :obj:`~prism._gui.widgets.base_widgets.QW_QEditableComboBox` object
            The combobox that is used for setting the entry type of this entry.


        Qt slot that modifies the field box associated with the provided
        `kwargs_box` to given `entry_type`.

        Parameters
        ----------
        entry_type : str
            The entry type that is requested for the field box.
        kwargs_box : \
            :obj:`~prism._gui.widgets.base_widgets.QW_QEditableComboBox` object
            The combobox that is used for setting the entry type of this entry.


Base function for creating the entry types 'xscale' and 'yscale'.


    For debugging / special-case processing, read previous checksums, and update them with
    current checksums values, then write out the result.


Cleanup after any worker processes which have exited due to reaching
        their specified lifetime.  Returns True if any workers were cleaned up.


Bring the number of pool processes up to the specified number,
        for use after reaping workers which have exited.


Clean up any exited workers and start replacements for them.


Equivalent of `func(*args, **kwds)`.


Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.


Like `imap()` method but ordering of results is arbitrary.


Asynchronous version of `apply()` method.


Helper function to implement map, starmap and their async counterparts.


       Requirement V3.4
       90% filled to g=24, r=23.4 and z=22.5 and 95% and 98% at 0.3/0.6 mag shallower.

       Produces extinction correction magnitude maps for visual inspection

       MARCM stable version, improved from AJR quick hack
       This now included extinction from the exposures
       Uses quicksip subroutines from Boris, corrected
       for a bug I found for BASS and MzLS ccd orientation


       Requirement V3.4
       90% filled to g=24, r=23.4 and z=22.5 and 95% and 98% at 0.3/0.6 mag shallower.

       MARCM
       Makes histogram of predicted magnitudes
       by MonteCarlo from exposures converving fraction of number of exposures
       This produces the histogram for Dustin's processed galaxy depth


Decides if it is in DES footprint


get pixels maps of fwhm min, max and mean


       Requirement v4.1
       z-band image quality will be smaller than 1.3 arcsec FWHM in at least one pass.
       allow to be tested in all bands


       Requirement V3.4
       90% filled to g=24, r=23.4 and z=22.5 and 95% and 98% at 0.3/0.6 mag shallower.

       Produces extinction correction magnitude maps for visual inspection
       MARCM includes min number of exposures
       MARCM stable version, improved from AJR quick hack
       This now included extinction from the exposures
       Uses quicksip subroutines from Boris, corrected
       for a bug I found for BASS and MzLS ccd orientation


    No region > 3deg will be based upon non-photometric observations

    Produces a plot of zero-point variations across the survey to inspect visually
    MARCM It can be extended to check the 3deg later if is necessary


    450 sq deg overlap between all instruments (R3.5)
    14000 sq deg filled  (R3.1)

    MARCM
    Uses healpix pixels projected from ccd to count standing, join and overlap areas
    Produces a map of the overlap
    It can be extended to 3 samples if necessary


       Requirement V4.1: z-band image quality will be smaller than 1.3 arcsec FWHM in at least one pass.

       Produces FWHM maps and histograms for visual inspection

       H-JS's addition to MARCM stable version.
       MARCM stable version, improved from AJR quick hack
       This now included extinction from the exposures
       Uses quicksip subroutines from Boris, corrected
       for a bug I found for BASS and MzLS ccd orientation


       Requirement V4.1: z-band image quality will be smaller than 1.3 arcsec FWHM in at least one pass.

       Produces FWHM maps and histograms for visual inspection

       H-JS's addition to MARCM stable version.
       MARCM stable version, improved from AJR quick hack
       This now included extinction from the exposures
       Uses quicksip subroutines from Boris, corrected
       for a bug I found for BASS and MzLS ccd orientation

       The same as val3p4c_seeing, but this makes only plots without regenerating input files for the plots


    450 sq deg overlap between all instruments (R3.5)
    14000 sq deg filled  (R3.1)

    MARCM
    Reads healpix maps produced by previous runs of say
    fname=val3p4c_depthfromIvar(sample,Nexpmin=1,Nexpmax=500)


fix dtype of a numpy structured array


Combines CCD annotated files


Make imaging maps for each band


make a healpix map given hpix and signal


Combine the imaging maps (.fits) into a hdf5 file


either survey-ccds or ccds-annotated


WARNING copy files from dr4 first so keep prestine
    3 files for each mzls,bass
    sccd_wbool -- survey ccds having original boolean arrays for each cut
    sccd_dr4 -- survey ccds released with dr4 that has incorrect bitmask
    accd_dr4 -- annotated ccds released ...


makes copy of fits file and modifies it
    modify_func -- function that takes hdulist as input, modifies it as desired, and returns it


new data model catalouge and fix all headers
    touch a junk_brickname.txt file when done so can see which bricks finished
    OR
    sanity checks on outputs


    radius in arcsec.
    pixscale: WISE pixel scale in arcsec/pixel;
        make this smaller than 2.75 to oversample.


    if decam:
        O = fits_table('obstatus/decam-tiles_obstatus.fits')
    else:
        O = fits_table('mosaic-tiles_obstatus.fits')


Compute the perplexity and the P-row for a specific value of the precision of a Gaussian distribution.


Performs a binary search to get P-values in such a way that each conditional Gaussian has the same perplexity.


Runs PCA on the NxD array X in order to reduce its dimensionality to no_dims dimensions.


Runs t-SNE on the dataset in the NxD array X to reduce its dimensionality to no_dims dimensions.
    The syntaxis of the function is Y = tsne.tsne(X, no_dims, perplexity), where X is an NxD NumPy array.


    targetwcs: wcs object describing region of interest
    ccds: fits_table object of CCDs

    ccdrad: radius of CCDs, in degrees.  Default 0.17 is for DECam.
    #If None, computed from T.

    Returns: index array I of CCDs within range.


create mask and mask_wise, apply them to all self.data.keys() fields


compute flux/ext, mags, etc., vals automatically masked where self.mask,self.mask_wise true


self.mask should be applied to all self.data.keys() fields


    Draw N samples uniformly within the given RA,Dec box, correctly
    handling the change of scale of RA with respect to Dec.


    Looks in directory 'dirnm' for raw FITS (.fz) images, reporting summary stats on
    file sizes and counts by type.  Works for NERSC directories containing Bok,
    Mosaic, and DECam data.

    *ps*: PlotSequence object for saving plots.


    Converts a string like "20160316" to fiscal year, defined as
    beginning Oct 1 of previous calendar year.


Global initialization routine called by mpi4py when each worker is started.


Splits a string into floats


Determines data values (x0,x1,x2) which will be scaled to (0,noiselum,1)


Adjust the color saturation of an image.  K > 1 boosts it.


r, g, b = data  (3, ny, nx)
    Converts to an Image


Extracts filter from a FITS header


Load R,G,B filenames and options


Determine data scalings
        will sample a (samplesize x samplesize) region of the (centered) core
        make color image of the core as a test if desired


Make color image (in sections)


Written by Gregory Rudnick 27 August 2015

    PURPOSE:

      This function reads in a 2D histogram in color, collapses it
      into 1D and draws each of the colors from the collapsed
      distribution.  It can return many draws.

      The spacing of the histogram is read from the input file, and so
      requires constant linear spacing in color.

    CALLING SEQUENCE

    INPUT PARAMETERS
      filein - input ASCII file with 2D histogram
      ndraw - number of draws

    OPTIONAL INPUT PARAMETERS

      drawplot - if == 1, draw a plot with the two histograms of the
      draws overlaid as well as the collapsed probabilities of the
      input distribution

    OUTPUT PARAMETERS
      gr - list of g-r colors
      rz - list of r-z colors

    EXAMPLES

    PROCEDURE

    REQUIRED PYTHON MODULES
    numpy
    astropy
    matplotlib

    ADDITIONAL REQUIRED MODULES

    NOTES

    assumes constant spacing in color


    Reads the FITS primary header (HDU 0) from the given filename.
    This is just a faster version of fitsio.read_header(fn).


Reads the inverse-variance (weight) map image.


Reads the Data Quality (DQ) mask image.


Return a discrete colormap from the continuous colormap cmap.

        cmap: colormap instance, eg. cm.jet.
        N: number of colors.

    Example
        x = resize(arange(100), (5,100))
        djet = cmap_discretize(cm.jet, 5)
        imshow(x, cmap=djet)


uses Dustin's fits_table() function to read his tractor catalog then returns it as dictionary of np arrays
    his fits_table handles booleans with weird values like 84 for "brick_primary", and converts that to True/False


returns data dict for DECaLS()
	same_keys -- keys that have identical names b/w tractor cat and data dict expected by DeCALS()


return data dict for DECaLS()
	fn -- file name of psql db txt file
	use_cols -- list of column indices to get, first column is 0
	str_cols -- list of column names that should have type str not float


data -- returned by read_from_*
    indicies -- return data but only at these indices


match_type -- m_decam,m_bokmos,u_decam, etc
        new data -- data returend from read_from..() to be concatenated with existing m_decam, etc


deg2 spanned by objects in each data set, lower limit


cat1,2 are tractor catalogue to match objects between


make histograms of nobs so can compare depths of g,r,z between the two catalogues


obj[m_types] -- DECaLS() objects with matched OR unmatched indices


decam,bokmos -- DECaLS() objects with matched OR unmatched indices


finds indices for 0.25 bins, returns bin centers and q25,50,75 percentiles of data_percentile in each bin
    bin_edges: compute percentiles for each sample between bin_edges


return mask for selecting type == all,psf,lrg
    data -- obj['m_decam'].data
    lrg mask -- obje['m_decam'].lrg


obj['m_decam'] is DECaLS() object
    found_by -- 'matched' or 'unmatched'
    type -- all,psf,lrg


using matched sample, plot diff in mags vs. DECAM psf_fwhm in bins
    obj['m_decam'] is DECaLS() object


using matched sample, plot decam psf_fwhm vs. bokmos psf_fwhm
    obj['m_decam'] is DECaLS() object


cm -- NxN array containing the Confusion Matrix values
    ticknames -- list of strings of length == N, column and row names for cm plot


compares MATCHED decam (truth) to bokmos (prediction)
    return 5x5 confusion matrix and colum/row names
    obj[m_decam'] is DECaLS object


d12 is array of distances in degress between matched objects


decam,bokmos are DECaLS() objects matched to decam ra,dec


for a sample that should be distributed as N(mean=0,stddev=1), returns mask for the N that are greater 3 sigma
    low,hi -- minimum and maximum sample values that will be considered


returns mean,std,q25, frac outliers > 3 sigma for n_samples drawn from unit gaussian N(0,1)


return dictionary of stats about the data and stats for a sample that is unit gaussian distributed
    low,hi -- minimum and maximum sample values that will be considered


image requirements grz<=24,23.4,22.5
    compute number density in each bin for each band mag [18,requirement]


    > cp ~/cosmo/staging/mosaicz/MZLS_CP/CP20180102/k4m_180103_040423_ooi_zd_v1.fits.fz /tmp
    > funpack /tmp/k4m_180103_040423_ooi_zd_v1.fits.fz
    > fitsgetext -i /tmp/k4m_180103_040423_ooi_zd_v1.fits -o mosaic-%02i.wcs -a -H
    > cat mosaic-??.wcs > mosaic.wcs
    > for ((i=1; i<=4; i++)); do modhead mosaic.wcs+$i NAXIS2; modhead mosaic.wcs+$i NAXIS2 0; done
    NAXIS2  =                 4079 / Axis length

    NAXIS2  =                 4079 / Axis length

    NAXIS2  =                 4079 / Axis length

    NAXIS2  =                 4061 / Axis length


  1 BRICKID          J
   2 BRICKNAME        8A
   3 OBJID            J
   4 TYPE             4A
   5 RA               D
   6 RA_IVAR          E
   7 DEC              D
   8 DEC_IVAR         E
   9 DECAM_FLUX       6E
  10 DECAM_FLUX_IVAR  6E
  11 DECAM_MW_TRANSMISSION 6E
  12 DECAM_NOBS       6B
  13 DECAM_RCHI2      6E
  14 DECAM_PSFSIZE    6E
  15 DECAM_FRACFLUX   6E
  16 DECAM_FRACMASKED 6E
  17 DECAM_FRACIN     6E
  18 DECAM_DEPTH      6E
  19 DECAM_GALDEPTH   6E
  20 OUT_OF_BOUNDS    L
  21 DECAM_ANYMASK    6I
  22 DECAM_ALLMASK    6I
  23 WISE_FLUX        4E
  24 WISE_FLUX_IVAR   4E
  25 WISE_MW_TRANSMISSION 4E
  26 WISE_NOBS        4I
  27 WISE_FRACFLUX    4E
  28 WISE_RCHI2       4E
  29 DCHISQ           5E
  30 FRACDEV          E
  31 TYCHO2INBLOB     L
  32 SHAPEDEV_R       E
  33 SHAPEDEV_R_IVAR  E
  34 SHAPEDEV_E1      E
  35 SHAPEDEV_E1_IVAR E
  36 SHAPEDEV_E2      E
  37 SHAPEDEV_E2_IVAR E
  38 SHAPEEXP_R       E
  39 SHAPEEXP_R_IVAR  E
  40 SHAPEEXP_E1      E
  41 SHAPEEXP_E1_IVAR E
  42 SHAPEEXP_E2      E
  43 SHAPEEXP_E2_IVAR E
  44 EBV              E


    Written by Gregory Rudnick 27 August 2015

    PURPOSE:

    reads in a list of colors from an ascii file and ouputs a 2D
    histogram in color

    CALLING SEQUENCE

    histmake(filein, fileout, grmin, grmax, rzmin, rzmax, bin_gr, bin_rz)

    INPUT PARAMETERS

    filein - the input ascii file

    fileout - the output 2D histogram as an ASCII file

    bin_gr, bin_rz - the bin sizes in colors

    OPTIONAL KEYWORKDS

    grmin, grmax, rzmin, rzmax - the min and max boundaries of the
    histogram.  If they are not specified as options they will be
    computed from the data and truncated to the nearest 0.1

    OUTPUTS

    an output file containin the 2D histogram normalized to the total
    number of objects in the histogram.

    EXAMPLES

    PROCEDURE

    REQUIRED PYTHON MODULES

    astropy
    numpy

    NOTES


finds approx. distance between reference and test points and
    returns array of indices and distance where distance < dsmax (degrees)


return dict containing astropy Table of concatenated tractor cats


return dict containing astropy Table of concatenated tractor cats
    one Table for matched and missed reference and test objects, each


True where BAD, return boolean array


set each Column's mask to specified mask


mask additional pixels to current mask


return boolean union of all masks in "list_of_names"


for mask being union of "list of names",
        returns number object not masked out
        example -- n_psf= self.number_masked(['psf'])


bins "data_for_percentile" into "nbins" using "data_bin_by" to decide how indices are assigned to bins
    returns bin center,N,q25,50,75 for each bin


make histograms of nobs so can compare depths of g,r,z between the two catalogues
    obj -- Single_TractorCat()


ra,dec distribution of objects
    obj -- Single_TractorCat()


number of psf,exp,dev,comp, etc
    obj -- Single_TractorCat()


plots Signal to Noise vs. mag for each band
    obj -- Single_TractorCat()


compares MATCHED reference (truth) to test (prediction)
    ref_obj,test_obj -- reference,test Single_TractorCat()
    return 5x5 confusion matrix and colum/row names


plot confusion matrix
    ref_obj,test_obj -- reference,test Single_TractorCat()


dist -- array of distances in degress between matched objects


compute number density in each bin for each band mag [18,requirement]
    deg2 -- square degrees spanned by sources in obj table
    req_mags -- image requirements grz<=24,23.4,22.5


Initialize the CCDs table.

    Description and Units at:
    https://github.com/legacysurvey/legacyzpts/blob/master/DESCRIPTION_OF_OUTPUTS.md


Initialize the stars table.

    Description and Units at:
    https://github.com/legacysurvey/legacyzpts/blob/master/DESCRIPTION_OF_OUTPUTS.md


Return list of -survey.fits table colums


Wrapper on the camera-specific classes to measure the CCD-level data on all
    the FITS extensions for a given set of images.


Generate a legacypipe-compatible (survey) CCDs file for a given image.


 Produce zeropoints for all CP images in image_list
    image_list -- iterable list of image filenames
    args -- parsed argparser objection from get_parser()


Computes photometric and astrometric zeropoints for one CCD.

    Args:

    Returns:
        ccds, stars_photom, stars_astrom


    Correct zeropoints for trends with airmass and MJD
    before making too-big/too-small cuts.

    *airmass_terms*: list of (band, airmass) coeffs.
    *mjd_terms*: list of (band, zpt0, [ (terms...)]) coeffs.


    Per Arjun's email 2021-08-06 "Zeropoint variations with MJD for
    DECam data - DR10 edition".


zpt_cut_lo, zpt_cut_hi: dict from band to zeropoint.


**kw are keyword arguments for psf_zeropoint_cuts.


Given a list of numpy arrays [a0,a1,...], zero-pads them all to be the same shape.


Build a color-color plot.  Show the data on the left-hand panel and random draws from
    the MoGs on the right-hand panel.


Number componentes from Bayesian Information Criterion


d -- dictionary of morphology params


        1) Adds gaussian noise to perfect source (in place)
        2) return invvar for the stamp
        Remember that STAMP and IVARSTAMP
        are in units of nanomaggies and 1/nanomaggies**2, respectively.


Convolve the object with the PSF and then draw it.


Render a star (PSF).


Create an ELG (disk-like) galaxy.


Samp -- table containing id,ra,dec,colors
	returns bool indices to cut so not overlapping


Build the simulated object catalog, which depends on OBJTYPE.


Parses input and returns dict containing
    metatable,seeds,brickwcs, other goodies


add simcat, simcat_dir to dict d
    simcat -- contains randomized ra,dec and PDF fluxes etc for ith chunk
    d -- dict returned by get_metadata_others()


Run tractor
    Can be run as 1) a loop over nchunks or 2) for one chunk
    d -- dict returned by get_metadata_others() AND added to by get_ith_simcat()


for each chunk that finishes running,
    Remove unecessary files and give unique names to all others
    d -- dict returned by get_metadata_others() AND added to by get_ith_simcat()


Main routine which parses the optional inputs.


unique_ids -- ids assigned to this mpi task
    writes ra,dec,grz qso,lrg,elg,star to fits file
    for given seed


    For each sample_fn, split into bricks
    get  brick sample fn for that brick and sample
    write it if does not exist
    sample_fn -- sample_seed.fits file assigned to that mpi task
    sbricks -- survey bricks table cut to radec region


index: optional nddex array for subset of compenents to save


sample() uses the component datum x is closest too, sample_full_pdf() uses sum of components at datum x
        this is more time consuming than sample() and difference is negligible


returns
            -pmap: 2d probability map, with requirement that integral(pdf d2x) within 1% of 1
            -xvec,yvec: vectors where x[ix] and y[ix] data points have probability pmap[ix,iy]


plot 2-sigma ellipses for each multivariate component


draw color selection box


data is a fits_table object with Tractor Catalogue columns


See: https://desi.lbl.gov/trac/wiki/TargetSelectionWG/TargetSelection#SpectrophotometricStandardStarsFSTD
           data is a fits_table object with Tractor Catalogue columns


returns array of indices of shape (k,n_train/k) to grab the k bins of training data


C is parameter varying


No Targeting cuts on g band, but need to fit it so can insert in grz image


Angular two-point correlation function

    A separate function is needed because angular distances are not
    euclidean, and random sampling needs to take into account the
    spherical volume element.

    Parameters
    ----------
    ra_G, dec_G : array_like
        Observed galaxy ra,dec
    bins : array_like
        bins within which to compute the 2-point correlation.
        shape = Nbins + 1
    method : string
        "standard" or "landy-szalay".
    ra_R, dec_R : array_like
        Random catlogue of ra,dec
    Nbootstraps : int
        number of bootstrap resamples

    Returns
    -------
    corr : ndarray
        the estimate of the correlation function within each bin
        shape = Nbins
    dcorr : ndarray
        error estimate on dcorr (sample standard deviation of
        bootstrap resamples)
    bootstraps : ndarray
        The full sample of bootstraps used to compute corr and dcorr


        read data in all gather_training_%d.hdf5 files, and store in
        gather_training_all.hdf5


read obj_simcat.fits in outdir and remove ids that were not used


Nran -- # of randoms


from two_point_angular() in astroML/correlation.py


basic plotting func


each pixel of stamp+noise image - stamp image should be gaussian distributed with std dev = sqrt(pix value in stamp)


return boolean indices for which to keep and throw out


return:
    1) median dmag of bright sources
    2) indices of sources that are bright AND |dmag[band]| -|median_dmag[band]| > 0.005 in ANY band
    3) indices of sources that are bright AND |dmag[band]| -|median_dmag[band]| <= 0.005 in ALL bands


compares classifications of matched objects, returns 2D array which is conf matrix and xylabels
    return 5x5 confusion matrix and colum/row names
   answer_type,predict_type -- arrays of same length with reference and prediction types


cm_stack -- list of single row confusion matrices
    stack_names -- list of same len as cm_stack, names for each row of cm_stack


    # Morphology plots
    if objtype=='ELG':
        fig = plt.figure(figsize=(8,4))
        plt.subplot(1,3,1)
        plt.plot(rmag,deltam,'s',markersize=3)
        plt.axhline(y=0.0,lw=2,ls='solid',color='gray')
        plt.xlim(rminmax)
        plt.xlabel('r (AB mag)')

        plt.subplot(1,3,2)
        plt.plot(bigsimcat['R50_1'],deltam,'s',markersize=3)
        plt.axhline(y=0.0,lw=2,ls='solid',color='gray')
        plt.xlabel('$r_{50}$ (arcsec)')

        plt.subplot(1,3,3)
        plt.plot(bigsimcat['BA_1'],deltam,'s',markersize=3)
        plt.axhline(y=0.0,lw=2,ls='solid',color='gray')
        plt.xlabel('b/a')
        plt.xlim([0.2,1.0])
        fig.subplots_adjust(bottom=0.18)
        qafile = os.path.join(output_dir,'qa-'+brickname+'-'+lobjtype+'-morph.png')
        log.info('Writing {}'.format(qafile))
        plt.savefig(qafile)


if subimage=True, assume that 'tims' are subimages, and demand that they have the same
    x0,y0 pixel offsets and size as the outlier mask files.

    if subimage=False, assume that 'tims' are full-CCD images, and
    apply the mask to the relevant subimage.

    *output* determines where we search for the file: treating it as output, or input?


    Given a list of tractor sources *cat*
    and a list of unWISE tiles *tiles* (a fits_table with RA,Dec,coadd_id)
    runs forced photometry, returning a FITS table the same length as *cat*.

    *get_masks*: the WCS to resample mask bits into.


Are the given points within the given RA,Dec rectangle?

    Returns a boolean array.


This is the entry-point from runbrick.py, called via mp.map()


    Converts WISE mask bits (in the unWISE data products) into the
    more compact codes reported in the tractor files as
    WISEMASK_W[12], and the "maskbits" WISE extensions.

    output bits :
    # 2^0 = bright star core and wings
    # 2^1 = PSF-based diffraction spike
    # 2^2 = optical ghost
    # 2^3 = first latent
    # 2^4 = second latent
    # 2^5 = AllWISE-like circular halo
    # 2^6 = bright star saturation
    # 2^7 = geometric diffraction spike


Returns a FITS table (with RA,Dec,coadd_id) of unWISE tiles


    Returns a Tan WCS object at the given RA,Dec center, axis aligned, with the
    given pixel W,H and pixel scale in arcsec/pixel.


    Reads Gaia stars within the given *wcs* object.

    *wcs* should include any margin you want (eg with *wcs.get_subimage()*).

    If *bands* is not *None*, the returned *GaiaSource* objects will
    be created with slots for fluxes in the given *bands*.


    Desired behaviors.

    Parent catalog:
    - if overlaps LMC/SMC mask,
      - no new source detection (only Gaia and SGA)
      - in DR10, we did this by setting CLUSTER
      - add new MASKBITS bit: CLOUDS (LMC/SMC), same behavior as CLUSTER
    - ignore LMC/SMC SGA sources
      - don't want to set GALAXY


The code to generate the NGC-star-clusters-fits catalog is in
    legacypipe/bin/build-cluster-catalog.py.


Driver function for forced photometry of individual Legacy
    Survey images.


    Units:
    - matches Gaia DR1/DR2
    - pmra,pmdec are in mas/yr.  pmra is in angular speed (ie, has a cos(dec) factor)
    - parallax is in mas.

    NOTE: does not broadcast completely correctly -- all params
    vectors or all motion params vector + scalar mjd work fine.  Other
    combos: not certain.

    Returns RA,Dec


    Returns an astrometry.net style Tan WCS object for a given brick object.

    b: row from survey-bricks.fits file
    W,H: size in pixels
    pixscale: pixel scale in arcsec/pixel.

    Returns: Tan wcs object


    Finds LegacySurvey bricks touching a given WCS header object.

    Parameters
    ----------
    targetwcs : astrometry.util.Tan object or similar
        The region of sky to search
    survey : legacypipe.survey.LegacySurveyData object
        From which the brick table will be retrieved
    B : FITS table
        The table of brick objects to search
    margin : int
        Margin in pixels around the outside of the WCS

    Returns
    -------
    A table (subset of B, if given) containing the bricks touching the
    given WCS region + margin.


    targetwcs: wcs object describing region of interest
    ccds: fits_table object of CCDs

    ccdrad: radius of CCDs, in degrees.
    If None (the default), compute from the CCDs table.
    (0.17 for DECam)

    Returns: index array I of CCDs within range.


    Saves a image in JPEG format.

    Some matplotlib installations
    don't support jpeg, so we optionally write to PNG and then convert
    to JPEG using the venerable netpbm tools.

    *jpegfn*: JPEG filename
    *img*: image, in the typical matplotlib formats (see plt.imsave)


Makes a band name suitable for a FITS column name


        Go through self.maskbits and self.maskbits_descriptions,
        updating the current bands (default GRZI) that have SATUR_ and
        ALLMASK_ entries.  Reuse these same bits in order.

        This method exists for the convenience of subclassers, eg in
        runs.py.


        Returns the filename of a Legacy Survey file.

        *filetype* : string, type of file to find, including:
             "tractor" -- Tractor catalogs
             "depth"   -- PSF depth maps
             "galdepth" -- Canonical galaxy depth maps
             "nexp" -- number-of-exposure maps

        *brick* : string, brick name such as "0001p000"

        *output*: True if we are about to write this file; will use self.outdir as
        the base directory rather than self.survey_dir.

        Returns: path to the specified file (whether or not it exists).


        Returns a context manager for writing an output file.

        Example use: ::

        with survey.write_output('ccds', brick=brickname) as out:
            ccds.writeto(out.fn, primheader=primhdr)

        For FITS output, out.fits is a fitsio.FITS object.  The file
        contents will actually be written in memory, and then a
        sha256sum computed before the file contents are written out to
        the real disk file.  The 'out.fn' member variable is NOT set.

        ::

        with survey.write_output('ccds', brick=brickname) as out:
            ccds.writeto(None, fits_object=out.fits, primheader=primhdr)

        Does the following on entry:
        - calls self.find_file() to determine which filename to write to
        - ensures the output directory exists
        - prepends a "tmp-" to the filename

        Does the following on exit:
        - moves the "tmp-" to the final filename (to make it atomic)
        - computes the sha256sum


Callback to be called in the *write_output* routine.


        Clears all cached data contained in this object.  Useful for
        pickling / multiprocessing.


Returns an index vector of the bricks that touch the given RA,Dec box.


        When reading the list of CCDs, we find all files named
        survey-ccds-*.fits.gz, then filter that list using this function.


        Provides the opportunity for subclassers (eg in runs.py) to drop some CCDs from the given
        fits_table of CCDs.


        When reading the list of annotated CCDs,
        filter file list using this function.


Returns a table of the CCDs touching the given *wcs* region.


        Creates tractor.Image objects for CCDs touching the given
        *targetwcs* region.

        mp: multiprocessing object

        kwargs are passed to LegacySurveyImage.get_tractor_image() and
        may include:

        * gaussPsf
        * pixPsf


        Returns a table of CCDs matching the given *expnum* (exposure
        number, integer), *ccdname* (string), and *camera* (string),
        if given.


        # By creating a kd-tree from the 'expnum' column, search for expnums
        # can be sped up:
        from astrometry.libkd.spherematch import *
        from astrometry.util.fits import fits_table
        T=fits_table('/global/cscratch1/sd/dstn/dr7-depthcut/survey-ccds-dr7.kd.fits',
            columns=['expnum'])
        ekd = tree_build(np.atleast_2d(T.expnum.copy()).T.astype(float),
                         nleaf=60, bbox=False, split=True)
        ekd.set_name('expnum')
        ekd.write('ekd.fits')

        > fitsgetext -i $CSCRATCH/dr7-depthcut/survey-ccds-dr7.kd.fits -o dr7-%02i -a -M
        > fitsgetext -i ekd.fits -o ekd-%02i -a -M
        > cat dr7-0* ekd-0[123456] > $CSCRATCH/dr7-depthcut+/survey-ccds-dr7.kd.fits


return gain*pixel DN as numpy array


extract wcs from fits header directly


    Build an object mask by doing a quick estimate of the sky background on a
    given image.

    skypix - True is unmasked pixels


    Bring individual CCDs onto a common flux scale based on overlapping pixels.

    fulltims - full-CCD tims, used to derive the corrections
    coaddtims - tims sliced to just the pixels contributing to the output coadd

    Some notes on the procedure:

    A x = b
    A: weights
    A: shape noverlap x nimg
    - entries have units of weights

    x_i: offset to apply to image i
    x: length nimg
    - entries will have values of image pixels

    b: (weighted) measured difference between image i and image j
    b: length -- "noverlap" number of overlapping pairs of images -- filled-in elements in your array
    - units of weighted image pixels


    With the ubercal option, we (1) read the full-field mosaics ('bandtims') for
    a given bandpass and put them all on the same 'system' using the overlapping
    pixels; (2) apply the derived corrections to the in-field 'tims'; (3) build
    the coadds (per bandpass) from the 'tims'; and (4) subtract the median sky
    from the mosaic (after aggressively masking objects and reference sources).


Returns a fitsio.FITS object for this image file.


        This checks for a relatively common type of corruption we see in
        the CP files, where the overall structure of the FITS files
        looks okay, but the data are corrupt so attempts to funpack
        uncompress them fail.  Test for this by just finding the list
        of expected extensions in the image file, and reading each of
        those exts in the image, weight, and dq maps.


Did the low-level processing succeed for this image?  If not, no
        need to process further.


        Returns a pixelized (or scalar) estimate of the sky background,
        plus the median sky and the 'skyrms' scatter around that.


        Called after legacy_zeropoints has just written the "photom" and
        "annotated" files.  (The objects are passed as *ann* and *photom*,
        along with the annotated header *hdr*.)


        Returns an estimate in bytes of the memory required to store
        this image's get_tractor_image tim.


        Reads the image file from disk.

        The image is read from FITS file self.imgfn HDU self.hdu.

        Parameters
        ----------
        slc : slice, optional
            2-dimensional slice of the subimage to read.
        header : boolean, optional
            Return the image header also, as tuple (image, header) ?

        Returns
        -------
        image : numpy array
            The image pixels.
        (image, header) : (numpy array, fitsio header)
            If `header = True`.


Returns the full shape of the image, (H,W).


        Reads the FITS primary (HDU 0) header from self.imgfn.

        Returns
        -------
        primary_header : fitsio header
            The FITS header


        Reads the FITS image header from self.imgfn HDU self.hdu.

        Returns
        -------
        header : fitsio header
            The FITS header


        Called by get_tractor_image() to map the results from read_dq
        into a bitmask.


Reads the sky model, returning a Tractor Sky object.


Source Extractor can't handle .fz files, so unpack them.


Run calibration pre-processing steps.


    wt: weight-map array
    weightfn: filename
    ext: extension
    slc: slice


Returns the healpix number for a given single (scalar) RA,Dec.


mags: 2-d array (Nstars, Nbands)


    psmags: 2-d array (Nstars, Nbands)
    band: [grz]


    psmags: 2-d array (Nstars, Nbands)
    band: [gr]

    color terms are taken from:
      https://desi.lbl.gov/trac/wiki/BokLegacy/Photometric


    psmags: 2-d array (Nstars, Nbands)
    band: [gr]


    Some versions of the CP use integer codes, not bit masks.
    This converts them.

    1 = bad
    2 = no value (for remapped and stacked data)
    3 = saturated
    4 = bleed mask
    5 = cosmic ray
    6 = low weight
    7 = diff detect (multi-exposure difference detection from median)
    8 = long streak (e.g. satellite trail)


    truncated_ok: the target *plver* or *plprocid* may be truncated, so only
    demand a match up to the length of those variables.  This can happen if, eg,
    the survey-ccds table has the PLVER or PLPROCID columns too short.


    Return a list of tractor Sources.

    If invvars=True, return sources,invvars
    where invvars is a list matching sources.getParams()

    If *ellipseClass* is set, assume that type for galaxy shapes; if None,
    read the type from the header.


    After the model fits are finished, we can perform forced
    photometry of the GALEX coadds.


one band x multiple GALEX tiles/images


    Given a list of tractor sources *cat*
    and a list of GALEX tiles *tiles* (a fits_table with RA,Dec,tilename)
    runs forced photometry, returning a FITS table the same length as *cat*.


Find and read the overlapping GALEX FUV/NUV tiles.


    Generate custom GALEX cutouts.

    radius_mosaic and radius_mask in arcsec

    pixscale: GALEX pixel scale in arcsec/pixel.


    keep_propids: iterable of PROPID strings to definitely keep
    first_propids: iterable of PROPID strings to try first


Did the CP processing succeed for this image?  If not, no need to process further.


Fits sources contained within a "blob" of pixels.


    radius: int
    ix,iy: int arrays
    I: indices into ix,iy that will be placed into 'segmap'


Note that this modifies the *tims* if subtract=True.


Adds the models for source *i* back into the tims.


    mod: Patch
    sh: tim shape
    ie: tim invError
    Returns: new Patch


Returns keepmod (string), the name of the preferred model.


chisqs, chisqs_none: dict of band->chisq


    Determines which SED-matched filters to run based on the available
    bands.

    Returns
    -------
    SEDs : list of (name, sed) tuples


    Runs a given set of SED-matched filters.

    Parameters
    ----------
    SEDs : list of (name, sed) tuples
        The SEDs to run.  The `sed` values are lists the same length
        as `bands`.
    bands : list of string
        The band names of `detmaps` and `detivs`.
    detmaps : numpy array, float
        Detection maps for each of the listed `bands`.
    detivs : numpy array, float
        Inverse-variances of the `detmaps`.
    omit_xy : None, or (xx,yy,rr) tuple
        Existing sources to avoid: x, y, radius.
    targetwcs : WCS object
        WCS object to use to convert pixel values into RA,Decs for the
        returned Tractor PointSource objects.
    nsigma : float, optional
        Detection threshold
    saturated_pix : None or list of numpy arrays, booleans
        Passed through to sed_matched_detection.
        A map of pixels that are always considered "hot" when
        determining whether a new source touches hot pixels of an
        existing source.
    exclusion_radius: int
        How many pixels around an existing source to veto
    plots : boolean, optional
        Create plots?
    ps : PlotSequence object
        Create plots?
    mp : multiproc object
        Multiprocessing

    Returns
    -------
    Tnew : fits_table
        Table of new sources detected
    newcat : list of PointSource objects
        Newly detected objects, with positions and fluxes, as Tractor
        PointSource objects.
    hot : numpy array of bool
        "Hot pixels" containing sources.

    See also
    --------
    sed_matched_detection : run a single SED-matched filter.


    Runs a single SED-matched detection filter.

    Avoids creating sources close to existing sources.

    Parameters
    ----------
    sedname : string
        Name of this SED; only used for plots.
    sed : list of floats
        The SED -- a list of floats, one per band, of this SED.
    detmaps : list of numpy arrays
        The per-band detection maps.  These must all be the same size, the
        brick image size.
    detivs : list of numpy arrays
        The inverse-variance maps associated with `detmaps`.
    bands : list of strings
        The band names of the `detmaps` and `detivs` images.
    xomit, yomit, romit : iterables (lists or numpy arrays) of int
        Previously known sources that are to be avoided; x,y +- radius
    nsigma : float, optional
        Detection threshold.
    saddle_fraction : float, optional
        Fraction of the peak heigh for selecting new sources.
    saddle_min : float, optional
        Saddle-point depth from existing sources down to new sources.
    saturated_pix : None or list of numpy arrays, boolean
        A map of pixels that are always considered "hot" when
        determining whether a new source touches hot pixels of an
        existing source.
    cutonaper : bool, optional
        Apply a cut that the source's detection strength must be greater
        than `nsigma` above the 16th percentile of the detection strength in
        an annulus (from 10 to 20 pixels) around the source.
    ps : PlotSequence object, optional
        Create plots?

    Returns
    -------
    hotblobs : numpy array of bool
        A map of the blobs yielding sources in this SED.
    px, py : numpy array of int
        The new sources found.
    aper : numpy array of float
        The detection strength in the annulus around the source, if
        `cutonaper` is set; else -1.
    peakval : numpy array of float
        The detection strength.

    See also
    --------
    sed_matched_filters : creates the `(sedname, sed)` pairs used here
    run_sed_matched_filters : calls this method


    *image*: binary image that defines "blobs"
    *T*: source table; only ".ibx" and ".iby" elements are used (x,y integer
    pix pos).  Note: ".blob" field is added.
    *name*: for debugging only

    Returns: (blobmap, blobsrcs, blobslices)

    *blobmap*: image, values -1 = no blob, integer blob indices
    *blobsrcs*: list of np arrays of integers, elements in T within each blob
    *blobslices*: list of slice objects for blob bounding-boxes.


    Finds "hot" pixels that are separated by masked pixels, to connect
    blobs across, eg, bleed trails and saturated cores.
    Updates *hot* in-place.


    This is the first stage in the pipeline.  It
    determines which CCD images overlap the brick or region of
    interest, runs calibrations for those images if necessary, and
    then reads the images, creating `tractor.Image` ("tractor image"
    or "tim") objects for them.

    PSF options:

    - *gaussPsf*: boolean.  Single-component circular Gaussian, with
      width set from the header FWHM value.  Useful for quick
      debugging.

    - *pixPsf*: boolean.  Pixelized PsfEx model.

    - *hybridPsf*: boolean.  Hybrid Pixelized PsfEx / Gaussian approx model.

    Sky:

    - *splinesky*: boolean.  If we have to create sky calibs, create SplineSky model rather than ConstantSky?
    - *subsky*: boolean.  Subtract sky model from tims?


This pipeline stage tries to detect artifacts in the individual
    exposures, by blurring all images in the same band to the same PSF size,
    then searching for outliers.

    *cache_outliers*: bool: if the outliers-mask*.fits.fz file exists
    (from a previous run), use it.  We turn this off in production
    because we still want to create the JPEGs and the checksum entry
    for the outliers file.


    Immediately after reading the images, we can create coadds of just
    the image products.  Later, full coadds including the models will
    be created (in `stage_coadds`).  But it's handy to have the coadds
    early on, to diagnose problems or just to look at the data.


    In this stage we run SED-matched detection to find objects in the
    images.  For each object detected, a `tractor` source object is
    created, initially a `tractor.PointSource`.  In this stage, the
    sources are also split into "blobs" of overlapping pixels.  Each
    of these blobs will be processed independently.


    This is where the actual source fitting happens.
    The `one_blob` function is called for each "blob" of pixels with
    the sources contained within that blob.


    *blobmap*: integer image map, with -1 indicating no-blob, other values indexing
        into *blobslices*,*blobsrcs*.
    *blobsrcs*: a list of numpy arrays of integers -- indices into *cat* -- of the sources in
        this blob.
    *T*: a fits table parallel to *cat* with some extra info (very little used)


This wraps the one_blob function for multiprocessing purposes (and
    now also does some post-processing).


    After the `stage_fitblobs` fitting stage, we have all the source
    model fits, and we can create coadds of the images, model, and
    residuals.  We also perform aperture photometry in this stage.


    After the model fits are finished, we can perform forced
    photometry of the unWISE coadds.


    Read in images from the survey-ccds files in *forced_bands* bands.

    Perform forced photometry on them, and also accumulate a coadd.

    (Also run forced-photometry on the individual exposures in *tims* ??)


    Final stage in the pipeline: format results for the output
    catalog.


For debugging / special-case processing, write out the current checksums file.


Run the full Legacy Survey data reduction pipeline.

    The pipeline is built out of "stages" that run in sequence.  By
    default, this function will cache the result of each stage in a
    (large) pickle file.  If you re-run, it will read from the
    prerequisite pickle file rather than re-running the prerequisite
    stage.  This can yield faster debugging times, but you almost
    certainly want to turn it off (with `writePickles=False,
    forceall=True`) in production.

    Parameters
    ----------
    brick : string
        Brick name such as '2090m065'.  Can be None if *radec* is given.
    survey : a "LegacySurveyData" object (see common.LegacySurveyData), which is in
        charge of the list of bricks and CCDs to be handled, and where output files
        should be written.
    radec : tuple of floats (ra,dec)
        RA,Dec center of the custom region to run.
    pixscale : float
        Brick pixel scale, in arcsec/pixel.  Default = 0.262
    width, height : integers
        Brick size in pixels.  Default of 3600 pixels (with the default pixel
        scale of 0.262) leads to a slight overlap between bricks.
    zoom : list of four integers
        Pixel coordinates [xlo,xhi, ylo,yhi] of the brick subimage to run.
    bands : string
        Filter (band) names to include; default is "grz".

    Notes
    -----
    You must specify the region of sky to work on, via one of:

    - *brick*: string, brick name such as '2090m065'
    - *radec*: tuple of floats; RA,Dec center of the custom region to run

    If *radec* is given, *brick* should be *None*.  If *brick* is given,
    that brick`s RA,Dec center will be looked up in the
    survey-bricks.fits file.

    You can also change the size of the region to reduce:

    - *pixscale*: float, brick pixel scale, in arcsec/pixel.
    - *width* and *height*: integers; brick size in pixels.  3600 pixels
      (with the default pixel scale of 0.262) leads to a slight overlap
      between bricks.
    - *zoom*: list of four integers, [xlo,xhi, ylo,yhi] of the brick
      subimage to run.

    If you want to measure only a subset of the astronomical objects,
    you can use:

    - *nblobs*: None or int; for debugging purposes, only fit the
       first N blobs.
    - *blob*: int; for debugging purposes, start with this blob index.
    - *blobxy*: list of (x,y) integer tuples; only run the blobs
      containing these pixels.
    - *blobradec*: list of (RA,Dec) tuples; only run the blobs
      containing these coordinates.

    Other options:

    - *max_blobsize*: int; ignore blobs with more than this many pixels

    - *nsigma*: float; detection threshold in sigmas.

    - *wise*: boolean; run WISE forced photometry?

    - *do_calibs*: boolean; run the calibration preprocessing steps?

    - *old_calibs_ok*: boolean; allow/use old calibration frames?

    - *write_metrics*: boolean; write out a variety of useful metrics

    - *gaussPsf*: boolean; use a simpler single-component Gaussian PSF model?

    - *pixPsf*: boolean; use the pixelized PsfEx PSF model and FFT convolution?

    - *hybridPsf*: boolean; use combo pixelized PsfEx + Gaussian approx model

    - *normalizePsf*: boolean; make PsfEx model have unit flux

    - *splinesky*: boolean; use the splined sky model (default is constant)?

    - *subsky*: boolean; subtract the sky model when reading in tims (tractor images)?

    - *ceres*: boolean; use Ceres Solver when possible?

    - *wise_ceres*: boolean; use Ceres Solver for unWISE forced photometry?

    - *galex_ceres*: boolean; use Ceres Solver for GALEX forced photometry?

    - *unwise_dir*: string; where to look for unWISE coadd files.
      This may be a colon-separated list of directories to search in
      order.

    - *unwise_tr_dir*: string; where to look for time-resolved
      unWISE coadd files.  This may be a colon-separated list of
      directories to search in order.

    - *unwise_modelsky_dir*: string; where to look for the unWISE sky background
      maps.  The default is to look in the "wise/modelsky" subdirectory of the
      calibration directory.

    - *threads*: integer; how many CPU cores to use

    Plotting options:

    - *coadd_bw*: boolean: if only one band is available, make B&W coadds?
    - *plots*: boolean; make a bunch of plots?
    - *plots2*: boolean; make a bunch more plots?
    - *plot_base*: string, default brick-BRICK, the plot filename prefix.
    - *plot_number*: integer, default 0, starting number for plot filenames.

    Options regarding the "stages":

    - *pickle_pat*: string; filename for 'pickle' files
    - *stages*: list of strings; stages (functions stage_*) to run.

    - *force*: list of strings; prerequisite stages that will be run
      even if pickle files exist.
    - *forceall*: boolean; run all stages, ignoring all pickle files.
    - *write_pickles*: boolean; write pickle files after each stage?

    Raises
    ------
    RunbrickError
        If an invalid brick name is given.
    NothingToDoError
        If no CCDs, or no photometric CCDs, overlap the given brick or region.


Called from the input thread to generate work packets for the given *brickname*.


Returns `git describe, or 'unknown' if not a git repo


parse filename to check if this is a tractor brick file;
    returns brickname if it is, otherwise raises ValueError


 Iterator over all tractor files in a directory.

        Parameters
        ----------
        root : string
            Path to start looking

        Returns
        -------
        An iterator of (brickname, filename).

        Examples
        --------
        >>> for brickname, filename in iter_tractor('./'):
        >>>     print(brickname, filename)

        Notes
        -----
        root can be a directory or a single file; both create an iterator


 Returns the the amount of memory available for use.

        This function is not very useful.
        The memory is obtained from MemTotal entry in /proc/meminfo.


 Returns the number of slave processes to be spawned.

        The default value is the number of physical cpu cores seen by python.
        :code:`OMP_NUM_THREADS` environment variable overrides it.

        On PBS/torque systems if OMP_NUM_THREADS is empty, we try to
        use the value of :code:`PBS_NUM_PPN` variable.

        Notes
        -----
        On some machines the physical number of cores does not equal
        the number of cpus shall be used. PSC Blacklight for example.


 Wait and join the child process.
            The return value of the function call is returned.
            If any exception occurred it is wrapped and raised.


 Creates a MapReduce object but with the Thread backend.

        The process backend is usually preferred.


 Map-reduce with multile processes.

            Apply func to each item on the sequence, in parallel.
            As the results are collected, reduce is called on the result.
            The reduced result is returned as a list.

            Parameters
            ----------
            func : callable
                The function to call. It must accept the same number of
                arguments as the length of an item in the sequence.

                .. warning::

                    func is not supposed to use exceptions for flow control.
                    In non-debug mode all exceptions will be wrapped into
                    a :py:class:`SlaveException`.

            sequence : list or array_like
                The sequence of arguments to be applied to func.

            reduce : callable, optional
                Apply an reduction operation on the
                return values of func. If func returns a tuple, they
                are treated as positional arguments of reduce.

            star : boolean
                if True, the items in sequence are treated as positional
                arguments of reduce.

            Returns
            -------
            results : list
                The list of reduced results from the map operation, in
                the order of the arguments of sequence.

            Raises
            ------
            SlaveException
                If any of the slave process encounters
                an exception. Inspect :py:attr:`SlaveException.reason` for the underlying exception.


Create a shared memory array from the shape of array.


Create a shared memory array with the same shape and type as a given array, filled with `value`.


Create a shared memory array of given shape and type, filled with `value`.


 Copy an array to the shared memory.

        Notes
        -----
        copy is not always necessary because the private memory is always copy-on-write.

        Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory


Compute distances to pixels in cutout.


Cuts out the aperture and defines slice objects.

        General setup procedure.

        Parameters
        ----------
        self : `RadialProfile`
            Radial profile object.
        data : array-like
            Input data array from which to cut out aperture.


Fit 1d Moffat function to measured radial profile.

        Fits a Moffat profile to the distance and values of
        the pixels.

        Note
        ----
            Further development may allow user-defined
            models.


Returns 1D Moffat profile evaluated at r values.

        This function takes radius values and parameters in
        a simple 1D Moffat profile and returns the values
        of the profile at those radius values.

        The model is defined as:
            model = amp * (1. + (r / gamma) ** 2.) ** (-1. * alpha) + bias

        Parameters
        ----------
        r : array
            The distances at which to sample the model.
        amp : float
            The amplitude of the of the model.
        gamma: float
            The width of the profile.
        alpha: float
            The decay of the profile.
        bias: float
            The bias level (piston term) of the data. This
            is like a background value.

        Returns
        -------
        model : array
            The values of the model sampled at the r values.


Recenters/updates source position in cutout.

        Parameters
        ----------
        self : `RadialProfile`
            Radial profile object.
        data : array-like
            Input data array from which to cut out aperture.


    Planet-star flux ratio

    Parameters
    ----------
    A : float or array-like
        Planetary geometric albedo
    Phi : float
        Planetary phase function
    Rp : float
        Planetary radius [Earth radii]
    r : float
        Planetary orbital semi-major axis [AU]

    Returns
    -------
    FpFs : float or array-like
        Planet-star flux ratio


    Exoplanetary photon count rate

    Parameters
    ----------
    q : float or array-like
        Quantum efficiency
    fpa : float
        Fraction of planetary light that falls within photometric aperture
    T : float
        Telescope and system throughput
    lam : float or array-like
        Wavelength [um]
    dlam : float or array-like
        Spectral element width [um]
    Fplan : float or array-like
        Planetary flux [W/m**2/um]
    D : float
        Telescope diameter [m]

    Returns
    -------
    cplan : float or array-like
        Exoplanetary photon count rate [1/s]


    Speckle count rate

    Parameters
    ----------
    q : float or array-like
        Quantum efficiency
    T : float
        System throughput
    C : float, optional
        Coronagraph design contrast
    lam : float or array-like
        Wavelength [um]
    dlam : float or array-like
        Spectral element width [um]
    D : float
        Telescope diameter [m]
    Fstar : float or array-like
        Host star spectrum at distance of planet (TOA) [W/m**2/um]

    Returns
    -------
    cspeck : float or array-like
        Speckle photon count rate [1/s]


    Clock induced charge count rate (not currently in use)

    Parameters
    ----------
    Rc : float or array-like
        Clock induced charge counts per pixel per read
    X : float, optional
        Width of photometric aperture ( * lambda / diam)
    lam : float or array-like
        Wavelength [um]
    D : float
        Telescope diameter [m]
    theta :
        Angular size of lenslet or pixel [arcsec**2]
    Dtmax : float, optional
        Detector maximum exposure time [hours]
    IMAGE : bool, optional
        Set to indicate imaging mode (not IFS)
    CIRC : bool, optional
        Set to use a circular aperture

    Returns
    -------
    cread :
        Read noise count rate [1/s]


    Numerical integration to determine fraction of Airy power
    contained square aperture (SLOW!)

    Parameters
    ----------
    X : float, optional
        Width of photometric aperture ( * lambda / diam)

    Returns
    -------
    f_airy : float
        Fraction of planetary light that falls within photometric aperture X*lambda/D


    Earth atmosphere thermal count rate

    Parameters
    ----------
    q : float or array-like
        Quantum efficiency
    X : float, optional
        Width of photometric aperture ( * lambda / diam)
    lam : float or array-like
        Wavelength [um]
    dlam : float or array-like
        Spectral element width [um]
    D : float
        Telescope diameter [m]
    Itherm : float or array-like
        Earth thermal intensity [W/m**2/um/sr]

    Returns
    -------
    cthe : float or array-like
        Earth atmosphere thermal photon count rate [1/s]


    Calculate the Lambertian Phase Function from the phase angle

    Parameters
    ----------
    alpha: float
        Planet phase angle [deg]

    Returns
    -------
    Phi : float
        Lambertian phase function


Plots noised-up spectrum.


    Parameters
    ----------
    Ahr : array
        hi-res planetary albedo spectrum
    lamhr : array
        wavelength grid for Ahr (um)
    solhr : array
        hi-res TOA solar spectrum (W/m**2/um)
    telescope : Telescope
        Telescope object containing parameters
    planet : Planet
        Planet object containing parameters
    star : Star
        Star object containing parameters
    FIX_OWA : bool
        set to fix OWA at OWA*lammin/D, as would occur if lenslet array is limiting the OWA
    COMPUTE_LAM : bool
        set to compute lo-res wavelength grid, otherwise the grid input as variable 'lam' is used
    NIR : bool
        re-adjusts pixel size in NIR, as would occur if a second instrument was designed to handle the NIR
    THERMAL : bool
        set to compute thermal photon counts due to telescope temperature


Uses coronagraph model to observe planets located in planetdir

    Parameters
    ----------
    name : str (optional)
        Name of the planet
    telescope : Telescope (optional)
        Telescope object to be used for observation
    planet : Planet (optional)
        Planet object to be used for observation
    itime : float (optional)
        Integration time (hours)
    planetdir : str
        Location of planets/ directory
    plot : bool (optional)
        Make plot flag
    savedata : bool (optional)
        Save output as data file
    saveplot : bool (optional)
        Save plot as PDF
    ref_lam : float (optional)
        Wavelength at which SNR is computed

    Returns
    -------
    lam : array
        Observed wavelength array (microns)
    spec : array
        Observed reflectivity spectrum
    sig : array
        Observed 1-sigma error bars on spectrum


    Parameters
    ----------
    wlhr : float
        Wavelength array (microns)
    Ahr : float
        Geometric albedo spectrum array
    itime : float
        Integration time (hours)
    telescope : Telescope
        Telescope object
    planet : Planet
        Planet object
    star : Star
        Star object
    tag : string
        ID for output files
    plot : boolean
        Set to True to make plot
    saveplot : boolean
        Set to True to save the plot as a PDF
    savedata : boolean
        Set to True to save data file of observation

    Returns
    -------
    lam : array
        Wavelength grid of observed spectrum
    spec : array
        Albedo grid of observed spectrum
    sig : array
        One sigma errorbars on albedo spectrum

    Output
    ------
    If saveplot=True then plot will be saved
    If savedata=True then data will be saved


Uses coronagraph noise model to create an observation of high resolution SMART output.

    Parameters
    ----------
    radfile : string
        Location and name of file to be read in
    itime : float
        Integration time (hours)
    telescope : Telescope
        Telescope object
    planet : Planet
        Planet object
    star : Star
        Star object
    tag : string
        ID for output files
    plot : boolean
        Set to True to make plot
    saveplot : boolean
        Set to True to save the plot as a PDF
    savedata : boolean
        Set to True to save data file of observation

    Returns
    ----------
    lam : array
        Wavelength grid of observed spectrum
    spec : array
        Albedo grid of observed spectrum
    sig : array
        One sigma errorbars on albedo spectrum
    rwl : array
        Wavelength grid of SMART output
    Ahr : array
        Albedo grid of SMART output

    Output
    ---------
    If saveplot=True then plot will be saved
    If savedata=True then data will be saved


Adds new filter to wheel

        Parameters
        ----------
        filt : Filter
            New Filter object to be added to wheel
        name : string (optional)
            Name to give new filter attribute


Basic printout of module capabilities


        Reads MRMS NetCDF mosaic tiles.
        Attempts to distinguish between v1 (<= 7/30/2013)
        and v2 (>= 7/30/2013) mosaics.
        v2 are produced from original binary tiles by MRMS_to_CFncdf.
        Reads the file and populates class attributes.


Reads gzipped MRMS binary files and populates MosaicTile fields.
Attempts to distinguish between v1 (<= 7/30/2013) and v2 (>= 7/30/2013)
mosaics.
Major reference:
ftp://ftp.nssl.noaa.gov/users/langston/MRMS_REFERENCE/MRMS_BinaryFormat.pdf


        Method that is capable of reading grib2-format MRMS mosaics.
        Relies on MosaicGrib and NetcdfFile classes to do the heavy lifting.
        This method is mainly concerned with taking their output and creating
        a properly formatted MosaicTile object.

        Arguments/Keywords (passed to MosaicGrib)
        -----------------------------------------
        filename = Single string or list of strings, can be for grib2 or
                   netCDFs created by wgrib2
        wgrib2_path = Path to wgrib2 executable
        wgrib2_name = Name of wgrib2 executable
        keep_nc = Set to False to erase netCDFs created by wgrib2
        verbose = Set to True to get text updates on progress
        nc_path = Path to directory where netCDFs will be created
        lat/lonrange = 2-element lists used to subsection grib data
                       before ingest


        Prints out diagnostic information and produces
        a basic plot of tile/stitch composite reflectivity.


        Subsections a tile (or stitch) by keeping data only within the given
        2-element lists: latrange (deg), lonrange (deg), zrange (km).
        Lists that are not defined will lead to no subsectioning along those
        axes.
        verbose = Set to True to get some text response.


        Produces a gzipped binary file containing only a composite of
        the chosen variable. The existing tile now will only consist
        of a single vertical level (e.g., composite reflectivity)


v1 MRMS netcdf data file


v2 MRMS netcdf data file


        This is the structure of a complete binary MRMS file.
        This method breaks in Python 2.7 if you import the
        unicode_literals module from __future__. However,
        the method works fine under Python 3.4 as written.


Returns tile number as a string based on starting lat/lon


This is the structure of the header of a binary MRMS file


        Turns a 3D float mosaic into a 1-D short array suitable for writing
        to a binary file


        Actual reading of grib2 and netCDF files occurs here.
        Input arguments and keywords same as __init__() method.
        Now capable of ingesting grib2 directly via pygrib.


        This method takes a list of ingested grib files and formats the data
        to match the MMM-Py model.


        Method to group all the reflectivity 2D planes into a 3D array.
        Also populates attributes that will be necessary for MosaicTile.


Disabled in a MosaicStitch to avoid problems.


        Stitches MosaicTile pair or MosaicStitch pair (or mixed pair)
        in N-S direction.


        Stitches MosaicTile pair or MosaicStitch pair (or mixed pair)
        in W-E direction


        ns_flag=True means N-S stitch, False means W-E stitch.
        Uses np.append() to stitch together.


        ns_flag=True means N-S stitch, False means W-E stitch.
        Uses np.append() to stitch together.
        Ignore composite - can recalculate quickly rather than stitch.


        Plots a basemap projection with a plan view of the mosaic radar data.
        The projection can be used to incorporate other data into figure
        (e.g., lightning).
        var = Variable to be plotted.
        latrange = Desired latitude range of plot (2-element list).
        lonrange = Desired longitude range of plot (2-element list).
        level = If set, performs horizontal cross-section thru that altitude,
                or as close as possible to it. If not set, will plot composite.
        meridians, parallels = Scalars to denote desired gridline spacing.
        linewidth = Width of gridlines (default=0).
        show_grid = Set to False to suppress gridlines and lat/lon labels.
        title = Plot title string, None = Basic time & date string as title.
                So if you want a blank title use title='' as keyword.
        clevs = Desired contour levels.
        cmap = Desired color map.
        basemap = Assign to basemap you want to use.
        embellish = Set to false to suppress basemap changes.
        colorbar_loc = Options: 'bottom', 'top', 'right', 'left'
        save = File to save image to. Careful, PS/EPS/PDF can get large!
        verbose = Set to True if you want a lot of text for debugging.
        resolution = Resolution of Basemap instance (e.g., 'c', 'l', 'i', 'h')
        area_thresh = Area threshold to show lakes, etc. (km^2)
        return_flag = Set to True to return plot info.
                      Order is Figure, Axis, Basemap


        Plots a vertical cross-section through mosaic radar data.
        var = Variable to be plotted.
        lat/lon = If set, performs vertical cross-section thru that lat/lon,
                  or as close as possible to it. Only one or the other
                  can be set.
        xrange = Desired latitude or longitude range of plot (2-element list).
        zrange = Desired height range of plot (2-element list).
        xlabel, zlabel = Axes labels.
        clevs = Desired contour levels.
        cmap = Desired color map.
        title = String for plot title, None = Basic time & date as title.
                So if you want a blank title use title='' as keyword.
        save = File to save image to. Careful, PS/EPS/PDF can get large!
        verbose = Set to True if you want a lot of text for debugging.
        return_flag = Set to True to return Figure, Axis objects


        Plots horizontal and vertical cross-sections through mosaic radar data.
        Subplot (a) is the horizontal view, (b) is the
        var = Variable to be plotted.
        latrange = Desired latitude range of plot (2-element list).
        lonrange = Desired longitude range of plot (2-element list).
        level = If set, performs horizontal cross-section thru that altitude,
                or as close as possible to it. If not set, will plot composite.
        meridians, parallels = Scalars to denote desired gridline spacing.
        linewidth = Width of gridlines (default=0).
        show_grid = Set to False to suppress gridlines and lat/lon tick labels.
        title_a, _b, _c = Strings for subplot titles, None = Basic time & date
                          string as title for subplot (a), and constant lat/lon
                          for (b) and (c). So if you want blank titles use
                          title_?='' as keywords.
        clevs = Desired contour levels.
        cmap = Desired color map.
        save = File to save image to. Careful, PS/EPS/PDF can get large!
        verbose = Set to True if you want a lot of text for debugging.
        zrange = Desired height range of plot (2-element list).
        resolution = Resolution of Basemap instance (e.g., 'c', 'l', 'i', 'h')
        area_thresh = Area threshold to show lakes, etc. (km^2)
        lonlabel, latlabel, zlabel = Axes labels.
        lat/lon = Performs vertical cross-sections thru those lat/lons,
                  or as close as possible to them. Both are required to be set!
        return_flag = Set to True to return plot info.
                      Order is Figure, Axes (3 of them), Basemap.
        show_crosshairs = Set to False to suppress the vertical cross-section
                          crosshairs on the horizontal cross-section.
        xrange_b, _c = Subplot (b) is constant latitude, so xrange_b is is a
                       2-element list that allows the user to adjust the
                       longitude domain of (b). Default lonrange if not set.
                       Similar setup for xrange_c - subplot (c) - except for
                       latitude (i.e., defaults to latrange if not set). The
                       xrange_? variables determine length of crosshairs.


Execute slicing, get xvar, vcut


Parse and return ax and fig parameters. Adapted from Py-ART.