likefit


Namelikefit JSON
Version 0.1.0 PyPI version JSON
download
home_page
SummaryFit data with least squares and other likelihood methods
upload_time2024-01-05 21:58:08
maintainer
docs_urlNone
author
requires_python>=3.10
licenseMIT License Copyright (c) 2024 Diego Ravignani Guerrero 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.
keywords fit likelihood scipy
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # LikeFit

LikeFit is an open-source library to fit data in science and engineering. 
It provides a simple yet complete interface to SciPy that performs linear and nolinear least squares and other likelihood fits. 

## Install

```sh
python -m pip install likefit
```

## Features
  * Linear and nonlinear least squares fits
  * Poisson likelihood to fit histograms
  * Binomial likelihood 
  * Calculation of estimators, errors, and correlations
  * Evaluation of goodness-of-fit with chi-squared test
  * Support for plotting error bands, confidence ellipses, and likelihood functions

## How to use

### Nonlinear least squares

Example of fitting data with a nonlinear least squares method

```py
import numpy as np

import likefit

xdata = np.array([0., 0.2, 0.4, 0.6, 0.8, 1., 1.2, 1.4, 1.6, 1.8, 2.])
ydata = np.array([0.92, 0.884, 0.626, 0.504, 0.481, 0.417, 0.288, 0.302, 0.177, 0.13, 0.158])
ysigma = np.array([0.1, 0.082, 0.067, 0.055, 0.045, 0.037, 0.03, 0.025, 0.02, 0.017, 0.014])


# Fit model must be vectorized in x
def fit_model(x, par):
    return par[0] * np.exp(par[1] * x)

# Create a least squares fitter and inititalize it with the data and the fit model
fitter = likefit.LeastSquares(xdata, ydata, ysigma, fit_model)

# Fit the data
seed = np.array([0, 0])
fitter.fit(seed)

print(f"Estimators: {fitter.get_estimators()}")
print(f"Errors: {fitter.get_errors()}")
print(f"Covariance matrix: {fitter.get_covariance_matrix()}")
print(f"Correlation matrix: {fitter.get_correlation_matrix()}")
print(f"Deviance: {fitter.get_deviance()}")
print(f"Degrees of freedom: {fitter.get_ndof()}")
print(f"Pvalue: {fitter.get_pvalue()}")
```

Plotting the fit and the error band

```py
# Plot
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_xlabel("x")
ax.set_ylabel("y")

# Plot data
ax.errorbar(fitter.x, fitter.y, fitter.ysigma, ls='none', marker='o', label="Data")

# Plot fit
xfit = np.linspace(start=xdata.min(), stop=xdata.max(), num=100)
yfit = fitter.get_yfit(xfit)
ax.plot(xfit, yfit, ls='--', label="Fit")

# Plot error band
yfit_error = fitter.get_yfit_error(xfit)
ax.fill_between(xfit, yfit - yfit_error, yfit + yfit_error, color='tab:orange', alpha=0.2)

plt.legend()
plt.tight_layout()
plt.show()
```

![](examples/least_squares/least_squares.png)


### Linear least squares

Support of linear least squares fits with a similar interface to the nonlinear case.

```py
import numpy as np

import likefit

xdata = np.array([1.02, 1.06, 1.1, 1.14, 1.18, 1.22, 1.26, 1.3, 1.34])
ydata = np.array([2.243, 2.217, 2.201, 2.175, 2.132, 2.116, 2.083, 2.016, 2.004])
ysigma = np.array([0.008, 0.008, 0.01, 0.009, 0.011, 0.016, 0.018, 0.021, 0.017])
npar = 2


# Model linear in the parameters 
def fit_model(x, par):
    return par[0] + par[1] * (x - 1.2)


fitter = likefit.LinearLeastSquares(xdata, ydata, ysigma, npar, fit_model)
fitter.fit()  # Seed not needed
```

### Poisson

The example below fits a normal distribution to a histogram

```py
import numpy as np
from scipy.stats import norm

import likefit

xdata = np.linspace(start=-2.9, stop=2.9, num=30)
nevents = np.array([0, 2, 5, 8, 7, 18, 15, 27, 34, 51, 55, 63, 67, 75, 90, 78, 73, 70, 62, 51, 33, 26, 30, 17, 15, 14, 5,
                  4, 1, 0])


# fit_model vectorized in x
def fit_model(x, par):
    return par[0] * norm.pdf(x, loc=par[1], scale=par[2])


fitter = likefit.Poisson(xdata, nevents, fit_model)
seed = np.array([1, 0, 1])
fitter.fit(seed)
```

