Alien-libhisto

 view release on metacpan or  search on metacpan

bundled/include/histo/fit.h  view on Meta::CPAN

     *   params[2] = b  (scale / diversity, > 0)
     */
    HISTO_FIT_MODEL_LAPLACE = 10,

    /**
     * @brief Custom user-defined callback function.
     */
    HISTO_FIT_MODEL_CUSTOM = 11
} histo_fit_model_t;

/**
 * @brief Objective loss function / statistic to minimize.
 */
typedef enum histo_fit_loss {
    /**
     * @brief Pearson/Neyman Chi-Square weighted by bin variances.
     * Chi2 = sum_i (y_i - f(x_i))^2 / sigma_i^2
     * Variance sigma_i^2 is taken from sum_w2 if tracked, else max(y_i, 1.0).
     */
    HISTO_FIT_LOSS_CHI2 = 0,

    /**
     * @brief Binned Poisson Maximum Likelihood Estimation (Cash / Baker-Cousins deviance).
     * -2 ln L = 2 * sum_i [ f(x_i) - y_i + y_i * ln(y_i / f(x_i)) ]
     * Highly recommended for low-count, Poisson, or sparse histograms.
     */
    HISTO_FIT_LOSS_POISSON_MLE = 1,

    /**
     * @brief Unweighted Least Squares (assumes uniform unit variance).
     * SS = sum_i (y_i - f(x_i))^2
     */
    HISTO_FIT_LOSS_UNWEIGHTED_LS = 2
} histo_fit_loss_t;

/**
 * @brief Fitting algorithm strategy.
 */
typedef enum histo_fit_algo {
    /** @brief Automatically choose best algorithm (Linear LS for polynomials with Chi2/LS, LM otherwise) */
    HISTO_FIT_ALGO_AUTO = 0,

    /** @brief Levenberg-Marquardt non-linear least squares with adaptive damping */
    HISTO_FIT_ALGO_LEVENBERG_MARQUARDT = 1,

    /** @brief Direct Linear Least Squares via Normal Equations / QR factorization */
    HISTO_FIT_ALGO_LINEAR_LS = 2
} histo_fit_algo_t;

/**
 * @brief Fitting convergence and status return codes.
 */
typedef enum histo_fit_status {
    HISTO_FIT_CONVERGED_FTOL     =  0, /**< Converged: relative reduction in sum of squares <= ftol */
    HISTO_FIT_CONVERGED_XTOL     =  1, /**< Converged: relative step size in parameters <= xtol */
    HISTO_FIT_CONVERGED_GTOL     =  2, /**< Converged: orthogonal gradient norm <= gtol */
    HISTO_FIT_CONVERGED_EXACT    =  3, /**< Converged: direct exact linear solution obtained */
    HISTO_FIT_MAX_ITERATIONS     = -1, /**< Exceeded maximum allowed iterations without convergence */
    HISTO_FIT_ERR_INVALID_ARG    = -2, /**< Invalid parameter, NULL pointer, or illegal range */
    HISTO_FIT_ERR_SINGULAR       = -3, /**< Singular or rank-deficient Hessian/Jacobian matrix */
    HISTO_FIT_ERR_DIVERGENCE     = -4, /**< Objective function diverged or encountered NaN/Inf */
    HISTO_FIT_ERR_NO_DATA        = -5, /**< Insufficient non-empty bins in fitting range */
    HISTO_FIT_ERR_NOMEM          = -6  /**< Memory allocation failed */
} histo_fit_status_t;

/**
 * @brief Function pointer signature for custom parametric models.
 *
 * @param x Coordinate value (bin center).
 * @param params Array of model parameters.
 * @param userdata User context pointer.
 * @return Evaluated model value f(x; params).
 */
typedef double (*histo_fit_fn)(double x, const double *params, void *userdata);

/**
 * @brief Optional analytical gradient callback for custom parametric models.
 *
 * @param x Coordinate value (bin center).
 * @param params Array of model parameters.
 * @param grad Output array of size num_params to store partial derivatives [df/dp_0, df/dp_1, ...].
 * @param userdata User context pointer.
 */
typedef void (*histo_fit_grad_fn)(double x, const double *params, double *grad, void *userdata);

/**
 * @brief Configuration options and constraints for curve fitting.
 */
typedef struct histo_fit_options {
    uint32_t           max_iterations; /**< Maximum number of LM iterations (default: 500) */
    double             ftol;           /**< Relative reduction tolerance in loss (default: 1e-8) */
    double             xtol;           /**< Relative parameter step tolerance (default: 1e-8) */
    double             gtol;           /**< Orthogonal gradient tolerance (default: 1e-8) */
    double             initial_lambda; /**< Initial Marquardt damping parameter (default: 1e-3) */
    histo_fit_loss_t   loss_type;      /**< Loss statistic to minimize (default: HISTO_FIT_LOSS_CHI2) */
    histo_fit_algo_t   algo;           /**< Algorithm choice (default: HISTO_FIT_ALGO_AUTO) */
    uint32_t           poly_degree;    /**< Degree for polynomial models (0 to 10, default: 1) */
    double             range_min;      /**< Lower bound of fit range (default: 0.0) */
    double             range_max;      /**< Upper bound of fit range (default: 0.0, if min >= max: full range) */
    const double      *lower_bounds;   /**< Optional array of lower box constraints (or NULL) */
    const double      *upper_bounds;   /**< Optional array of upper box constraints (or NULL) */
    const bool        *fixed_params;   /**< Optional array of flags indicating frozen parameters (or NULL) */
    histo_fit_grad_fn  grad_fn;        /**< Optional analytical gradient callback (or NULL for finite differences) */
    void              *userdata;       /**< Optional context pointer passed to callbacks */
} histo_fit_options_t;

/**
 * @brief Comprehensive curve fitting results structure.
 */
typedef struct histo_fit_result {
    size_t             num_params;     /**< Number of model parameters */
    double            *params;         /**< Array of optimal fitted parameters */
    double            *param_errors;   /**< Array of estimated parameter standard errors (sqrt(Cov_ii)) */
    double            *cov_matrix;     /**< Covariance matrix (num_params x num_params, row-major) */
    double            *cor_matrix;     /**< Correlation matrix (num_params x num_params, row-major) */
    double             chi2;           /**< Final Chi-Square (or Poisson deviance) */
    int                ndf;            /**< Number of degrees of freedom (N_bins - N_free_params) */
    double             reduced_chi2;   /**< Reduced Chi-Square (chi2 / ndf) */
    double             p_value;        /**< Goodness-of-fit p-value: P(Chi2 >= chi2_obs | ndf) */
    double             log_likelihood; /**< Maximized log-likelihood ln(L) */
    double             aic;            /**< Akaike Information Criterion (2k - 2 ln L) */



( run in 1.209 second using v1.01-cache-2.11-cpan-60884a8df76 )