    :returns: arc cosine
    :rtype:   :py:class:`~.RegData`


    :returns: arc tangens
    :rtype:   :py:class:`~.RegData`


    :returns: hyperbolic sine
    :rtype:   :py:class:`~.RegData`


    :returns: hyperbolic cosine
    :rtype:   :py:class:`~.RegData`


    :returns: hyperbolic tangens
    :rtype:   :py:class:`~.RegData`


    :returns: hyperbolic arc sine
    :rtype:   :py:class:`~.RegData`


    :returns: hyperbolic arc cosine
    :rtype:   :py:class:`~.RegData`


    :returns: hyperbolic arc tangens
    :rtype:   :py:class:`~.RegData`


    :returns: square root
    :rtype:   :py:class:`~.RegData`


    :returns: exponential
    :rtype:   :py:class:`~.RegData`


    :returns: natural logarithm
    :rtype:   :py:class:`~.RegData`


    :returns: base-10 logarithm
    :rtype:   :py:class:`~.RegData`


    :returns: real part
    :rtype:   :py:class:`~.RegData`


    :returns: imaginary part
    :rtype:   :py:class:`~.RegData`


    :returns: complex conjugate
    :rtype:   :py:class:`~.RegData`


    :param b: data to compare to
    :type b:  :py:class:`~.RegData` or numpy array
    :returns: element-wise maximum
    :rtype:   :py:class:`~.RegData`


    :param b: data to compare to
    :type b:  :py:class:`~.RegData` or numpy array
    :returns: element-wise minimum
    :rtype:   :py:class:`~.RegData`


Merges a list of RegData instances into one, assuming they
  all have the same grid spacing and filling a regular grid completely,
  with the same values in overlapping regions (ghost zones etc).
  Beware, the assumptions are not checked.


Create a regular dataset by sampling a scalar function on a
  regular grid.

  :param func:  The function to sample.
  :type func:   Anything accepting 1d numpy array as input and returns
                scalar.
  :param x0:    Minimum corner of regular sample grid.
  :type x0:     1d numpy array or list of float
  :param x0:    Maximum corner of regular sample grid.
  :type x0:     1d numpy array or list of float
  :param shape: Number of sample points in each dimension.
  :type shape:  1d numpy array or list of int
  :returns:     Sampled data.
  :rtype:       :py:class:`~.RegData`


    :returns: Number of dimensions.
    :rtype:   int


The bounding box corner with minimum coordinates.

    :returns: Corner coordinate.
    :rtype:   1d numpy array of float


The bounding box corner with maximum coordinates.

    :returns: Corner coordinate.
    :rtype:   1d numpy array of float


Get coordinates as composite datasets with the same structure.
    Useful for arithmetic operations involving data and coordinates.

    :returns: list of coordinates for each dimension
    :rtype:   list of :py:class:`~.CompData` instances


    :returns: The maximum of the data.
    :rtype:   same as data.


    :returns: The minimum of the data.
    :rtype:   same as data.


Compute the integral over the whole volume of the grid.
    Note this is currently only implemented for the case of one
    refinement level with only one component, otherwise raises an
    exception.

    :returns: The integral.
    :rtype:   float (or complex if data is complex).


Computes the partial derivative along a given dimension. Uses
    either a 3-point central difference stencil for 2nd order accuracy,
    or a five point central stencil for 4th order. At the boundaries, 1
    point (2 for 4th order) is computed to first order accuracy using
    one-sided derivatives. The array size in the dimension dim needs to
    be at least the stencil size.

    .. Note:: The derivative is computed for each refinement level and
      component independently, if there are not enough ghost zones the
      order of accuracy drops to one at each component boundary.

    :param dim:   Dimension of partial derivative.
    :type dim:    int
    :param order: Order of accuracy (2 or 4).
    :type order:  int
    :returns:     The derivative.
    :rtype:       :py:class:`~.CompData` instance with same structure.


Zeroth order interpolation, using the finest available grid
    covering the given coordinate. For positions outside the grid, it
    uses the outside value specified when creating the object.

    :param x: Coordinate to interpolate to.
    :type x:  1d numpy array or list of float
    :returns: Value at nearest grid point or outside_value.
    :rtype:   same as data.


Perform a multilinear interpolation to the coordinate x, using
    the finest grid containing x. If x is outside the grid, return the
    outside value.

    :param x: Coordinate to interpolate to.
    :type x:  1d numpy array or list of float
    :returns: Value at nearest grid point or outside_value.
    :rtype:   same as data.


Resamples to a regular grid with alternative method.

    :param geom:  Regular grid geometry to sample to.
    :type geom:   :py:class:`~.RegGeom`
    :param order: Order of interpolation.
    :type order:  int
    :param dest:  optional, use existing array for result
    :type dest:   Numpy array
    :returns:     Resampled data.
    :rtype:       :py:class:`~.RegData`


Resamples to a regular grid using.

    :param geom:  Regular grid geometry to sample to.
    :type geom:   :py:class:`~.RegGeom`
    :param order: Order of interpolation.
    :type order:  int
    :param dest:  optional, use existing array for result
    :type dest:   Numpy array
    :returns:     Resampled data.
    :rtype:       :py:class:`~.RegData`


Apply a unary function to the data.

    :param op: unary function.
    :type op:  function operating on a numpy array
    :returns:  result.
    :rtype:    :py:class:`~.CompData`


Apply a binary function to two data sets.

    :param a:  Left operand.
    :type a:   :py:class:`~.CompData`
    :param b:  Right operand.
    :type b:   :py:class:`~.CompData`

    :param op: binary function.
    :type op:  function operating on two numpy arrays
    :returns:  f(a,b).
    :rtype:    :py:class:`~.RegData`


    :returns: absolute value.
    :rtype:   :py:class:`~.CompData`


    :returns: sign
    :rtype:   :py:class:`~.CompData`


    :returns: complex phase
    :rtype:   :py:class:`~.CompData`


    :returns: sine
    :rtype:   :py:class:`~.CompData`


    :returns: cosine
    :rtype:   :py:class:`~.CompData`


    :returns: tangens
    :rtype:   :py:class:`~.CompData`


    :returns: arc sine
    :rtype:   :py:class:`~.CompData`


    :returns: arc cosine
    :rtype:   :py:class:`~.CompData`


    :returns: arc tangens
    :rtype:   :py:class:`~.CompData`


    :returns: hyperbolic sine
    :rtype:   :py:class:`~.CompData`


    :returns: hyperbolic cosine
    :rtype:   :py:class:`~.CompData`


    :returns: hyperbolic tangens
    :rtype:   :py:class:`~.CompData`


    :returns: hyperbolic arc sine
    :rtype:   :py:class:`~.CompData`


    :returns: hyperbolic arc cosine
    :rtype:   :py:class:`~.CompData`


    :returns: hyperbolic arc tangens
    :rtype:   :py:class:`~.CompData`


    :returns: square root
    :rtype:   :py:class:`~.CompData`


    :returns: exponential
    :rtype:   :py:class:`~.CompData`


    :returns: natural logarithm
    :rtype:   :py:class:`~.CompData`


    :returns: base-10 logarithm
    :rtype:   :py:class:`~.CompData`


    :returns: real part
    :rtype:   :py:class:`~.CompData`


    :returns: imaginary part
    :rtype:   :py:class:`~.CompData`


    :returns: complex conjugate
    :rtype:   :py:class:`~.CompData`


    :param b: data to compare to
    :type b:  :py:class:`~.CompData`
    :returns: element-wise maximum
    :rtype:   :py:class:`~.CompData`


    :param b: data to compare to
    :type b:  :py:class:`~.CompData`
    :returns: element-wise minimum
    :rtype:   :py:class:`~.CompData`


internal helper function.


Convert 1D refined grid hierachy into irregularly (piecewise
  regularly) spaced 1D data, using the finest level available at each
  interval.

  :param comps: Grid hierachy.
  :type comps:  :py:class:`~.CompData`
  :returns:     coordinates and data values.
  :rtype:       two 1d numpy arrays


returns matrix-vector product m*v


returns matrix-vector product v*m


Dot product of vectors.


Returns determinant. Currently, only supported for 3x3 and smaller
    matrices.


returns inverse matrix. Currently, only supported for 3x3 and smaller
    matrices.


Save peaks to human readable file.

    :param string fname:  The filename.


Convert RegData to vtkImageData data.


Construct a vtkColorTransferFunction in the range (vmin,vmax).
  The colors have to be in the range [0,1].


Construct a vtkLookupTable.


Snap a given grid to the next finest grid in the data.

    :param geom:  the initial geometry
    :type geom:   :py:class:`~.RegGeom` instance
    :param name:  variable from which to read grid spacing.


Read grid data for given variable and iteration.

    This can either return a grid hierarchy or resample to a uniform
    grid. For the latter, there is an option to return the refinement
    level used for each point instead of the data.

    :param name:   variable to read.
    :param it:     iteration to read.

    :param geom:            if given, resample to uniform grid.
    :type geom:             :py:class:`~.RegGeom` instance
    :param adjust_spacing:  whether to snap grid spacing to next finest level.
    :param order:           interpolation order for resampling.
    :type order:            0 or 1
    :param outside_val:     fill value for points not covered by data.
    :param level_fill:      if True, return refinement level instead of actual data.


Load complex Moncrief variables Qodd or Qeven from seperate
     files for real and imaginary part.


Check if a given multipole component extracted at a given
    distance is available.

    :param l:     Multipole component l.
    :type l:      int
    :param m:     Multipole component m.
    :type m:      int
    :param dist:  Distance of detector.
    :type dist:   float

    :returns:     If available or not
    :rtype:       bool


DEPRECATED. Load scalar CACTUS timeseries in 3 column ASCII format, e.g.
  rho.maximum.asc. If the file contains overlapping time intervals
  (as happens when restarting in the same directory), the latest
  of the overlapping segments is kept and the others removed.

  :param string fname: Path to the data file.
  :returns:            The time series.
  :rtype:              :py:class:`~.TimeSeries`


DEPRECATED. Load 0D CACTUS ASCII timeseries, e.g. rho..asc.
  If the file contains overlapping time intervals (as happens when
  restarting in the same directory), the latest of the overlapping
  segments is kept and the others removed.

  :param string fname: Path to the data file.
  :returns:            The time series.
  :rtype:              :py:class:`~.TimeSeries`


Whether shape is available at a given time

    :param float t: Time.
    :param tol:     Tolerance for time match. Default: infinite.
    :type tol:      float or None.

    :returns:       If shape info is available.
    :rtype:         bool


