/** @file  pmSourceFitModel.c
 *
 *  fit single source models to image pixels
 *
 *  @author EAM, IfA
 *  @author GLG, MHPCC
 *
 *  @version $Revision: 1.27 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2007-09-28 00:38:56 $
 *
 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <pslib.h>
#include "pmHDU.h"
#include "pmFPA.h"
#include "pmPeaks.h"
#include "pmMoments.h"
#include "pmGrowthCurve.h"
#include "pmResiduals.h"
#include "pmTrend2D.h"
#include "pmPSF.h"
#include "pmModel.h"
#include "pmSource.h"
#include "pmModelClass.h"
#include "pmSourceFitModel.h"

// save as static values so they may be set externally
static psF32 PM_SOURCE_FIT_MODEL_NUM_ITERATIONS = 15;
static psF32 PM_SOURCE_FIT_MODEL_TOLERANCE = 0.1;
static psF32 PM_SOURCE_FIT_MODEL_WEIGHT = 1.0;
static bool  PM_SOURCE_FIT_MODEL_PIX_WEIGHTS = true;

bool pmSourceFitModelInit (float nIter, float tol, float weight, bool poissonErrors)
{

    PM_SOURCE_FIT_MODEL_NUM_ITERATIONS = nIter;
    PM_SOURCE_FIT_MODEL_TOLERANCE = tol;
    PM_SOURCE_FIT_MODEL_WEIGHT = weight;
    PM_SOURCE_FIT_MODEL_PIX_WEIGHTS = poissonErrors;

    return true;
}

bool pmSourceFitModel (pmSource *source,
                       pmModel *model,
                       pmSourceFitMode mode,
                       psMaskType maskVal)
{
    psTrace("psModules.objects", 5, "---- %s begin ----\n", __func__);
    PS_ASSERT_PTR_NON_NULL(source, false);
    PS_ASSERT_PTR_NON_NULL(source->pixels, false);
    PS_ASSERT_PTR_NON_NULL(source->maskObj, false);
    PS_ASSERT_PTR_NON_NULL(source->weight, false);

    psBool fitStatus = true;
    psBool onPic     = true;
    psBool rc        = true;

    // maximum number of valid pixels
    psS32 nPix = source->pixels->numRows * source->pixels->numCols;

    // arrays to hold the data to be fitted
    psArray *x = psArrayAllocEmpty(nPix);
    psVector *y = psVectorAllocEmpty(nPix, PS_TYPE_F32);
    psVector *yErr = psVectorAllocEmpty(nPix, PS_TYPE_F32);

    // fill in the coordinate and value entries
    nPix = 0;
    for (psS32 i = 0; i < source->pixels->numRows; i++) {
        for (psS32 j = 0; j < source->pixels->numCols; j++) {
            // skip masked points
            if (source->maskObj->data.U8[i][j] & maskVal) {
                continue;
            }
            // skip zero-weight points
            if (source->weight->data.F32[i][j] == 0) {
                continue;
            }
            // skip nan values in image
            if (!isfinite(source->pixels->data.F32[i][j])) {
                continue;
            }

            psVector *coord = psVectorAlloc(2, PS_TYPE_F32);

            // Convert i/j to image space:
            coord->data.F32[0] = (psF32) (j + source->pixels->col0);
            coord->data.F32[1] = (psF32) (i + source->pixels->row0);
            x->data[nPix] = (psPtr *) coord;
            y->data.F32[nPix] = source->pixels->data.F32[i][j];

            // psMinimizeLMChi2 takes wt = 1/dY^2.  suggestion from RHL is to use the local sky
            // as weight to avoid the bias from systematic errors here we would just use the
            // source sky variance
            if (PM_SOURCE_FIT_MODEL_PIX_WEIGHTS) {
                yErr->data.F32[nPix] = 1.0 / source->weight->data.F32[i][j];
            } else {
                yErr->data.F32[nPix] = 1.0 / PM_SOURCE_FIT_MODEL_WEIGHT;
            }
            nPix++;
        }
    }
    x->n = nPix;
    y->n = nPix;
    yErr->n = nPix;

    psVector *params = model->params;
    psVector *dparams = model->dparams;

    // create the minimization constraints
    psMinConstraint *constraint = psMinConstraintAlloc();
    constraint->paramMask = psVectorAlloc (params->n, PS_TYPE_U8);
    constraint->checkLimits = model->modelLimits;

    // set parameter mask based on fitting mode
    int nParams = 0;
    switch (mode) {
    case PM_SOURCE_FIT_NORM:
        // NORM-only model fits only source normalization (Io)
        nParams = 1;
        psVectorInit (constraint->paramMask, 1);
        constraint->paramMask->data.U8[PM_PAR_I0] = 0;
        break;
    case PM_SOURCE_FIT_PSF:
        // PSF model only fits x,y,Io
        nParams = 3;
        psVectorInit (constraint->paramMask, 1);
        constraint->paramMask->data.U8[PM_PAR_I0] = 0;
        constraint->paramMask->data.U8[PM_PAR_XPOS] = 0;
        constraint->paramMask->data.U8[PM_PAR_YPOS] = 0;
        break;
    case PM_SOURCE_FIT_EXT:
        // EXT model fits all params (except sky)
        nParams = params->n - 1;
        psVectorInit (constraint->paramMask, 0);
        constraint->paramMask->data.U8[PM_PAR_SKY] = 1;
        break;
    default:
        psAbort("invalid fitting mode");
    }
    // force the floating parameters to fall within the contraint ranges
    for (int i = 0; i < params->n; i++) {
        model->modelLimits (PS_MINIMIZE_PARAM_MIN, i, params->data.F32, NULL);
        model->modelLimits (PS_MINIMIZE_PARAM_MAX, i, params->data.F32, NULL);
    }

    if (nPix <  nParams + 1) {
        psTrace ("psModules.objects", 4, "insufficient valid pixels\n");
        model->flags |= PM_MODEL_STATUS_BADARGS;
        psFree (x);
        psFree (y);
        psFree (yErr);
        psFree (constraint);
        return(false);
    }

    psMinimization *myMin = psMinimizationAlloc (PM_SOURCE_FIT_MODEL_NUM_ITERATIONS, PM_SOURCE_FIT_MODEL_TOLERANCE);

    psImage *covar = psImageAlloc (params->n, params->n, PS_TYPE_F32);

    fitStatus = psMinimizeLMChi2(myMin, covar, params, constraint, x, y, yErr, model->modelFunc);
    for (int i = 0; i < dparams->n; i++) {
        if (psTraceGetLevel("psModules.objects") >= 4) {
            fprintf (stderr, "%f ", params->data.F32[i]);
        }
        if ((constraint->paramMask != NULL) && constraint->paramMask->data.U8[i])
            continue;
        dparams->data.F32[i] = sqrt(covar->data.F32[i][i]);
    }
    psTrace ("psModules.objects", 4, "niter: %d, chisq: %f", myMin->iter, myMin->value);

    // save the resulting chisq, nDOF, nIter
    model->chisq = myMin->value;
    model->nIter = myMin->iter;
    model->nDOF  = y->n - nParams;
    model->flags |= PM_MODEL_STATUS_FITTED;
    if (!fitStatus) model->flags |= PM_MODEL_STATUS_NONCONVERGE;

    // get the Gauss-Newton distance for fixed model parameters
    // hold the fitted parameters fixed; mask sky which is not fitted at all
    if (constraint->paramMask != NULL) {
        psVector *delta = psVectorAlloc (params->n, PS_TYPE_F32);
        psVector *altmask = psVectorAlloc (params->n, PS_TYPE_U8);
        altmask->data.U8[0] = 1;
        for (int i = 1; i < dparams->n; i++) {
            altmask->data.U8[i] = (constraint->paramMask->data.U8[i]) ? 0 : 1;
        }
        psMinimizeGaussNewtonDelta(delta, params, altmask, x, y, yErr, model->modelFunc);

        for (int i = 0; i < dparams->n; i++) {
            if (!constraint->paramMask->data.U8[i])
                continue;
            // note that delta is the value *subtracted* from the parameter
            // to get the new guess.  for dparams to represent the direction
            // of motion, we need to take -delta
            dparams->data.F32[i] = -delta->data.F32[i];
        }
        psFree (delta);
        psFree (altmask);
    }

    // models can go insane: reject these
    onPic &= (params->data.F32[PM_PAR_XPOS] >= source->pixels->col0);
    onPic &= (params->data.F32[PM_PAR_XPOS] <  source->pixels->col0 + source->pixels->numCols);
    onPic &= (params->data.F32[PM_PAR_YPOS] >= source->pixels->row0);
    onPic &= (params->data.F32[PM_PAR_YPOS] <  source->pixels->row0 + source->pixels->numRows);
    if (!onPic) {
        model->flags |= PM_MODEL_STATUS_OFFIMAGE;
    }

    source->mode |= PM_SOURCE_MODE_FITTED;

    psFree(x);
    psFree(y);
    psFree(yErr);
    psFree(myMin);
    psFree(covar);
    psFree(constraint);

    rc = (onPic && fitStatus);
    psTrace("psModules.objects", 5, "---- %s(%d) end ----\n", __func__, rc);
    return(rc);
}