### Binomial

Fit efficiency data with a sigmoid function

```py
import numpy as np

import likefit

xdata = np.arange(start=0.05, stop=1.05, step=0.05)
ntrials = np.full(xdata.shape, 30)
nsuccess = np.array([0, 0, 0, 3, 3, 2, 8, 5, 4, 11, 18, 15, 19, 20, 26, 24, 26, 29, 30, 30])


# fit_model is sigmoid function vectorized in x
def fit_model(x, par):
    return 1 / (1 + np.exp(-(x - par[0]) / par[1]))


fitter = likefit.Binomial(xdata, ntrials, nsuccess, fit_model)
seed = np.array([0.5, 1])
fitter.fit(seed)
```

## Contributing
If you'd like to contribute, please fork the repository and use a feature
branch. Pull requests are warmly welcome.

## Links
- Repository: https://github.com/ravignad/likefit/

## Licensing
The code in this project is licensed under MIT license.


            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "likefit",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": "",
    "keywords": "fit,likelihood,scipy",
    "author": "",
    "author_email": "Diego Ravignani <diego.ravignani@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/c1/49/8cbfea9848cc248871ee64f38e222781971c91dad4be11fc8951de08d54e/likefit-0.1.0.tar.gz",
    "platform": null,
    "description": "# LikeFit\n\nLikeFit is an open-source library to fit data in science and engineering. \nIt provides a simple yet complete interface to SciPy that performs linear and nolinear least squares and other likelihood fits. \n\n## Install\n\n```sh\npython -m pip install likefit\n```\n\n## Features\n  * Linear and nonlinear least squares fits\n  * Poisson likelihood to fit histograms\n  * Binomial likelihood \n  * Calculation of estimators, errors, and correlations\n  * Evaluation of goodness-of-fit with chi-squared test\n  * Support for plotting error bands, confidence ellipses, and likelihood functions\n\n## How to use\n\n### Nonlinear least squares\n\nExample of fitting data with a nonlinear least squares method\n\n```py\nimport numpy as np\n\nimport likefit\n\nxdata = np.array([0., 0.2, 0.4, 0.6, 0.8, 1., 1.2, 1.4, 1.6, 1.8, 2.])\nydata = np.array([0.92, 0.884, 0.626, 0.504, 0.481, 0.417, 0.288, 0.302, 0.177, 0.13, 0.158])\nysigma = np.array([0.1, 0.082, 0.067, 0.055, 0.045, 0.037, 0.03, 0.025, 0.02, 0.017, 0.014])\n\n\n# Fit model must be vectorized in x\ndef fit_model(x, par):\n    return par[0] * np.exp(par[1] * x)\n\n# Create a least squares fitter and inititalize it with the data and the fit model\nfitter = likefit.LeastSquares(xdata, ydata, ysigma, fit_model)\n\n# Fit the data\nseed = np.array([0, 0])\nfitter.fit(seed)\n\nprint(f\"Estimators: {fitter.get_estimators()}\")\nprint(f\"Errors: {fitter.get_errors()}\")\nprint(f\"Covariance matrix: {fitter.get_covariance_matrix()}\")\nprint(f\"Correlation matrix: {fitter.get_correlation_matrix()}\")\nprint(f\"Deviance: {fitter.get_deviance()}\")\nprint(f\"Degrees of freedom: {fitter.get_ndof()}\")\nprint(f\"Pvalue: {fitter.get_pvalue()}\")\n```\n\nPlotting the fit and the error band\n\n```py\n# Plot\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\n\n# Plot data\nax.errorbar(fitter.x, fitter.y, fitter.ysigma, ls='none', marker='o', label=\"Data\")\n\n# Plot fit\nxfit = np.linspace(start=xdata.min(), stop=xdata.max(), num=100)\nyfit = fitter.get_yfit(xfit)\nax.plot(xfit, yfit, ls='--', label=\"Fit\")\n\n# Plot error band\nyfit_error = fitter.get_yfit_error(xfit)\nax.fill_between(xfit, yfit - yfit_error, yfit + yfit_error, color='tab:orange', alpha=0.2)\n\nplt.legend()\nplt.tight_layout()\nplt.show()\n```\n\n![](examples/least_squares/least_squares.png)\n\n\n### Linear least squares\n\nSupport of linear least squares fits with a similar interface to the nonlinear case.\n\n```py\nimport numpy as np\n\nimport likefit\n\nxdata = np.array([1.02, 1.06, 1.1, 1.14, 1.18, 1.22, 1.26, 1.3, 1.34])\nydata = np.array([2.243, 2.217, 2.201, 2.175, 2.132, 2.116, 2.083, 2.016, 2.004])\nysigma = np.array([0.008, 0.008, 0.01, 0.009, 0.011, 0.016, 0.018, 0.021, 0.017])\nnpar = 2\n\n\n# Model linear in the parameters \ndef fit_model(x, par):\n    return par[0] + par[1] * (x - 1.2)\n\n\nfitter = likefit.LinearLeastSquares(xdata, ydata, ysigma, npar, fit_model)\nfitter.fit()  # Seed not needed\n```\n\n### Poisson\n\nThe example below fits a normal distribution to a histogram\n\n```py\nimport numpy as np\nfrom scipy.stats import norm\n\nimport likefit\n\nxdata = np.linspace(start=-2.9, stop=2.9, num=30)\nnevents = np.array([0, 2, 5, 8, 7, 18, 15, 27, 34, 51, 55, 63, 67, 75, 90, 78, 73, 70, 62, 51, 33, 26, 30, 17, 15, 14, 5,\n                  4, 1, 0])\n\n\n# fit_model vectorized in x\ndef fit_model(x, par):\n    return par[0] * norm.pdf(x, loc=par[1], scale=par[2])\n\n\nfitter = likefit.Poisson(xdata, nevents, fit_model)\nseed = np.array([1, 0, 1])\nfitter.fit(seed)\n```\n\n### Binomial\n\nFit efficiency data with a sigmoid function\n\n```py\nimport numpy as np\n\nimport likefit\n\nxdata = np.arange(start=0.05, stop=1.05, step=0.05)\nntrials = np.full(xdata.shape, 30)\nnsuccess = np.array([0, 0, 0, 3, 3, 2, 8, 5, 4, 11, 18, 15, 19, 20, 26, 24, 26, 29, 30, 30])\n\n\n# fit_model is sigmoid function vectorized in x\ndef fit_model(x, par):\n    return 1 / (1 + np.exp(-(x - par[0]) / par[1]))\n\n\nfitter = likefit.Binomial(xdata, ntrials, nsuccess, fit_model)\nseed = np.array([0.5, 1])\nfitter.fit(seed)\n```\n\n## Contributing\nIf you'd like to contribute, please fork the repository and use a feature\nbranch. Pull requests are warmly welcome.\n\n## Links\n- Repository: https://github.com/ravignad/likefit/\n\n## Licensing\nThe code in this project is licensed under MIT license.\n\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2024 Diego Ravignani Guerrero  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. ",
    "summary": "Fit data with least squares and other likelihood methods",
    "version": "0.1.0",
    "project_urls": {
        "Homepage": "https://github.com/ravignad/likefit"
    },
    "split_keywords": [
        "fit",
        "likelihood",
        "scipy"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "73b7ca0487af01c801f7c0dd66ef2fb89e906b489fb9b0dcf648092f2f601ba3",
                "md5": "d02d9d2100761de16120e02f7812edcb",
                "sha256": "99d0a95de22e705fc9dea91e3d70134ffd41067fffa3710474765fb572ae64b6"
            },
            "downloads": -1,
            "filename": "likefit-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d02d9d2100761de16120e02f7812edcb",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 7038,
            "upload_time": "2024-01-05T21:58:06",
            "upload_time_iso_8601": "2024-01-05T21:58:06.755173Z",
            "url": "https://files.pythonhosted.org/packages/73/b7/ca0487af01c801f7c0dd66ef2fb89e906b489fb9b0dcf648092f2f601ba3/likefit-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c1498cbfea9848cc248871ee64f38e222781971c91dad4be11fc8951de08d54e",
                "md5": "c4df1025e0492f1d274459d739a9f49e",
                "sha256": "303d0a768d0492b01def61fc8852bed51fe5e7a35fe5a21b5b108667fbf7f602"
            },
            "downloads": -1,
            "filename": "likefit-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "c4df1025e0492f1d274459d739a9f49e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 6410,
            "upload_time": "2024-01-05T21:58:08",
            "upload_time_iso_8601": "2024-01-05T21:58:08.393249Z",
            "url": "https://files.pythonhosted.org/packages/c1/49/8cbfea9848cc248871ee64f38e222781971c91dad4be11fc8951de08d54e/likefit-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-01-05 21:58:08",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "ravignad",
    "github_project": "likefit",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "likefit"
}
        
Elapsed time: 0.17276s