Whether shape is available at iteration it.

    :param int it: Iteration.

    :param tol:    Tolerance for iteration number match. Default: infinite.
    :type tol:     int or None.
    :returns:      If shape info is available.
    :rtype:        bool


Load and parse a Cactus parameter file given by path. If guess_types
  True, the function will try to guess the type of the parameters and bring
  them into canonic form, e.g. 0.0001 will become a float, no or false will
  become a bool. This can go wrong, e.g. a string parameter set to "yes" would
  be read as bool. This function knows about some parameters representing
  lists of Cactus grid functions, and tries to bring them in canonic form,
  unless parse_varlists is False. If unparsable content is encountered, a
  warning is printed.

  .. Note:: This does not know anything about default values.

  .. Warning:: Cactus might parse parameter files slightly different
     in some corner cases.

  :param string path:  Location of the parfile.
  :param bool parse_varlists: Whether to bring known variable list parameters
   into canonical form.
  :param bool guess_Types: Whether to guess parameter types and convert into
   canonical form.

  :returns: The extracted parameters
  :rtype: :py:class:`Parfile`


Not intended to be used directly


Create a document section. You need to specify a title and a short name.
     The short name is used e.g. in navigation bars if the document is rendered as HTML.
     The section can consist of a list of subsection given by parameter subs,
     *or* just normal content (no subsection elements) given as a list in cont.


Create a subsection. You need to specify a title and a short name.
     The short name is used e.g. in navigation bars if the document is rendered as HTML.
     The content is given as a list by the cont parameter.


Create a paragraph. cont is either plain text or a list containing text-like elements,
     e.g. integers, floats, emphasized text, etc.


Create an ordered list. cont is list of the items. The items need to be text-like,
     e.g. plain text, integers, floats, emphasized text, etc.


Create an unordered list. cont is list of the items. The items need to be text-like,
     e.g. plain text, integers, floats, emphasized text, etc.


Create a table. cont is a list of rows. The first row will be the header.
     Each row is a list of elements. The rows should contain the same number of elements.
     Elements can be lists themselves. The table will be inserted in the text if no caption
     is specified, else it will be a floating element with a caption. A table number
     will be added automatically to the caption.


Create a figure. The path is either relative to the main document path, or absolute.
     The path should not contain the extension. The suitable formats will be chosen
     automatically. If no caption is specified, the figure will be inserted in the text
     flow. Else, the figure will be a floating element with caption, and a figure number
     is added automatically.


Create a movie. The path is either relative to the main document path, or absolute.
     If no caption is specified, the movie will be inserted in the text
     flow. Else, the movie will be a floating element with caption.


Create a listing. The content cont is a plain string. Linebreaks in the content
     will be preserved. Optionally, one can highlight bad words in the list alarming.


Create a floating point number. The value is given by v, the number of digits
     to display by digits. If you don't need to specify the number of digits, just use
     a float number instead of this function.


 This is the place to call postprocessing scripts which produce plots or other data.
  datadir is the directory where the data is.
  simdir is a python object providing easy acces to various Cactus data
  stored in datadir.
  repdir is the place where the figures should be saved in by the scripts.

  For this example we simply copy a picture to repdir.


Here we define the content shown from this module in the report


        Replaces NIFTY's exp-function.

        See Also
        --------
        nifty.nifty_core.exp

        Notes
        -----
        This exp-function restricts input values to be smaller than 709 in
        order to avoid infinite return values.


        Replaces NIFTY's log-function.

        See Also
        --------
        nifty.nifty_core.log

        Notes
        -----
        This log-function restricts input values to be larger than 1E-323 in
        order to avoid infinite return values.


            Updates the configuration.

            See Also
            --------
            problem

            Notes
            -----
            This workaround updates the configuration; e.g., with problem
            specific parameters such as ``kindex``.


Resets the Levenberg damping term.


            Applies the inverse of ``F`` to a given object.

            Parameters
            ----------
            x : {scalar, ndarray, field}
                Input object.

            Returns
            -------
            y : field
                Mapped field.

            Other Parameters
            ----------------
            force : bool
                Indicates wheter to return a field instead of ``None`` in case
                the conjugate gradient fails.
            W : {operator, function}, *optional*
                Operator `W` that is a preconditioner on `A` and is applicable to a
                field (default: None).
            spam : function, *optional*
                Callback function which is given the current `x` and iteration
                counter each iteration (default: None).
            reset : integer, *optional*
                Number of iterations after which to restart; i.e., forget previous
                conjugated directions (default: sqrt(b.dim())).
            note : bool, *optional*
                Indicates whether notes are printed or not (default: False).
            x0 : field, *optional*
                Starting guess for the minimization.
            tol : scalar, *optional*
                Tolerance specifying convergence; measured by current relative
                residual (default: 1E-4).
            clevel : integer, *optional*
                Number of times the tolerance should be undershot before
                exiting (default: 1).
            limii : integer, *optional*
                Maximum number of iterations performed (default: 10 * b.dim()).


Computes the effective diffuse contribution.


Computes the effective point-like contribution.


            Computes the (unnormalized) Poissonian likelihood.

            Parameters
            ----------
            l : field
                Expected or most likely number of photon counts.

            Returns
            -------
            E : float
                Likelihood.

            Notes
            -----
            Confer D3PO reference equation (9).


            Computes the Hamiltonian and its gradient with respect to ``s``.

            Notes
            -----
            Confer D3PO reference equation (31) and (32) disregarding ``u``.


            Computes the Gibbs free energy and its gradient with respect to ``s``.

            Notes
            -----
            Confer D3PO reference equation (48) and (49) disregarding ``u``.


            Computes the Hamiltonian and its gradient with respect to ``s``.

            Notes
            -----
            Confer D3PO reference equation (31) and (32).


            Computes the Gibbs free energy and its gradient with respect to ``s``.

            Notes
            -----
            Confer D3PO reference equation (48) and (49).


Evaluates energy and gradient for the diffuse signal field.


            Computes the Hamiltonain and its gradient with respect to ``u``.

            Notes
            -----
            Confer D3PO reference equation (31) and (33).


            Computes the Gibbs free energy and its gradient with respect to ``u``.

            Notes
            -----
            Confer D3PO reference equation (48) and (50).


Evaluates energy and gradient for the point-like signal field.


Calculates the operator ``D`` in the harmonic basis using CG.


Calculates the diagonal of the operator ``D`` in the image basis using CG.


Calculates the diagonal of the operator ``F`` in image basis using CG.


            Calculates the diagonal of the operator ``F`` in image basis using CG,
            evaluated at certain positions only.


Infers the current power spectrum using *critical smooth filtering*.


Optimizes the current diffuse signal field using SD.


Optimizes the current power spectrum.


Optimizes the current point-like signal field using SD.


Optimizes the current diffuse signal (co)variance.


Optimizes the current point-like signal (co)variance.


Infers the current diffuse contributions.


Infers the current point-like contributions.


Raises an initial guess for the diffuse signal field.


            Raises an initial guess for the point-like signal field.

            Point sources are rasied by increasing ``u`` at the
            most promising positions iteratively.


            Optimizes all parameters until convergence.

            Parameters
            ----------
            cycle : integer
                Starting cycle (default: 0).

            Notes
            -----
            The global optimization of all problem parameters is done in cycles
            until convergence. Given default configuration: Cycle 0 yields an
            initial `s` estimate, and rough `u`, `s`, and `p` estimate;
            Cycle 1 yields a second rough estimate after forgetting the others;
            Cycle 2+ yield estimates for `u`, `F`, `s`, `p`, and `D`; and the
            aftermath cycles (<0) improve the estimates on `F` and `D`.
            For details ...

            See Also
            --------
            _infer_s, _infer_u

            Raises
            ------
            KeyboardInterrupt
                If KeyboardInterrupt is encountered but states current cylce to
                allow to resume the optimization.


            Solves the problem.

            Parameters
            ----------
            d : {list, array, field}
                A given data set.
            resume : {bool, integer}, *optional*
                Restarting cycle (default: False).

            See Also
            --------
            optimize

            Raises
            ------
            ValueError
                If data domain and response target do not match, or if negative
                count data is encountered.


            Applies a point spread function by convolving the input array with
            the corresponding kernel.

            Parameters
            ----------
            x : ndarray
                Input 2D array.

            See Aslo
            --------
            scipy.signal.sepfir2d

            Returns
            -------
            y : ndarray
                Convolved output 2D array.


        Loads all objects relevant for the D3PO demonstration

        Parameters
        ----------
        demodirectory : string
            Directory whereto the demo files are located.

        Raises
        ------
        IOError
            If one of the demo files is missing.

        Retrurns
        --------
        R : convulotion_operator
            Response operaotr of the D3PO demonstration.
        d : field
            Data vector of the D3PO demonstration.


Returns main MS table, applying TaQL selection if any


        Factory: Initializes a gridding machine for this facet
        Args:
            iFacet: index of facet

        Returns:
            grid machine instance


