Skip to content

Commit

Permalink
fit range on levenberg-marquadt
Browse files Browse the repository at this point in the history
  • Loading branch information
settwi committed Nov 26, 2024
1 parent e8e136e commit d5d42f1
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions yaff/fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,18 +538,30 @@ def free_param_units(self) -> list[u.Unit]:
return list(p.unit for p in self.free_parameters)


def levenberg_minimize(fitter: BayesFitter, **scipy_kwargs) -> BayesFitter:
def levenberg_minimize(
fitter: BayesFitter,
restriction: np.ndarray[bool] = None,
**scipy_kwargs
) -> BayesFitter:
"""Given a Bayes fitter, minimize its parameters using the Levenberg-Marquadt
(weighted) least squares minimization like XSPEC does.
This minimization technique operates on **all** of the model and data
The `restriction` parameter is used to optionally exclude count bins
which shouldn't be considered when fitting.
---
Levenberg-Marquadt operates on **all** of the model and data
count bins. So, it tends to be more robust (and converge faster) than
algorithms which are based on a single summary "fit statistic."
Applying this minimizer is a good first step before doing MCMC
as it will (robustly) put the parameter vector near its global minimum.
"""

if restriction is None:
restriction = np.ones_like(fitter.data.counts, dtype=bool)

def residual_function(vector: ArrayLike):
fitter.emplace_free_parameters(vector)
if np.isneginf(fitter.eval_priors()):
Expand All @@ -566,6 +578,7 @@ def residual_function(vector: ArrayLike):
)

ret = (mod - compare) / total_error
ret[~restriction] = 0
# Any "zero-error" bins need to get deleted
return np.nan_to_num(ret, copy=False, nan=0, posinf=0, neginf=0)

Expand Down

0 comments on commit d5d42f1

Please sign in to comment.