Metadata-Version: 2.4
Name: twinfit
Version: 0.0.1
Summary: Bias correction of a fit through a simulator of the data (indirect inference)
Author: Michelangelo Dondi
License-Expression: MIT
Keywords: indirect inference,bias correction,simulation,fitting,systematic errors
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21
Requires-Dist: scipy>=1.7
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Dynamic: license-file

# twinfit

Bias correction of a fit through a simulator of the data.

A fit maps a record to an estimate. When the estimate is biased, because the record is short, the fitted model is approximate or
the errors are not those the fit assumes, a simulator that is right where the fit is wrong can measure the bias. twinfit applies the
same fit to simulated records and corrects the estimate in one of two ways.

- `plugin_correction` measures the bias by simulating at the estimate, and subtracts it.
- `solved_correction` finds the parameters at which the mean fit of the simulations equals the fit of the data. This is indirect
  inference with the fit as its auxiliary statistic (Gourieroux, Monfort and Renault 1993). The same random draws are used at every
  trial, so the equation is smooth whenever the fit is.

## Install

```bash
pip install twinfit
```

## Example

The maximum likelihood estimate of a Gaussian variance from ten draws is biased low by a factor 9/10. The solved correction removes
that bias in expectation. A single record keeps its sampling error, so one corrected estimate can still sit far from the truth.

```python
import numpy as np
from twinfit import solved_correction

def simulate(theta, rng):          # one record at the parameters theta
    return np.sqrt(theta[0]) * rng.standard_normal(10)

def fit(record):                   # the fit to correct
    return np.var(record)

record = simulate([2.0], np.random.default_rng(1))
out = solved_correction(fit(record), simulate, fit, n_sim=400)
print(out.estimate, out.converged)
```

The result also carries the derivative of the mean fit with respect to the parameters, so that
`out.delta_covariance(C)` carries a covariance `C` of the raw estimate to the corrected one.

## Status

Version 0.0.1 is the first release. Further tools are in preparation.

## Reference

C. Gourieroux, A. Monfort and E. Renault (1993). Indirect inference. *Journal of Applied Econometrics* 8, S85-S118.
doi:10.1002/jae.3950080507

## Licence

MIT.
