"""A minimal, editable SciPy ODR example from curve.fit.

Run with Python, NumPy, SciPy and Matplotlib installed. The sample runs as-is.
To use your data, save four whitespace-separated columns: x, dx, y, dy, and
uncomment the loadtxt line below. Edit model() and the starting guesses.
All uncertainties must be positive. This example uses both x and y errors;
it is not a copy of curve.fit's validation, model library or reporting engine.
Parameter errors below use Nominal, curve.fit's default for every model.
Absolute instead uses sqrt(diag(result.cov_beta)). This changes only
uncertainties, not the ODR solution. See https://curve.fit/help#parameter-uncertainties.
For Weighted Mean, use y and dy with w=1/dy**2: sum(w*y)/sum(w), with supplied-scale
standard uncertainty sqrt(1/sum(w)); x and dx do not enter that calculation.

Adapted from University of Toronto's odr_fit_to_data.py (MIT License below).
Copyright (c) 2011 University of Toronto; Michael Luzi and David Bailey.
"""

import numpy as np
from scipy import odr
from matplotlib import pyplot as plt


def model(parameters, x):
    """Change this equation and supply one starting guess per parameter."""
    slope, intercept = parameters
    return slope * x + intercept


# Rows are x, dx (1 sigma), y, dy (1 sigma).
data = np.array(
    [
        [0.0, 0.05, 1.1, 0.2],
        [1.0, 0.05, 2.9, 0.2],
        [2.0, 0.05, 5.2, 0.2],
        [3.0, 0.05, 6.8, 0.2],
        [4.0, 0.05, 9.1, 0.2],
    ]
)
# data = np.loadtxt("data.txt", comments="#")
starting_guesses = [2.0, 1.0]


def fit(data, guesses):
    """Fit this example with independent x and y measurement uncertainties."""
    rows = np.asarray(data, dtype=float)
    if rows.ndim != 2 or rows.shape[1] != 4 or len(rows) < len(guesses):
        raise ValueError("Use x, dx, y, dy rows, at least one per parameter.")
    if not np.all(np.isfinite(rows)) or np.any(rows[:, [1, 3]] <= 0):
        raise ValueError("Use finite data and positive x and y uncertainties.")
    x, dx, y, dy = rows.T
    solver = odr.ODR(
        odr.RealData(x, y, sx=dx, sy=dy), odr.Model(model), beta0=guesses, maxit=10_000, sstol=1e-14
    )
    solver.set_job(fit_type=0, deriv=1)
    return solver.run()


def main():
    result = fit(data, starting_guesses)
    print("Stop reason:", "; ".join(result.stopreason))
    # sd_beta includes residual-variance scaling; cov_beta alone does not.
    for index, (value, uncertainty) in enumerate(zip(result.beta, result.sd_beta)):
        print(f"p[{index}] = {value:.10g} +/- {uncertainty:.10g} (1 sigma)")
    x, dx, y, dy = data.T
    grid = np.linspace(x.min(), x.max(), 200)
    plt.errorbar(x, y, xerr=dx, yerr=dy, fmt="o", label="Data")
    plt.plot(grid, model(result.beta, grid), label="Fit")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.tight_layout()
    plt.show()


if __name__ == "__main__":
    main()


"""
Full text of MIT License:

    Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
