The core of PyImfit is the Imfit class, which acts as a wrapper around the underlying C++ ModelObject instance. It holds a ModelDescription instance which describes the model to be fit to the data (or just used to generate a model image, if no actual fitting is to be done). In the (usual) case of fitting the model to an image, it also holds the data image, optional PSF images, and parameters that describe the image (A/D gain, etc.).

It also has methods for running a fit and for inspecting the results.

class `pyimfit.fitting.` `FitResult`

  Represents the result of fitting an image.

  `params`

    The best-fit vector of parameter values.

    Type

      ndarray

  `success`

    Whether or not the optimizer exited successfully.

    Type

      bool

  `status`

    Termination status of the optimizer. Its value depends on the underlying solver. Refer to message for details.

    Type

      int

  `message`

    Description of the cause of the termination.

    Type

      str

  `nfev`

    Number of evaluations of the objective function.

    Type

      int

  `nit`

    Number of iterations performed by the optimizer.

    Type

      int

  `OTHER IDEAS`

    AIC,BIC fitStatistic, reduced fitStatistic

  Notes

  There may be additional attributes not listed above depending of the specific solver. Since this class is essentially a subclass of dict with attribute accessors, one can see which attributes are available using the keys() method.

class `pyimfit.fitting.` `Imfit`(model_descr: pyimfit.descriptions.ModelDescription, psf=None, psfNormalization=True, quiet=True, nproc=0, chunk_size=10, subsampling=True, zeroPoint=None)

  The main class for fitting models to images using Imfit. Can also be used to create images based on models.

  Due to some library limitations, this object can only fit the model specified in the constructor. If you want to fit several models, you need to create one instance of `Imfit` for each model. On the other hand, one instance can be used to fit the same model to any number of images, or to fit and then create the model image.

  `AIC`
  `BIC`
  `fitConverged`
  `fitError`
  `fitStatistic`
  `fitTerminated`
  `nIter`
  `nPegged`
  `nValidPixles`
  `numberedParameterNames`
  `parameterErrors`
  `reducedFitStatistic`

  See also

  `parse_config_file`

  property `AIC`

    bias-corrected Akaike Information Criterion for the fit.

    Type

      float

  property `BIC`

    Bayesian Information Criterion for the fit.

    Type

      float

  `computeFitStatistic`(newParameters)

    Returns the fit-statistic value for the specified parameter vector. (Which fit statistic will calculated is set by the loadData() or fit() methods.)

    Parameters

      newParameters (ndarray of float) –

    Returns

      fitStatistic

    Return type

      float

  `doFit`(solver='LM', verbose=None, getSummary=True)

    Fit the model to previously supplied data image.

    Parameters

      - solver (string, optional) –

        One of the following solvers (optimization algorithms) to be used for the fit:

          - `'LM'` : Levenberg-Marquardt.

          - `'NM'` : Nelder-Mead Simplex.

          - `'DE'` : Differential Evolution.

      - verbose (int or None, optional) – set this to an integer to specify a feedback level for the fit (this overrides the Imfit object’s internal verbosity setting)

      - getSummary (bool, optional) – if True, a summary of the fit is returned (as a string)

    Returns

      result

    Return type

      FitResult object

    Examples

    TODO: Examples of doFit().

  `fit`(image, error=None, mask=None, solver='LM', verbose=None, getSummary=True, **kwargs)

    Supply data image (and optionally mask and/or error images) and image info, then fit the model to the data.

    Parameters

      - image (2-D numpy array (ndarray or MaskedArray)) – Image to be fitted. Can be a masked array.

      - error (2-D numpy array, optional) – error/weight image, same shape as `image`. If not set, errors are generated from `image`. See also the keyword args `use_poisson_mlr`, `use_cash_statistics`, and `use_model_for_errors`.

      - mask (2-D numpy array, optional) – Array containing the masked pixels; must have the same shape as `image`. Pixels set to `True` are bad by default (see the kwarg `mask_format` for other options). If not set and `image` is a masked array, then its mask is used. If both masks are present, the final mask is composed by masking any pixel that is masked in either of the input masks.

      - solver (string, optional) –

        One of the following solvers (optimization algorithms) to be used for the fit:

          - `'LM'` : Levenberg-Marquardt.

          - `'NM'` : Nelder-Mead Simplex.

          - `'DE'` : Differential Evolution.

      - verbose (int or None, optional) – set this to an integer to specify a feedback level for the fit (this overrides the Imfit object’s internal verbosity setting)

      - getSummary (bool, optional) – if True, a summary of the fit is returned (as a string)

      - loadData() for list of allowed extra keywords. (See) –

    Returns

      result

    Return type

      FitResult object

  property `fitConverged`

    indicates whether fit converged.

    Type

      bool

  property `fitStatistic`

    the \(\chi^2\), Poisson MLR, or Cash statistic of the fit.

    Type

      float

  property `fitTerminated`

    indicates whether fit terminated for any reason.

    Type

      bool

  `getFitResult`()

    Returns a summary of the fitting process.

    Returns

      result

    Return type

      FitResult object

  `getModelDescription`()
    Returns

      model – A copy of the currently fitted model, or a copy of the template model if no fitting has taken place yet.

    Return type

      `ModelDescription`

  `getModelFluxes`(newParameters=None)

    Computes and returns total and individual-function fluxes for the current model and current parameter values.

    Parameters

      newParameters (1-D numpy array of float, optional) – vector of parameter values to use in computing model (default is to use current parameter values, e.g., from most rencent fit, instead)

    Returns

      (totalFlux, individualFluxes) – totalFlux = total flux (or magnitude) of model individualFluxes = numpy ndarray of fluxes/magnitudes for each image-function in the model

    Return type

      tuple of (float, ndarray of float)

  `getModelImage`(shape=None, newParameters=None, includeMask=False)

    Computes and returns the image described by the currently fitted model. If not fitted, use the template model.

    Parameters

      - newParameters (1-D numpy array of float, optional) – vector of parameter values to use in computing model (default is to use current parameter values, e.g., from fit)

      - shape (tuple, optional) – Shape of the image in (Y, X) = (nRows, nColumns) format.

      - includeMask (bool, optional) – Specifies whether output should be numpy masked array, if there is a mask image associated with the data image.

    Returns

      image – Image computed from the current model. If a mask is associated with the original data image, then the returned image is a numpy masked array

    Return type

      2-D numpy array

  `getModelMagnitudes`(newParameters=None, zeroPoint=None)

    Computes and returns total and individual-function magnitudes for the current model and current parameter values.

    Parameters

      - newParameters (1-D numpy array of float, optional) – vector of parameter values to use in computing model (default is to use current parameter values, e.g., from most rencent fit, instead)

      - zeroPoint (float, optional) –

        If present, returned values are magnitudes, computed as

          zeroPoint - 2.5*log10(flux)

        (default is to use value of object’s zeroPoint property)

    Returns

      (totalMag, individualMags) – totalFlux = total flux (or magnitude) of model individualFluxes = numpy ndarray of fluxes/magnitudes for each image-function in the model

    Return type

      tuple of (float, ndarray of float)

  `getParameterErrors`()

    Returns current best-fit model parameter uncertainties (from L-M minimization).

    Returns

      errors – A 1D array containing the Levenberg-Marquardt parameter uncertainties.

    Return type

      ndarray of float

  `getParameterLimits`()

    Returns a list containing lower and upper limits for all parameters in the model.

    Returns

      parameterLimits – [(lower_limit, upper_limit)_1, (lower_limit, upper_limit)_2, …]

    Return type

      list of 2-element tuples of float

  `getRawParameters`()

    Returns current model parameter values.

    Returns

      raw_params – A 1D array containing all the model parameter values.

    Return type

      ndarray of float

  `loadData`(image, error=None, mask=None, **kwargs)

    Supply the underlying ModelObject instance with data image and error model, optionally including error and/or mask images.

    Parameters

      - image (2-D numpy array (ndarray or MaskedArray)) – Image to be fitted. Can be a masked array.

      - error (2-D numpy array, optional) – error/weight image, same shape as `image`. If not set, errors are generated from `image`. See also the keyword args `use_poisson_mlr`, `use_cash_statistics`, and `use_model_for_errors`.

      - mask (2-D numpy array, optional) – Array containing the masked pixels; must have the same shape as `image`. Pixels set to `True` are bad by default (see the kwarg `mask_format` for other options). If not set and `image` is a masked array, then its mask is used. If both masks are present, the final mask is composed by masking any pixel that is masked in either of the input masks.

    Keyword Arguments

      - n_combined (integer) – Number of images which were averaged to make final image (if counts are average or median). Default: 1

      - exp_time (float) – Exposure time in seconds (only if image is in ADU/sec). Default: 1.0

      - gain (float) – Image gain (e-/ADU). Default: 1.0

      - read_noise (float) – Image read noise (Gaussian sigma, in e-). Default: 0.0

      - original_sky (float) – Original sky background (ADUs) which has already been subtracted from image. Default: 0.0

      - error_type (string) –

        Values in `error` should be interpreted as:

          - `'sigma'` (default).

          - `'weight'`.

          - `'variance'`.

      - mask_format (string) –

        Values in `mask` should be interpreted as:

          - `'zero_is_good'` (default).

          - `'zero_is_bad'`.

      - psf_oversampling_list (list of PsfOversampling) – List of PsfOversampling objects, describing oversampling regions, PSFs, and oversampling scales.

      - use_poisson_mlr (boolean) – Use Poisson MLR (maximum-likelihood-ratio) statistic instead of chi^2. Takes precedence over `error`, `use_model_for_errors`, and ``use_cash_statistics`. Default: `False`

      - use_cash_statistics (boolean) – Use Cash statistic instead of chi^2 or Poisson MLR. Takes precedence over `error` and `use_model_for_errors`. Default: `False`

      - use_model_for_errors (boolean) – Use model values (instead of data) to estimate errors for chi^2 computation. Takes precedence over `error`. Default: `False`

  property `nIter`

    number of solver iterations during fit.

    Type

      int

  property `nPegged`

    number of parameters pegged against limits at end of fit.

    Type

      int

  property `nValidPixels`

    number of non-masked pixels in data image.

    Type

      int

  property `numberedParameterNames`

    List of parameter names for the current model, annotated by function number. E.g., [“X0_1”, “Y0_1”, “PA_1”, “ell_1”, “I_0_1”, “h_1”, …]

    Type

      list of str

  property `parameterErrors`

    estimated parameter errors from fit (L-M solver only)

    Type

      ndarray of float or None

  property `reducedFitStatistic`

    the “reduced” \(\chi^2\) or Poisson MLR of the fit.

    Type

      float

  `runBootstrap`(nIterations, ftol=1e-08, verboseFlag=False, seed=0, getColumnNames=False)

    Do bootstrap resampling for a model.

    Parameters

      - nIterations (int) – How many bootstrap samples to generate and fit

      - ftol (float, optional) – fractional tolerance in fit statistic for determining fit convergence

      - verboseFlag (bool, optional) – if True, a progress bar is printed during the boostrap iterations

      - seed (int, optional) – random number seed (default is to use system clock)

      - getColumnNames (bool, optional) – if True, then column (parameter) names are returned as well

    Returns

      - bootstrapOutput (2-D ndarray of float)

      - OR

      - (columnNames, bootstrapOutput) (tuple of (list of str, 2-D ndarray of float))

  `saveCurrentModelToFile`(filename: str, includeImageOptions=False)

    Saves the current model and parameter values to a text file in Imfit-configuration-file format.

    Parameters

      - filename (str) – Name for the output file

      - includeImageOptions (bool, optional) – if True, then image-description options (“GAIN”, etc.) are also written to the output file

  property `zeroPoint`

    photometric zero point (used by getModelMagnitudes method).

    Type

      float

`pyimfit.fitting.` `MakePsfOversampler`(psfImage, oversampleScale, regionSpec, psfNormalization=True)

  Helper function to generate PsfOversampling objects (corrects input psfImage, sets up region string, etc.).

  Parameters

    - psfImage (2-D numpy array) – the oversampled PSF image

    - oversampleScale (int) –

      oversampling scale of psfImage relative to data image: number of PSF-image

        pixels per data-image pixel in one dimension (must be >= 1)

    - regionSpec (sequence of int) – specifies inclusive boundaries of image region to be oversampled [x1,x2,y1,y2]

    - psfNormalization (bool, optional) – Normalize the PSF image before using. Default: `True`.

  Returns

    oversampleInfo

  Return type

    instance of PsfOversampling class