Updates this Parset with all keys found in other parset


 Method to define set of reference images to be tested.
            Can be overridden to add additional output products to the test.
            These must correspond to whatever is used in writing out the FITS files (eg. those in ClassDeconvMachine.py)
            Returns:
                List of image identifiers to reference and output products


 Method defining maximum error tolerance between any pair of corresponding
            pixels in the output and corresponding reference FITS images.
            Should be overridden if another tolerance is desired
            Returns:
                constant for maximum tolerance used in test case setup


 Method defining maximum tolerance for the mean squared error between any
            pair of FITS images. Should be overridden if another tolerance is
            desired
            Returns:
            constant for tolerance on mean squared error


        Ensure we have the image in RA-DEC-POL-FREQ axes order.
        Helper function for tp2vis()


        Re-arrange axes and make a RA-DEC-POL-FREQ cube. assume
        axinorder() is already run and 4 axes exist in order.
        Helper function for tp2vis()
        input:   image
        output:  temporary image name


 guess array name from MS
    this function uses the definitions of known arrays at the beginning
    of this code. See t2v_arrays[]
    msfile:    measurement set name
    Helper function for tp2vis()
    CAVEAT: analysis of the ANTENNA table is no guarentee that a dish
    is used in the correlations.


 return 2d kernel image of schwab's spheroidal function (Schwab 1984)

    CASA's sdimaging() uses the tabulated approx. of spheroidal function
    in Schwab 1984. Schwab's definition is different from the common
    definition as used in scipy. Within Schwab, the definition of
    key parameters (e.g., alpha, m) are not consistent in text and in table.
    Using the definition in the Schwab's table, the Schwab's spheroidal
    function is related to the scipy's as:

    Schwab(alpha,m,eta) =
      (1-eta^2)^((2-alpha)/2) *  scipy.special.pro_ang1(0, 0, m*pi/2, eta)[0]
    This means in the scipy's notation, n=0, alpha=m=0, and gamma=m*pi/2.
    In our definition, dist2d is eta, and the new parameter rscale to
    Note again that this alpha and m are different from Schwab's.

    Required:
    ---------
    alpha       Schwab's parameter alpha
    m           Schwab's parameter m
    rscale      size of kernel - it becomes zero at pixel=rscale
    dist2d      2d image that contains distances from center


    Required:
    ---------
    infile    Input IM filename,  in Jy/beam.  Must exist
    outfile   Output MS filename. Must not exist
    ptg       this can be one of:
              None:     NOT ALLOWED ANYMORE UNTIL RE-IMPLEMENTED TO AUTO_FILL
              string:   ptg file  (or list of strings?) - see also qtp_ms_ptg() [OK]
              list:     list of strings (from e.g. qtp_ms_ptg())   [OK]
              ms:       MS containing the pointings [not implemented]
    Optional:
    ---------
    maxuv     maximum uv distance of TP vis distribution (in m)
              default=10m for 12m ALMA dish
    rms       set the RMS (by default this will be ignored) in the infile
              in order to compute an initial guess for the weights
              Should be Jy/beam
              See also tp2viswt(mode=3)
    nvgrp     Number of visibility group (nvis = 1035*nvgrp)
              The number of antenna is hardcoded as 46
    deconv    Use deconvolution as input model? (True)
              When you have a Jy/pixel map, you want to set deconv=False
    winpix    Width of the Tukey window to reduce aliasing [=0 for no window],
              Number of pixels from each edge
    Some Technical Background:
    --------------------------
    There are 46 virtual antennas, each pointing will be visited 'nvgrp' times before
    going to the next field. Within each there are gaussian distributed 1035 visibilities
    as we don't store auto-correlations. Antenna positions are arbitrary, we only randomize
    the distribution in UV, and force a (0,0) for total flux. Thus UV is not derived from
    the antpos.


    Return just a set of baselines from a single pointing TP2VIS, a hacked version of tp2vis()

    Required:
    ---------
    infile    Input IM filename. The WCS of this file is used to set the RA,DEC and spectral
              axis of the MS.

    Optional:
    ---------
    ptg       string:   the RA,DEC of the source to be observed, if to override from infile
    dish      Dish size (12m for ALMA)

    maxuv     maximum uv distance of TP vis distribution (in m)
              default=10m for 12m ALMA dish

    nvgrp     Number of visibility group (nvis = 1035*nvgrp)
              The number of antenna is hardcoded as 46


        A patch to work with dishes that are not 12m (currently hardcoded in tp2vis.py)

        @todo   explain relationship to qac_vp()
        E.g. for GBT (a 100m dish) you would need to do:

        qac_tpdish('ALMATP',100.0)
        qac_tpdish('VIRTUAL',100.0)

        Note that ALMATP and VIRTUAL need to already exist.


    Parameters
    -----------
    mslist     MS(s) to report weights, or compute new weights for
    value      (mode=1,2,3) value to be applied applied to weight

    mode       0 or 'statistics'   (default)
               1 or 'constant'
               2 or 'multiply'
               3 or 'rms'
               4 or 'beammatch'
    makepsf    True/False for mode='beammatch'
    Example usage:
    --------------
    Report weights for "v1.ms"
    > tp2viswt("v1.ms",mode='stat')

    Set weights to 0.01
    > tp2viswt("v1.ms",mode='const',value=0.01)

    Multiply weights by 3
    > tp2viswt("v1.ms",mode='mult',value=3.0)
    Set weights to match beam sizes [need all MSs as input]
    > tp2viswt(["tp.ms","v07m.ms","v12m.ms"],mode='beam',makepsf=True)


    Mismatch of dirty and clean/restore beam areas become noticable in
    TP+INT joint-deconvolution. This function compares the two beam areas,
    rescales the flux density in residual map, and re-calculates the cleaned map.
    Note the mismatch problem exists even for INT alone, but without TP,
    the true flux is not known, so the problem is not noticable.
    Parameters
    -----------
    dirtyname   pre-name of dirty images (normally the filename without '.image')
    cleanname   pre-name of clean images
    pbcut       cutoff level of .pb map to define area for flux integration
                @todo clean() was using minpb=,   tclean() now uses pblimit=
    mask        user specified mask
    dirty and clean images must have the same shape, and it is assumed that
    your version of tclean() has also create the corresponding .residual and
    .pb images.
    Example usage:
    --------------
    Adjust beam size of residual image and add model and residual.
    > tp2vistweak('dirty','clean')
    This will expect 'dirty.image' and 'clean.image' as well as
    'clean.pb' and 'clean.residual'
    > tp2vistweak('dirty','clean',pbcut=0.9,mask='test_clean.image>10')


    Plotting TP, 7m, and 12m MSs
    MS should have been mstransform'd to the same freq range
    Parameters:
    -----------
    # need at least msTP
    mslist    list of measurement sets to plot
    ampPlot   True     amp-uvdistance plot
              False    weight-uvdistance plot
    show      True     plot in display as well as in file
              False    not plot in display, but in file
    outfig    file name of output figure


    standardized output from a combination method  (Moser-Fischer, L.)

    imname - file name base
    clean_origin - file name base of intermediate cleaning products that imname is based on (e.g. feather products is based on tclean products)


    convert image brightness unit from Jy/beam to Jy/pixel  (Moser-Fischer, L.)
    a helper for runWSM to prepare the startmodel format

    usemask - masking mode parameter as for tclean
    mask - file name of mask
    pbmask - PB mask cut-off level
    niter - number of iterations spent on this mask


    get maxscale for multiscale-deconvolver (Moser-Fischer, L.)
    a helper for runsdintimg and runtclean

    usemask - masking mode parameter as for tclean
    mask - file name of mask
    pbmask - PB mask cut-off level
    niter - number of iterations spent on this mask


    report selected mask used for tclean/sdint (Moser-Fischer, L.)
    a helper for runsdintimg and runtclean

    usemask - masking mode parameter as for tclean
    mask - file name of mask
    pbmask - PB mask cut-off level
    niter - number of iterations spent on this mask


    check validity of parameters and set up tclean parameters in a uniform manner
    (Moser-Fischer, L.)
    a helper for runsdintimg and runtclean
    Currently, it provides 'cube' and 'mfs' as spectral modes - 'mtmfs'
    might be implemented later.

    steps:
    - check

    vis
    spw -
    field,
    specmode,
    imsize,
    cell,
    phasecenter,
    start,
    width,
    nchan,
    restfreq,
    threshold,
    niter,
    cycleniter,
    usemask,
    sidelobethreshold,
    noisethreshold,
    lownoisethreshold,
    minbeamfrac,
    growiterations,
    negativethreshold,
    mask,
    pbmask,
    interactive,
    multiscale,
    maxscale,
    loadmask,
    fniteronusermask


    runsdintimg (D. Petry, ESO)
    a wrapper around the CASA task "sdintimaging"
    Currently, it provides 'cube' and 'mfs' as spectral modes - 'mtmfs'
    might be implemented later.

    steps:
    - check if SD image has a beam
    - if not present, create perplanebeams in SD image
    - derive multiscale sizes for 'multiscale=True'
    - clean parameter definition as known from tclean (analoguously to 'runtclean')
    --- important fixed parameters you should be aware of:
    restoring beam = common, nterms=1 (to get mfs from mtmfs),
    weighting='briggs', robust = 0.5, gridder = 'mosaic'
    - tidy up file names and rename to a uniform output-naming style
    - exportfits pcbor

    vis - the MS containing the interferometric data
    sdimage - the Single Dish image
             Note that in case you are creating a cube, this image must be a cube
             with the same spectral grid as the one you are trying to create.
    imname - the imagename of the output images
    sdpsf - (optional) the SD PSF, must have the same coords as sdimage
           if omitted or set to '' (empty string), a PSF will be derived
           from the beam information in sdimage
    sdgain - the weight of the SD data relative to the interferometric data
           default: 5
             'auto' - determine the scale automatically (experimental)
    dishdia - in metres, (optional) used if no sdpsf is provided
           default: 12.0
    spw - the standard selection parameter spw of tclean
           default: '' i.e. all SPWs
    field - the standard selection parameter field of tclean
           default: '' i.e. all fields
    specmode - the standard tclean specmode parameter: supported are msf or cube
           default: mfs
    imsize - the standard tclean imsize parameter
            should correspond to the imagesize for the most extended
            interferometer config.
    cell - the standard tclean cell parameter
            should correspond to the cell size for the most extended
            interferometer config, i.e. smallest beam / 5.
    phasecenter - the standard tclean phasecenter parameter
           e.g. 'J2000 12:00:00 -35.00.00.0000'
           default: '' - determine from the input MS with aU.pickCellSize
    start - the standard tclean start parameter
             default: 0
    width - the standard tclean width parameter
             default: 1
    nchan - the standard tclean nchan parameter
             default: -1
    restfreq - the restfrequency to write to the image for velocity calculations
             default: None, example: '115.271GHz'
    threshold - the tclean threshold
    niter - the standard tclean niter parameter
             default: 0, example: niter=1000000
    cycleniter -
    usemask - the standard tclean mask parameter.  If usemask='auto-multithresh', can specify:
             sidelobethreshold, noisethreshold, lownoisethreshold, minbeamfrac, growiterations -
             if usemask='user', must specify mask='maskname.mask'
             if usemask='pb', can specify pbmask=0.4, or some level.
             default: 'auto-multithresh'
    interactive - if True (default) use interactive cleaning with initial mask
                  set using pbmask=0.4
                  if False use non-interactive clean with automasking (you will
                  need to provide the threshold parameter)

    multiscale - if False (default) use hogbom cleaning, otherwise multiscale

    maxscale - for multiscale cleaning, use scales up to this value (arcsec)
              Recommended value: 10 arcsec
             default: 0.
    continueclean - if True, continue the runsdintimg on the sdintimaging products
              from a previous run. ALERT: previous run must have used renameexport=False,
              else the needed products have been renamed or deleted
             default: False
    renameexport - sort out the relevant imaging products and rename them according to
              the DC naming scheme, delete the rest.
              ALERT: if you plan to call runsdintimg again to continue work on the
              image products of the current run, set renameexport=False to keep the sdintimaging
              products in their native output form
             default: True
    loadmask - run sdintimaging with user-specified mask for fniteronusermask*niter iterations
              and continue with auto-masking (usemask='auto-multithresh') for the remaining
              niter*(1-fniteronusermask) iterations
             default: False
    fniteronusermask - adjusting the amount of iterations spend on a usermask for loadmask=True
              allowed values: 0.0 (none in theory, in fact: 1 iteration) - 1.0 (all)
             default: 0.3

    Examples: runsdintimg('gmc_120L.alma.all_int-weighted.ms','gmc_120L.sd.image',
                'gmc_120L.joint-sdgain2.5', phasecenter='J2000 12:00:00 -35.00.00.0000',
                 sdgain=2.5, spw='0', field='0~68', imsize=[1120,1120], cell='0.21arcsec')

              ... will do an interactive clean for an agg. bw. image.
                  A pbmask at level 0.4 will be suggested as a start.

              runsdintimg('gmc_120L.alma.all_int-weighted.ms','gmc_120L.sd.reimported.image',
                 'deepclean-automask-sdgain1.25', phasecenter='J2000 12:00:00 -35.00.00.0000',
                  sdgain=1.25, spw='0',field='0~68', imsize=[1120,1120], cell='0.21arcsec',
                  threshold='0.012Jy', interactive=False)

              ... will run a non-interactive clean for an agg. bw. image using automasking.

              runsdintimg('ngc253.ms','ngc253-b6-tp-cube-200chan.image',
                          'ngc253-sdgain5', spw='0', specmode='cube', field='NGC_253',
                          imsize=[500, 500], cell='1.2arcsec', phasecenter=3, nchan = 200,
                          start=150, width=1, restfreq='230.538GHz')

              ... will run an interactive clean on a cube.


    runWSM (A. Plunkett, NRAO)
    a wrapper around the CASA tasks "TCLEAN" and "FEATHER"
    in order to run TCLEAN with a single dish start model, then combine with FEATHER

    steps:
    - check brightness units of SD image
    - if needed, convert SD image to Jy/pix
    - call 'runtclean' with with SD image as startmodel
    - call 'runfeather'

    vis - the MS containing the interferometric data
    sdimage - the Single Dish image
             Note that in case you are creating a cube, this image must be a cube
             with the same spectral grid as the one you are trying to create.
             ---- DEPRECATED HERE??? -----
    imname - the imagename of the output images
    spw - the standard selection parameter spw of tclean
           default: '' i.e. all SPWs
    field - the standard selection parameter field of tclean
           default: '' i.e. all fields
    specmode - the standard tclean specmode parameter: supported are msf or cube
           default: msf
    imsize - (optional) the standard tclean imsize parameter
            should correspond to the imagesize for the most extended
            interferometer config.
           default: determine from the input MS with aU.pickCellSize
    cell - (optional) the standard tclean cell parameter
            should correspond to the cell size for the most extended
            interferometer config, i.e. smallest beam / 5.
           default: determine from the input MS with aU.pickCellSize
    phasecenter - the standard tclean phasecenter parameter
           e.g. 'J2000 12:00:00 -35.00.00.0000'
           default: '' - determine from the input MS with aU.pickCellSize
    start - the standard tclean start parameter
             default: 0
    width - the standard tclean width parameter
             default: 1
    nchan - the standard tclean nchan parameter
             default: -1
    restfreq - the restfrequency to write to the image for velocity calculations
             default: None, example: '115.271GHz'
    threshold - the threshold for cleaning
             default: None, example: '12mJy'
    niter - the standard tclean niter parameter
             default: 0, example: niter=1000000
    cycleniter -
    usemask - the standard tclean mask parameter.  If usemask='auto-multithresh', can specify:
             sidelobethreshold, noisethreshold, lownoisethreshold, minbeamfrac, growiterations -
             if usemask='user', must specify mask='maskname.mask'
             if usemask='pb', can specify pbmask=0.4, or some level.
             default: 'auto-multithresh'
    ##### sdmasklev - if usemask='user', then use SD image at this level to draw a mask.
    #####          default: 0.3
    interactive - the standard tclean interactive option
             default: True

    multiscale - if False (default) use hogbom cleaning, otherwise multiscale

    maxscale - for multiscale cleaning, use scales up to this value (arcsec)
             Recommended value: 10 arcsec
             default: 0.
    sdfactorh - Scale factor to apply to Single Dish image (same as for feather)
    continueclean - see runtclean
    loadmask - run sdintimaging with user-specified mask for fniteronusermask*niter iterations
              and continue with auto-masking (usemask='auto-multithresh') for the remaining
              niter*(1-fniteronusermask) iterations
             default: False
    fniteronusermask - adjusting the amount of iterations spend on a usermask for loadmask=True
              allowed values: 0.0 (none in theory, in fact: 1 iteration) - 1.0 (all)
             default: 0.3

    Example: runtclean('gmc_120L.alma.all_int-weighted.ms',
                'gmc_120L', phasecenter='J2000 12:00:00 -35.00.00.0000',
                spw='0', field='0~68', imsize=[1120,1120], cell='0.21arcsec',
                threshold='12mJy',niter=100000,
                usemask='auto-multithresh')

    Example: runWSM('gmc_120L.alma.all_int-weighted.ms','gmc_120L.sd.image',
                'gmc_120L.WSM', phasecenter='J2000 12:00:00 -35.00.00.0000',
                spw='0', field='0~68', imsize=[1120,1120], cell='0.21arcsec',
                threshold='12mJy',niter=100000,
                usemask='auto-multithresh')


    runfeather (A. Plunkett, NRAO)
    a wrapper around the CASA task "FEATHER,"

    steps:
    - outsourced?: reorder axes of SD image
    - outsourced?: regrid reordered SD image
    - regrid reordered SD image * INT primary beam = PB attenuated SD image
    - feather INT image with PB attenuated SD image
    - PB correct feather output
    - exportfits pbcor

    intimage - the interferometry image
             default: None, example: 'imagename.image'
    intpb - the interferometry primary beam
             default: None, example: 'imagename.pb'
    sdimage - the Single Dish image
             Note that in case you are creating a cube, this image must be a cube
             with the same spectral grid as the one you are trying to create.
             default: None, example: 'TPimage.image'
    sdfactor - Scale factor to apply to Single Dish image
    featherim - the name of the output feather image
             default: 'featherim'

    Example: runfeather(intimage='',intpb='',sdimage='',featherim='')


    Taken from the SDINT_helper module inside CASA 5.8, state: July, 2021),
    modified by Lydia Moser-Fischer
    _____________________________________________________________________

    Run the feather task to combine the SD and INT Cubes.

    There's a bug in feather for cubes. Hence, do each channel separately.
    FIX feather and then change this. CAS-5883 is the JIRA ticket that contains a fix for this issue....

    TODO : Add the effdishdia  usage to get freq-indep feathering.


    Taken from the SDINT_helper module inside CASA 5.8, state: July, 2021),
    modified by Lydia Moser-Fischer
    _____________________________________________________________________

    extract a channel plane image


    runtclean (A. Plunkett, NRAO, D. Petry, ESO)
    a wrapper around the CASA task "TCLEAN,"

    steps:
    - return mask setup
    - derive multiscale sizes for 'multiscale=True'
    - clean parameter definition as known from tclean (analoguously to 'runsdintimg')
    --- important fixed parameters you should be aware of:
    restoring beam = common, gridder = 'mosaic',
    weighting='briggs', robust = 0.5
    - exportfits pcbor

    vis - the MS containing the interferometric data
    imname - the root name of the output images
    startmodel - start model for cleaning
          default: '' i.e. no start model, example: 'TP.scaled.image'
    spw - the standard selection parameter spw of tclean
           default: '' i.e. all SPWs
    field - the standard selection parameter field of tclean
           default: '' i.e. all fields
    specmode - the standard tclean specmode parameter: supported are msf or cube
           default: msf
    imsize - (optional) the standard tclean imsize parameter
            should correspond to the imagesize for the most extended
            interferometer config.
           default: determine from the input MS with aU.pickCellSize
    cell - (optional) the standard tclean cell parameter
            should correspond to the cell size for the most extended
            interferometer config, i.e. smallest beam / 5.
           default: determine from the input MS with aU.pickCellSize
    phasecenter - the standard tclean phasecenter parameter
           e.g. 'J2000 12:00:00 -35.00.00.0000'
           default: '' - determine from the input MS with aU.pickCellSize
    start - the standard tclean start parameter
             default: 0
    width - the standard tclean width parameter
             default: 1
    nchan - the standard tclean nchan parameter
             default: -1
    restfreq - the restfrequency to write to the image for velocity calculations
             default: None, example: '115.271GHz'
    threshold - the threshold for cleaning
             default: None, example: '12mJy'
    niter - the standard tclean niter parameter
             default: 0, example: niter=1000000
    cycleniter -
    usemask - the standard tclean mask parameter.  If usemask='auto-multithresh', can specify:
             sidelobethreshold, noisethreshold, lownoisethreshold, minbeamfrac, growiterations -
             if usemask='user', must specify mask='maskname.mask'
             if usemask='pb', can specify pbmask=0.4, or some level.
             default: 'auto-multithresh'
    interactive - the standard tclean interactive option
             default: True
    multiscale - if False (default) use hogbom cleaning, otherwise multiscale
    maxscale - for multiscale cleaning, use scales up to this value (arcsec)
             Recommended value: 10 arcsec
             default: 0.
    restart - True (default): Re-use existing images. False: Increment imagename
    continueclean - True: same as 'restart', False(default): Delete old version
    loadmask - run sdintimaging with user-specified mask for fniteronusermask*niter iterations
              and continue with auto-masking (usemask='auto-multithresh') for the remaining
              niter*(1-fniteronusermask) iterations
             default: False
    fniteronusermask - adjusting the amount of iterations spend on a usermask for loadmask=True
              allowed values: 0.0 (none in theory, in fact: 1 iteration) - 1.0 (all)
             default: 0.3

    Example: runtclean('gmc_120L.alma.all_int-weighted.ms',
                'gmc_120L', phasecenter='J2000 12:00:00 -35.00.00.0000',
                spw='0', field='0~68', imsize=[1120,1120], cell='0.21arcsec',
                threshold='12mJy',niter=100000,
                usemask='auto-multithresh')


    Taken from analysisUtils.py (state: Jan 19th, 2021), modified by
    Lydia Moser-Fischer to get the CASA version used for the calibration of the ms.
    Use search='ms.hifa' to detect pipeline calibration (need to verify for cycle 2 data)!

    -------------------------

    Print the history information from a measurement set.
    origin: if specified, only print messages from this (task) origin
    search: if specified, only print messages containing this string
    includeVis: if True, then include the basename of the vis parameter is the search string
    Example: to see the flux scale that was set:
      au.visHistory('uid___A002_Xd1ff61_X5cd_target.ms','setjy','field,fluxde,spw',includeVis=True)
    -Todd Hunter


    wrapper for visHistory to check the CASA version used for calibration
    and the use of the calibration pipeline in CASA 4.2.2, specifically.
    Following the instructions on
    https://casaguides.nrao.edu/index.php/DataWeightsAndCombination
    this funtion tells the user when to double check/correct the combination
    weights, i.e. weight != 1.0 anymore, for concat.


    channel_cutout (L. Moser-Fischer)
    a tool to cut out a range of channels from a cube.
    In contrast to pure IMMATH, this procedure updates the reference frequency of the new cube.
    IMMATH sets perplane beam eventhough the input image has a common beam.
    This procedure fixes the per plane beams in the new cube to a common beam
    again.

    steps:
    - check if channels are set
    - cut out channel range with immath
    - update reference frequency in new cube
    - merge perplanebeams to a common beam

    old_image - the image cube whose channel should be extracted
             default: None, example: 'SD.image'
    new_image - the outputname for the extracted channels
             default: None, example: 'SD_ch3-15.image'
    startchan - first channel to be included (format: int)
             default: None, example: 3
    endchan - last channel to be included (format: int)
             default: None, example: 15

    Example: channel_cutout('SD.image', 'SD_ch3-15.image', startchan = 3, endchan = 15)


    regrid_SD (L. Moser-Fischer)
    (maybe rename to 'regrid_image' - need to check if 'SD only' is mandatory)
    IMREGRID alone does not fix any perplanebeam issues
    - need to smooth to common beam.

    steps:
    - regrid image
    - merge perplanebeams to a common beam

    old_image - the image to be be regridded
             default: None, example: 'SD.image'
    new_image - the outputname of the regridded image
             default: None, example: 'SD.reg'
    template_image - the template image to regrid the input image to
             default: None, example: 'INT.image'

    Example: regrid_SD('SD.image', 'SD.reg', 'INT.image' )


    reorder_axes (L. Moser-Fischer)
    a tool to reorder the axes according to a fixed order defined here

    steps:
    - simple imtrans

    to_reorder - the image whose axes should be reordered
             default: None, example: 'SD.image'
    reordered - the outputname whose axes have been reordered
             default: None, example: 'lowres.ro'

    Example: reorder_axes('SD.image', 'lowres.ro')


    reorder_axes2 (M. Hoffmann, D. Kunneriath, N. Pingel, L. Moser-Fischer)
    a tool to reorder the axes according to a reference/template image
    Replaced by clearer reorder_axes function

    steps:
    - read axes information of template and image to reorder
    - compare axis units and list 'to_reorder' axes according to template's order of units
    - apply the new axis order list to the image to be reordered if the new
      order deviates from the standard order

    template - the reference image
             default: None, example: 'INT.image'
    to_reorder - the image whose axes should be reordered
             default: None, example: 'SD.image'
    reordered - the outputname whose axes have been reordered
             default: None, example: 'lowres.ro'

    Example: reorder_axes('INT.image', 'SD.image', 'lowres.ro')


    make_SD_mask (A. Plunkett, L. Moser-Fischer)
    a tool to generate a mask from an SD image
     ##### and the first auto-masking step in tclean of an interferometric image

    steps:
    - create mask from SD image at a user given fraction of the peak flux
    #####- call 'runtclean' with relevant inputs to create the wanted grid/raster
    #####   and niter=1 to load the SD mask into a clean mask
    #####- rerun 'runtclean' with same parameters except from usemask='auto-multithresh', mask=''
    #####   to add the auto-detected compact emission regions (smoothed out in SD image)
    #####   to the existing clean mask
    #####- rename clean mask to wanted output name (root)

    #####vis - the MS containing the interferometric data
    sdimage - the Single Dish image
             Note that in case you are creating a cube, this SD image must be a cube
             with the same spectral grid as the one you are trying to create from vis.
    #####imname - the root name of the output images
    sdmasklev - if usemask='user', then use SD image at this level to draw a mask.
             typically: 0.3
    SDint_mask_root - the root name of the output mask, extention '.mask' will
             be added automatically
    #####phasecenter - the standard tclean phasecenter parameter
           e.g. 'J2000 12:00:00 -35.00.00.0000'
           default: '' - determine from the input MS with aU.pickCellSize
    #####spw - the standard selection parameter spw of tclean
           default: '' i.e. all SPWs
    #####field - the standard selection parameter field of tclean
           default: '' i.e. all fields
    #####imsize - (optional) the standard tclean imsize parameter
            should correspond to the imagesize for the most extended
            interferometer config.
           default: determine from the input MS with aU.pickCellSize
    #####cell - (optional) the standard tclean cell parameter
            should correspond to the cell size for the most extended
            interferometer config, i.e. smallest beam / 5.
           default: determine from the input MS with aU.pickCellSize
    #####specmode - the standard tclean specmode parameter: supported are msf or cube
           default: 'msf'
    #####start - the standard tclean start parameter
             default: 0
    #####width - the standard tclean width parameter
             default: 1
    #####nchan - the standard tclean nchan parameter
             default: -1
    #####restfreq - the restfrequency to write to the image for velocity calculations
             default: '', example: '115.271GHz'

    ##### Example: make_SDint_mask('gmc_120L.alma.all_int-weighted.ms',
                'gmc_120L.sd.image', 'gmc_120L.get_mask', 0.3, 'INT-SD',
                phasecenter='J2000 12:00:00 -35.00.00.0000',
                spw='0', field='0~68', imsize=[1120,1120], cell='0.21arcsec',
                specmode='cube', start= '1550km/s', width= '5km/s',
                nchan= 10, restfreq = '115.271202GHz')


    derive_threshold (L. Moser-Fischer)
    a tool to derive a reasonable clean threshold and mask for an
    interferometric image

    steps:
    - create dirty image if needed,
    - get an RMS (continuum: RMS of full image (!including emission),
    cube: RMS of moment 6 (RMS) map - right choice of cont_chans makes this
    the true RMS of the cube!),
    - create threshold by applying a user defined factor to the RMS (different
    for continuum and cube due to different RMS definition),
    - make mask from threshold
    - smooth mask by Gaussian with "smoothing"*beam_major and "smoothing"*beam_minor axes
    - turn smoothed mask into a 1,0-mask

    vis - the MS containing the interferometric data
    imname - the root name of the output images
    threshmask - the root name of the threshold mask, extention '.mask' will
             be added automatically
    phasecenter - the standard tclean phasecenter parameter
           e.g. 'J2000 12:00:00 -35.00.00.0000'
           default: '' - determine from the input MS with aU.pickCellSize
    spw - the standard selection parameter spw of tclean
           default: '' i.e. all SPWs
    field - the standard selection parameter field of tclean
           default: '' i.e. all fields
    imsize - (optional) the standard tclean imsize parameter
            should correspond to the imagesize for the most extended
            interferometer config.
           default: determine from the input MS with aU.pickCellSize
    cell - (optional) the standard tclean cell parameter
            should correspond to the cell size for the most extended
            interferometer config, i.e. smallest beam / 5.
           default: determine from the input MS with aU.pickCellSize
    specmode - the standard tclean specmode parameter: supported are msf or cube
           default: msf
    start - the standard tclean start parameter
             default: 0
    width - the standard tclean width parameter
             default: 1
    nchan - the standard tclean nchan parameter
             default: -1
    restfreq - the restfrequency to write to the image for velocity calculations
             default: None, example: '115.271GHz'
    overwrite - True: generate new template INT image: False: just derive
                threshold values and image mask from existing template INT image
    smoothing factor - smooth thresholdmask to multiples beamsizes (smoothing*beamaxis)
            to avoid unphysical mask shapes (too few pixels, straight lines, sharp corners)
    RMSfactor - to apply to a continuum RMS of the full image to define a threshold at which
            as much emission as possible/reasonable is contained; user needs to play with it
            typically: 0.5
    cube_rms - factor to apply to a a cube RMS to define a threshold. channels
            If cont_chans is set to line-free channels, this factor can be used
            to set the threshold as 3sigma, 10sigma, etc level)
    cont_chans - define the line-free channels here to get a pure noise RMS of a cube
    theoreticalRMS -

    Example: derive_threshold('gmc_120L.alma.all_int-weighted.ms',
                'gmc_120L.get_mask', 'gmc_120L.threshmask',
                phasecenter='J2000 12:00:00 -35.00.00.0000',
                spw='0', field='0~68', imsize=[1120,1120], cell='0.21arcsec',
                specmode='cube', start= '1550km/s', width= '5km/s',
                nchan= 55, restfreq = '115.271202GHz',
                overwrite=False, smoothing = 5,
                RMSfactor = 0.5, cube_rms = 3.,
                cont_chans ='2~13;44~54')


    make_masks_and_thresh (L. Moser-Fischer)
    wrapper for making all masks for DC_run

    steps:
    - helper functions for header information (beam, etc.)

    highres  - high resolution (interferometer) image

    Example: ssc(highres='INT.image', lowres='SD.image', pb='INT.pb',
                 combined='INT_SD_1.7.image', sdfactor=1.7)


    ssc (P. Teuben, N. Pingel, L. Moser-Fischer)
    an implementation of Faridani's short spacing combination method
    https://bitbucket.org/snippets/faridani/pRX6r
    https://onlinelibrary.wiley.com/doi/epdf/10.1002/asna.201713381

    steps:
    - helper functions for header information (beam, etc.)
    - outsourced?: reorder axes of SD image
    - outsourced?: regrid reordered SD image
    - regrid reordered SD image * INT primary beam = PB attenuated SD image
    - fix brightness unit of PB attenuated SD image
    - smooth INT image to resolution of PB attenuated SD image = SD convolved INT image
    - PB attenuated SD image - SD convolved INT image = INT subtracted SD image
    - define weightfactor = INT beam area / SD beam area
    - if SD in Jy/beam: INT image + INT subtracted SD image * weightfactor = combined image
    - if SD in Kelvin:  INT image + INT subtracted SD image = combined image
    - PB correct SSC output
    - exportfits pbcor and nopbcorr

    highres  - high resolution (interferometer) image
    lowres   - low resolution (single dish (SD)/ total power (TP)) image
    pb       - high resolution (interferometer) primary beam image
    combined - output image name base
    sdfactor - scaling factor for the SD/TP contribution

    Example: ssc(highres='INT.image', lowres='SD.image', pb='INT.pb',
                 combined='INT_SD_1.7', sdfactor=1.7)


    listobs_ptg (L. Moser-Fischer)
    based on Jin Koda's approach to get 12m pointings from listobs()
    https://github.com/tp2vis/distribute

    TPpointingTemplate - an ALMA 12m data set (before concat?) (ending on *.ms)
    listobsOutput - file name to store the listobs-output      (ending on *.log)
    TPpointinglist - final pointing list for TP2VIS            (ending on *.ptg)

    Example: ssc(highres='INT.image', lowres='SD.image', pb='INT.pb',
                 combined='INT_SD_1.7.image', sdfactor=1.7)


    Taken from the Quick Array Combinations (QAC) module, state: March, 2021,
    originally called qac_ms_ptg in
    https://github.com/teuben/QAC/blob/master/src/qac.py

    modified by Lydia Moser-Fischer

    # NOTE: seems to expect a target-only data set!
    _____________________________________________________________________

    get the ptg's from an MS into a list and/or ascii ptg file
    'J2000 19h00m00.00000 -030d00m00.000000',...
    This is a little trickier than it sounds, because the FIELD table has more entries than
    you will find in the FIELD_ID column (often central coordinate may be present as well,
    if it's not part of the observing fields, and locations of the Tsys measurements
    For 7m data there may also be some jitter amongst each "field" (are multiple SB used?)
    Note that the actual POINTING table is empty for the 12m and 7m data
    # @todo: should get the observing frequency and antenna size, so we also know the PB size
    #
    # @todo: what if DELAY_DIR, PHASE_DIR and REFERENCE_DIR are not the same???


        Decimal value to 3-element tuple of hour, min, sec. Just calls dms/15
        from https://github.com/teuben/QAC/blob/master/src/utils/constutils.py


        Decimal value to 3-element tuple of deg, min, sec.
        from https://github.com/teuben/QAC/blob/master/src/utils/constutils.py


        Convert a numeric vector to a string. Again, QA should do this.
        from https://github.com/teuben/QAC/blob/master/src/utils/constutils.py


    create_TP2VIS_ms (L. Moser-Fischer)
    tool to turn SD image into visibilities

    steps:
    - get rms from SD image/cube
    - make SD visibilities with tp2vis
    - tp2vispl - plots weights of the TP and of the INT data
    _____________________________________________________________________

    mode - specmode
    imTP - SD image (reordered, but not regridded)
    TPresult - output name of the TP visibilities (*.ms)
    TPpointinglist - 12m pointing list (ALMA, *.ptg)
    vis - INT ms-file to compare TP ms-file to
    inmame - output praefix for weightplot
    TPnoiseRegion - if mode='mfs', emission-free box in cont image is used to determine noise
    TPnoiseChannels - if mode='cube', line-free channels in cube are used to determine noise


    transform_INT_to_SD_freq_spec (L. Moser-Fischer)
    tool to transform the INT data to the same reference frame
    and same frequency range as the SD cube has

    else tclean with TP.ms and INT.ms together causes trouble.

    steps:
    - use get_SD_cube_params to derive the frequency range covered by the SD cube
    - mstransform fo given datacolumn to SD cube's freq-range and reference frame

    ----- not applied: mstransforms to spectral setup of the spw with the least number of
    spectral  channels and takes its spectral setup over to all other spw in the data.
    This assumes a similar frequency range for all spws so that not much information
    would be lost. Therefore, beware of mixed data set with strongly differing
    frequnecy coverages!

    _____________________________________________________________________

    imTP - SD image (reordered, but not regridded)
    TPresult - name of the TP visibilities (*.ms)  (actually ....this part of the script
    is not really used anymore  ---- need to modify)
    vis - input name of the INT visibilities (*.ms)
    transvis - output name of the INT visibilities (*.ms)
    datacolumn - data from which column to use (typilcay CASA parameter)
    outframe - reference frame of the transvis output


    runtclean_TP2VIS_INT (L. Moser-Fischer)

    tclean with TP.ms and INT.ms together

    steps:
    - make copy of TP.ms and scale it with tp2viswt (multiply with TPfac)
    - tp2vispl - plot of weights for scaled copy of TP and of the INT data
    - concat scaled TP data and INT data
    - tclean dirty image of concat data
    - derive new threshold
    - tclean with given niter and new threshold
    - correct for beam ratios (true PSF vs. Gaussian restoring) with tp2vistweak
    - export

    _____________________________________________________________________

    TPfac - factor to apply to the visibility weights of the TP visibilities
    TPresult - name of the TP visibilities (*.ms)

    from vis to continueclean analoguous to runtclean

    next 3 parameters as defined as in derive_threshold:

    RMSfactor - to apply to a continuum RMS of the full image to define a threshold at which
            as much emission as possible/reasonable is contained; user needs to play with it
            typically: 0.5
    cube_rms - factor to apply to a a cube RMS to define a threshold. channels
            If cont_chans is set to line-free channels, this factor can be used
            to set the threshold as 3sigma, 10sigma, etc level)
    cont_chans - define the line-free channels here to get a pure noise RMS of a cube


    save dictionaries (L. Moser-Fischer)
    pydict - a python dictionary
    filename - will store dict under this string +'.txt'


    load dictionaries (L. Moser-Fischer)
    filename - will load dict from this string +'.txt'
    return: python dictionary

    problems with arrays, int32,


    load dictionaries (L. Moser-Fischer)
    filename - will load dict from this string +'.txt'
    return: python dictionary


    save docstrings of all functions defined for DC project  (L. Moser-Fischer)
    filename - will store docstrings under this string +'.txt'


    file existence check  (L. Moser-Fischer)
    filename - if filename (string) exists, return filename, else exit script


    special file existence check for vis, i.e. one msfile as string or many as list (L. Moser-Fischer)
    vis - if vis (string/list) exists, return vis, else exit script (via file_check)


    special file existence check for vis accepting only one msfile - no list (L. Moser-Fischer)
    vis - if vis (string/list) exists, return vis, else exit script (via file_check)


    mask_image (A. Hacar, Univ. of Vienna)

    Mask an image (typicaly your reference) below an intensity threshold.
    Thresholding is recommended to avoid noisy data in many of the IQA tests
    Arguments:
      myimage - image to be masked
      threshold - value for thresholding
      relative - (default False)
         False = threshold is taken as absolute value (see image flux units)
         True = threshold value is measured as rms fraction (aka sigma)


    drop_axis (A. Hacar, Univ. of Vienna)

    Drop unnecesary axis (e.g. Stokes)
    Arguments:
     myimage : image wher drop_axis will be applied (CASA image)

    Notes:
     Check axis consistency with check_axis()

    Usage:
     drop_axis(myimage)


    image_Apar (A. Hacar, Univ. of Vienna)

    Function to generate A-par maps
    A-par is defined as the relative error between the target and reference images:
    Apar = (image-reference)/abs(reference)

    Arguments:
      image - target image
      ref_image - reference image
    (Note that the target image should have the same resolution as the target one)

    Outputs:
      str(image)+'_Apar' - A-par image

    Description:
      A=0 - Perfect image
      A>1 - target image overestimates the expected flux in the reference
      A<1 - target image underestimates the expected flux in the reference
      A value - relative difference (in %) between the target and the reference


    image_Fidelity (A. Hacar, Univ. of Vienna)

    Function to generate Fidelity maps
    Fidelity is defined as the ratio between the reference image and the difference between
    target and the reference images all in absolute terms:
    Fidelity = abs(reference)/abs(image-reference)

    Arguments:
      image - target image
      ref_image - reference image
    (Note that the target image should have the same resolution as the reference one)

    Outputs:
      str(image)+'_fidelity' - Fidelity image

    Description:
      The higher the fidelity, the better correspondance between the target and the reference images


    Generate a nosie FITS with similar properties than fitsfile
    Arguments:
      fitsfile - FITS file used as template
      noise - noise level (in whatever units if fitsfile)
      noisefile - name of the file where the results will be stored (default = "noise"+".fits"
    Output:
      str(noisefile)+'.fits' - FITS noise file


    Compare all Apar images (continuum or mom0 maps) (A. Hacar, Univ. of Vienna)

    Arguments:
      ref_image - image used as reference
      target_image - list of images to be compared with reference
      adjustDR - adjust DR in plot
      save - save plot? (default = False)
    Requires:
      The script will look for target_image[i]_convo2ref_Apar.fits images produced by the get_IQA() script

    Results:
      1- Histogram including the Apar distributions for all input images
      2- Numerical results: Total flux in the image, mean + std + kurtosis + skewness of each histogram

    Example:
      Compare_Apar(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'])


    Compare_Apar_signal (A. Hacar, Univ. of Vienna)

    Compare all Apar images vs signal (continuum or mom0 maps).
    If No. of targets = 1, the mean and std of A-par will be calculated.
    This function can be applied in both cont/mom0 and cubes FITS files.

    Arguments:
      ref_image - image used as reference
      target_image - list of images to be compared with reference
        (recommended to <= 4 targets)
      adjustDR - adjust dynamic range in plot (default = True)
      Nbins - number of bins in plot (default = 15)
      save - (optional) save plot? (default = False)
      noise - (optional) if noise > 0.0 the evolution of the noise level
        will be displayed

    Requires:
      The script will look for target_image[i]_convo2ref_Apar.fits images produced by the get_IQA() script

    Results:
      Apar as function of reference & target signals

    Example 1: compare a list of targets
      Compare_Apar_signal(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'])

    Example 2: investigate singel target (incl. A-par statistics)
      Compare_Apar_signal(ref_image = 'TP_image',target_image=['Feather.image'],noise=0.5)


    Compare_Flux_signal (A. Hacar, Univ. of Vienna)

    Compare Flux recovery in images vs signal (continuum or mom0 maps).
    This function can be applied in both cont/mom0 and cubes FITS files.

    Arguments:
      ref_image - image used as reference
      target_image - list of images to be compared with reference
        (recommended to <= 4 targets)
      adjustDR - adjust dynamic range in plot (default = True)
      Nbins = Number of bins in plot (default = 15)
      save - (optional) save plot? (default = False)
      noise - (optional) if noise > 0.0 the evolution of the noise level
        will be displayed

    Requires:
      The script will look for target_image[i]_convo2ref_Apar.fits images produced by the get_IQA() script

    Results:
      Flux recovery as function of reference signals both in absolute and relative terms

    Example 1: compare a list of targets
      Compare_Flux_signal(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'])

    Example 2: investigate single target
      Compare_Flux_signal(ref_image = 'TP_image',target_image=['Feather.image'])


    Compare all Fidelity images (continuum or mom0 maps) (A. Hacar, Univ. of Vienna)

    Arguments:
      ref_image - image used as reference
      target_image - list of images to be compared with reference
      save - save plot? (default = False)
    Requires:
      The script will look for target_image[i]_convo2ref_Fidelity.fits images produced by the get_IQA() script

    Results:
      1- Histogram including the Fidelity distributions for all input images
      2- Numerical results: Total flux in the image, mean + std + kurtosis + skewness of each histogram

    Example:
      Compare_Fidelity(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'])


    Compare all Fidelity images vs signal (continuum or mom0 maps) (A. Hacar, Univ. of Vienna)

    Arguments:
      ref_image - image used as reference
      target_image - list of images to be compared with reference (better only one)
      save - save plot? (default = False)
    Requires:
      The script will look for target_image[i]_convo2ref_Apar.fits images produced by the get_IQA() script

    Results:
      Fidelity vs signal in the original image

    Example:
      Compare_Fidelity_signal(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'])


    Compare all Apar cubes (per channel) (A. Hacar, Univ. of Vienna)

    Arguments:
      ref_image - image used as reference
      target_image - list of images to be compared with reference
      save - save plot? (default = False)
      showchannels - which channels to show, default [0,0] = ALL
    Requires:
      The script will look for target_image[i]_convo2ref_Apar.fits cubes produced by the get_IQA() script

    Results: (for each target)
      1- (left) A-par Spectrogram (density plot per channel)
      2- (right) vertical histogram per channel (grey) + average (red)

    Example:
      Compare_Apar_cubes(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'])


    Compares all Fidelity cubes (per channel) (A. Hacar, Univ. of Vienna)

    Arguments:
      ref_image - image used as reference
      target_image - list of images to be compared with reference
      save - save plot? (default = False)
    Requires:
      The script will look for target_image[i]_convo2ref_Fidelity.fits cubes produced by the get_IQA() script

    Results: (for each target)
      1- (left) Fidelity Spectrogram (density plot per channel)
      2- (right) vertical histogram per channel (grey) + average (red)

    Example:
      Compare_Fidelity_cubes(ref_image = 'TP_image',target_image=['Feather.image','TP2vis.image'])


    Display Accuracy maps (A. Hacar, Univ. of Vienna)
    Arguments:
     ref_image - reference image
     target_image - imaged to be compared
     channel - (for cubes only) channel to be compared (default = 0, aka continuum)

    Note:
     Generate the necessary imaged (e.g. target_image_convo2ref.fits) using get_IQA()

    Results: show_Apar_map will display a figure with 4 subpanels:
     - [1] (Upper left)  Reference image
     - [2] (Upper right) Target image at the resolution of the referenec
     - [3] (Lower left)  Accuracy map
     - [4] (Lower right) Histogram


    Display Fifelity maps (A. Hacar, Univ. of Vienna)
    Arguments:
     ref_image - reference image
     target_image - imaged to be compared
     channel - (for cubes only) channel to be compared (default = 0, aka continuum)

    Note:
     Generate the necessary imaged (e.g. target_image_convo2ref.fits) using get_IQA()

    Results: show_Apar_map will display a figure with 4 subpanels:
     - [1] (Upper left)  Reference image
     - [2] (Upper right) Target image at the resolution of the referenec
     - [3] (Lower left)  Fidelity map
     - [4] (Lower right) Histogram


    gensps
    Script to plot the power spectra of a user provided general 2D FITS file
    Arguments:
      fitsimages - list of names of input images
      save      - save plot? (default False)


    Display Accuracy maps (A. Hacar, Univ. of Vienna)
    Arguments:
     ref_image - reference image
     target_image - imaged to be compared
     channel - (for cubes only) channel to be compared (default = 0, aka continuum)
     adjustDR - adjust dynamic range (default = True)
     Nbins - number of bins in plot (default = 10)

    Note:
     Generate the necessary imaged (e.g. target_image_convo2ref.fits) using get_IQA()

    Results: show_Apar_map will display a figure with 4 subpanels:
     - [1] (Upper left)  Reference image
     - [2] (Upper right) Target image at the resolution of the referenec
     - [3] (Lower left)  Accuracy map
     - [4] (Lower right) Histogram


    Total flux within a square region at different radii center at a position (x,y)
    Script based on the same one produce by B.Mason
    Arguments:
     imvals - 2D array
     pixel - (x,y) central coordinates (in pixel units)
     max_radius - maximum number of beams in which it will be calculated (in beam units)
     pix_beam - pixels per beam


    Display Residual maps (L. Moser-Fischer)
    Arguments:
     target_image - list of images to be compared (FITS)
     channel - (for cubes only) channel to be compared (default = 0, aka continuum)

    Note: plots up to 4 plots!

    Results: show_Apar_map will display the residual map for each tclean instance used by the chosen
    combination method and the corresponding tclean feedback (stopping criteria etc.)


    Display combination image maps (L. Moser-Fischer)
    Arguments:
     target_image - list of images to be compared (FITS)
     channel - (for cubes only) channel to be compared (default = 0, aka continuum)

    Note: plots up to 4 plots!

    Results: show_Apar_map will display the residual map for each tclean instance used by the chosen
    combination method and the corresponding tclean feedback (stopping criteria etc.)


    This function allow to define the resolution of a matplotlib plot on a way
    wich is device independent. Put this before saving any of your plot to get
    homogeneous resolution.


    This function plot the pval in fuction of the radius for the found objects
    (we don't plot objects with pval>0.95)


Query the provided position with the given radius and catalog


        This function compute the final p value of the association

        Input parameters
        ----------------


        This function parse all the computation result to an readable table

        Input parameters
        ----------------


        This function add a column in the output file checking if the redshift
        is compatible with the provided values.


We have to compute the distance between each objects and the transient error box center


Final function call by ../crosmatch/HostHunt.py to compute pval for each transients


Adding information about object type


    This function count the number of galaxies in the outputed (and parsed) query from Pan-STARRS
    AllWISE and GLADE.

    Input parameters
    ----------------
    query_transient_box: astropy table
         Results of the query centered on the transient position
    query_random: astropy table
         Results of the query centered on the randomly drawned positions,
         or results of the query with big_radius
    RA: float
        RA of the best transient localisation
    Dec: float
        Dec of the best transient localisation


Return metadata for the specified catalog and table

    Parameters
    ----------
    table (string): summary, detailed, propermotions, or sourcepositions
    release (string): v3 or v2
    magtype (string): magaper2 or magauto (only applies to summary table)
    baseurl: base URL for the request

    Returns an astropy table with columns name, type, description


Return URL for the specified catalog and table

    Parameters
    ----------
    table (string): summary, detailed, propermotions, or sourcepositions
    release (string): v3 or v2
    magtype (string): magaper2 or magauto (only applies to summary table)
    baseurl: base URL for the request

    Returns a string with the base URL for this request


Checks if this combination of table, release and magtype is acceptable

    Raises a ValueError exception if there is problem


Perform a MAST query.

    Parameters
    ----------
    request (dictionary): The MAST request json object
    url (string): The service URL

    Returns the returned data content


Get the RA and Dec for an object using the MAST name resolver

    Parameters
    ----------
    name (str): Name of object

    Returns RA, Dec tuple with position


Transform the HSC query into an astropy table


Do a general search of the HSC catalog (possibly without ra/dec/radius)

    Parameters
    ----------
    table (string): summary, detailed, propermotions, or sourcepositions
    release (string): v3 or v2
    magtype (string): magaper2 or magauto (only applies to summary table)
    format: csv, votable, json
    columns: list of column names to include (None means use defaults)
    baseurl: base URL for the request
    verbose: print info about request
    **kw: other parameters (e.g., 'numimages.gte':2).  Note this is required!


Do a cone search of the HSC catalog

    Parameters
    ----------
    ra (float): (degrees) J2000 Right Ascension
    dec (float): (degrees) J2000 Declination
    radius (float): (degrees) Search radius (<= 0.5 degrees)
    table (string): summary, detailed, propermotions, or sourcepositions
    release (string): v3 or v2
    magtype (string): magaper2 or magauto (only applies to summary table)
    format: csv, votable, json
    columns: list of column names to include (None means use defaults)
    baseurl: base URL for the request
    verbose: print info about request
    **kw: other parameters (e.g., 'numimages.gte':2)


    In the HSC summary catalog there is no extended flag, we have to fetch it from the detailed one.
    So in this function we do two query and add a columns in the summary output with the extended
    flag info for each objects

    Also we save the image ID for each object for later uses


    This function classifie as 'galaxy','star' or 'unknown' the compatible object
    using the flag present in the HSC catalog

    Input parameters
    ----------------


    This function search for nearby bright galaxy in the RC3 catalog
    (https://heasarc.gsfc.nasa.gov/w3browse/all/rc3.html)
    If any galaxy is found, a warning is printed and the galaxy properties
    are stored in the result directory
    Parameters
    ----------
    ra : float
        right ascension
    dec : float
        declination
    radius : float
        radius for the search. The default is 30 arcsec.


        This returns the peak pixel value of the stamp
        @return:        A tuple containing the maximum pixel
                                value and a tuple of its location


        This returns the minimum pixel value of the stamp
        @return:        A tuple containing the minimum pixel
                                value and a tuple of its location


        This saves a fits file based on the internal stamp of the object
        @type filename:         string
        @param filename:        The filename to save the FITS file as


        This is an private method used to compute the
        median noise of an outer "frame" 5+ pixels thick.
        @type bpercent:         int
        @param bpercent:        The percentage of the total image
                                                size to make the frame for
        @return:                The value of the median noise
                                        computed over the outer frame.


        This is an private method used to compute the
        mean noise of an outer "frame" 5 pixels thick.
        @type bpercent:         int
        @param bpercent:        The percentage of the total image
                                                size to make the frame for
        @return:                The value of the mean noise
                                        computed over the outer frame.


        This is an private method used to compute the
        rms of an outer "frame" 5 pixels thick.
        @type bpercent:         int
        @param bpercent:        The percentage of the total image
                                                size to make the frame for
        @type mean:                     number
        @param mean:            Pass the mean of the box if you want to calculate
                                                the standard deviation rather than the rms
        @return:                        The value of the rms noise
                                                computed over the outer frame.


        This method is used to regrid the image to allow >1 pixel accuracy
        @type factor:           number
        @param factor:          the factor to scale the image by


        This method is used to scale the image stamp using cubic splines
        @type factor:           number or (number,number)
        @param factor:          the factor to scale the image by


        This method merges a Q and U stamp into one new stamp, by adding the
        two stamps in quadrature.
        @type stamp:    stampy
        @param stamp:   the stamp to merge into this one


        This method adds a constant value offset to each pixel in the stamp.
        @type value:    number
        @param value:   The value to be added to the stamp


        This method multiplies each pixel in the stamp by a constant value.
        @type value:    number
        @param value:   The value to be multiplied by the stamp


        This method adds a seeded 2D gaussian with a specified peak value and
        FWHM to the position in the source list.
        @type peak:             number
        @param peak:    The peak value for the seeded gaussian
        @type FWHM:             number
        @param FWHM:    The FWHM of the seeded gaussian


        This method adds another stamp to the stack.
        @type stamp:    Stampy
        @param stamp: The stamp to be added to the stamp stack


        This method returns a stamp of the mean values of the
        stack.
        @rtype:         numpy array
        @return:        The numpy array containing the mean pixels of the stack


        This method returns the a stamp of the median values of the
        stack.
        @rtype:         numpy array
        @return:        The numpy array containing the median pixels of the stack


        This method is used to find the value of the central pixel in the image
        at a certain percentile along the stack.
        @type percent:          number
        @param percent:         The percentile value to be found


        This method returns the a stamp at one percentile value of the
        stack.
        @type percent:  number
        @param percent: percentile value to be calculated
        @rtype:                 numpy array
        @return:                The numpy array containing the median pixels of the
        stack


        This method is used to sort the stack along the z-axis (each pixel
        column)


Returns (height, amplitude, x, y, width_x, width_y, rotation angle)
    the gaussian parameters of a 2D distribution by calculating its
    moments.  Depending on the input parameters, will only output
    a subset of the above


Returns a 2d gaussian function of the form:
        x' = cos(rota) * x - sin(rota) * y
        y' = sin(rota) * x + cos(rota) * y
        (rota should be in degrees)
        g = b + a exp ( - ( ((x-center_x)/width_x)**2 +
        ((y-center_y)/width_y)**2 ) / 2 )

        where x and y are the input parameters of the returned function,
        and all other parameters are specified by this function

        However, the above values are passed by list.  The list should be:
        inpars = (height,amplitude,center_x,center_y,width_x,width_y,rota)

        You can choose to ignore / neglect some of the above input parameters using the following options:
            circle=0 - default is an elliptical gaussian (different x, y widths), but can reduce
                the input by one parameter if it's a circular gaussian
            rotate=1 - default allows rotation of the gaussian ellipse.  Can remove last parameter
                by setting rotate=0
            vheight=1 - default allows a variable height-above-zero, i.e. an additive constant
                for the Gaussian function.  Can remove first parameter by setting this to 0


    Gaussian fitter with the ability to fit a variety of different forms of 2-dimensional gaussian.

    Input Parameters:
        data - 2-dimensional data array
        err=None - error array with same size as data array
        params=[] - initial input parameters for Gaussian function.
            (height, amplitude, x, y, width_x, width_y, rota)
            if not input, these will be determined from the moments of the system,
            assuming no rotation
        autoderiv=1 - use the autoderiv provided in the lmder.f function (the alternative
            is to us an analytic derivative with lmdif.f: this method is less robust)
        return_all=0 - Default is to return only the Gaussian parameters.  See below for
            detail on output
        circle=0 - default is an elliptical gaussian (different x, y widths), but can reduce
            the input by one parameter if it's a circular gaussian
        rotate=1 - default allows rotation of the gaussian ellipse.  Can remove last parameter
            by setting rotate=0
        vheight=1 - default allows a variable height-above-zero, i.e. an additive constant
            for the Gaussian function.  Can remove first parameter by setting this to 0

    Output:
        Default output is a set of Gaussian parameters with the same shape as the input parameters
        Can also output the covariance matrix, 'infodict' that contains a lot more detail about
            the fit (see scipy.optimize.leastsq), and a message from leastsq telling what the exit
            status of the fitting routine was

        Warning: Does NOT necessarily output a rotation angle between 0 and 360 degrees.


		This is an private method used to compute the standard deviation of an
		outer "frame" 5 pixels thick.
		@type n:			ndarray
		@param n:			The array to compute the frame rms noise for.
		@type bpercent:		int
		@param bpercent:	The percentage of the total image size to make the
							frame for
		@return:			The value of the rms noise computed over the outer
							frame.


		This is an private method used to compute the median noise of an outer
		"frame" 5+ pixels thick.
		@type n:			ndarray
		@param n:			The array to compute the frame median noise for.
		@type bpercent:		int
		@param bpercent:	The percentage of the total image size to make the
							frame for
		@return:			The value of the median noise computed over the									outer frame.


should be called only the first time SimState is created
        s: SimState object


Returns a copy of sim_state s (a new SimState instance with all attributes copied)


Chops the irrelevant end of the storage arrays using the relevant end-index


 s: simulation state, numba.jitclass containing all relevant variables
        N: iterate simulation up to N iterations (from s.i)


Calculate the cross product of two 3d vectors.


 Returns the x, v from j, a, e in the simple case where
     j is in the direction of z - axis, e is in the direction of x - axis


 Get eccentric anomaly from mean anomaly
        Solve Kepler equation:
                M = E - e * sin(E)
        iteratively using fixed point method


Get true anomaly from mean anomaly


Computes the expansion terms from Luo et al. (2016)
        See there: eq.(31) and Appendix B1


        Partially set up self with the configuration. This allows updating following a change to the configuration.
          Sets up run_info in addition to whatever the superclass method does.
        To update from configuration simply do self.update_config(config).
        :param config: Configuration to be used.
        :return: nada


        Create a model, update list of created models and index of models.
        :param   params: dictionary of parameters to create the model.
         The following parameters are special and handled differently:
           * reference -- the reference directory. If not there (or None) then self.refDir is used.
           * model_name -- the model type to be created. If not in params then then self.model_name is used.
           These support more complex algorithms where multiple models need to be ran.
        These will be augmented by fixedParams
        If you need functionality beyond this you may want to inherit from SubmitStudy and
          override create_model to meet your needs
        :param dump: If True dump  self (using self.dump_config method)
        :return: Model created (or model that already exists). Returns None if would make more than max_model_sims


        Update iteration information.
        :param models: models to add to iteration info.
        :return: current value of iteration count


        :return: list of lists of  models. Outer list is order by iteration. Inner list is models on each iteration.
            For example result[0] is list of all models from iteration 0.


        Dump the configuration to config_path.
        Unless dump_models is True  models are not dumped. This done to make code run faster as model.set_status(XX) saves the model.
        :param dump_models: If True dump all models
        :return: Nothing


        Load a SubmitStudy (or anything that inherits from it) from a file.
        The object will have its config_path replaced by config_path passed in.
        :param config_path: path to configuration to load
        :param Study: If True return a Study object. These are read-only (unless you modify by hand the attributes)
        :return: object


        Instantiate all created models. And update_iter so we can see what was done.
        :return: True if all were instantiated. False otherwise


        return a list of  models that need instantiation.
        :return:list of models that need instantiation


        return a list of  models that need submission.
        :return:list of models that need submission


:return: a list of models that are marked to continue


:return: list of models that have failed


:return: List of models that are running


        Convert StudyConfig instance to dict. engine will be saved with the computer name
       from_dict will replace these.
        :return: a dict. Keys are attributes.


        Convert a dct back to a SubmitStudy. Does the following:
           decodes config -- needs special handling. FIXME: re-engineer StudyConfig so it needs less special handling....
           Creates the object
           Copies over attributes from dct to any existing attributes
           Sets up submission engine using its name
           Loads up models from paths that are saved.
        :param dct: dict containing attributes to be converted
        :return: a SubmitStudy object


        Clean up SubmitStudy configuration by deleting all models and removing self.config_path.
        The Internal structure will be updated so gen_name goes back to start and will return xxxx0...0


        Copy
        :param direct: directory where study is to be copied. Will be created if it does not exist
        :param extra_paths: extra paths to be copied. Should be provided relative to rootDir
        :param extra_model_paths: extra_paths for each model to be copied. Passed into model.copy()
        :return: Nada


        Archive SubmitStudy and all its model configurations to archive.
        :param archive: archive to be written into.
        :param extra_paths -- a list of extra paths to be archived. For example, final_json and monitor paths.
          Should be specified relative to rootDir.
        :return Nada!


        Delete a model and remove it from the indices
        :param model: model to delete
        :return:


        generate the next name .  Will be self.config.baseRunID() + maxDigit chars. Chars are 0-9,a-z
        and will increment every time called. First time it is called then internal counter will be reset
          to zero. Counter is incremented before name is generated.
        :param reset: Reset internal counter to zero so starting sequence again.
        For example IA0Az
         :return: name


        Submit models, the post-processing and the next iteration in the algorithm to job control system.
        :param fake_fn:Function to fake model runs -- will skip most stages including post-processing.
          fake and anything to be continued will generate an error.  No pp or next submission will be done if provided,
        :return: number of models submitted

        Does the following:
            1) Submits the models & post processing jobs
            2) If any post-processing jobs were submitted then submits  self.next_iter_cmd
               so once the  post-processing jobs has completed the next bit of the algorithm gets ran.
            3) When all the post-processing jobs are done the resubmission will be ran.

        This algorithm is not particularly robust to failure -- if anything fails the various jobs will be sitting around
        Releasing them will be quite tricky! You can always kill everything, remove any continuing models and start again.
        TODO: make this a bit more robust.
        The models and study will contain info on jobs so you might be able to fix/kill by hand.


        Set status of running or submitted models to failed using model.guess_failed()
        :return: List of models that were guessed to have failed. Their status will be FAILED.


        Convert to a study.
        Study instances only have read access to info. Useful if you don't want to accidentally modify state.
          config_path will be set to None to further reduce risk.
        :return: Study


    :param scales: Scalings to apply to data
    :param obs: Observations to be scales
    :param simObs: Simulated Observations to be scaled
    :*param covariances: Covariances to be scaled
    :return:  returns scaled obs, simObs and covariances


    Applies desired perturbations (steps) to the initial set of parameter
    values to return the parameter sets required for the GaussNewton phase
    of an iteration.

    The perturbations are towards the centre of the valid range for each
    parameter

    Inputs

         baseVals: array of parameters for the first of the GN runs (unperturbed)

         parLimits: max,min as read from JSON into 2-D array,
                    and passed through to here unaltered

         steps: array of stepsizes for each parameter.

         nrandom: perturb nrandom parameters rather than the full set.
         deterministic: optional argument with default value True -- make random choice of parameters deterministic.
            deterministic will be added to the RNG seed. So to modify what you get change the value of deterministic.
            It is a bit of a hack though...

         trace: Optional argument with default value False.
                Boolean -- True to get output, False no output

    Note inputs are all arrays, with data in order of the parameter list.

    Returns
          y: array defining the next set of parameter values
             with dimensions (nparameters+1, nparameters) with each row corresponding to a
             single simulation.


Regularize hessian matrix