bambinos / bambi

BAyesian Model-Building Interface (Bambi) in Python.
https://bambinos.github.io/bambi/
MIT License
1.08k stars 124 forks source link

Implement truncated responses #752

Closed tomicapretto closed 1 year ago

tomicapretto commented 1 year ago

This PR adds a function truncated() that can be used in the formula syntax to specify truncated variables.

Example (taken from here)

import bambi as bmb
import numpy as np
import pandas as pd

rng = np.random.default_rng(12345)
slope, intercept, σ, N = 1, 0, 2, 200
x = rng.uniform(-10, 10, N)
y = rng.normal(loc=slope * x + intercept, scale=σ)

def truncate_y(x, y, bounds):
    keep = (y >= bounds[0]) & (y <= bounds[1])
    return (x[keep], y[keep])

bounds = [-5, 5]
xt, yt = truncate_y(x, y, bounds)

df = pd.DataFrame({"x": xt, "y": yt})
priors = {
    "Intercept": bmb.Prior("Normal", mu=0, sigma=1), 
    "x": bmb.Prior("Normal", mu=0, sigma=1),
    "sigma": bmb.Prior("HalfNormal", sigma=1)
}
model = bmb.Model("truncated(y, -5, 5) ~ x", df, priors=priors)

NOTE I still need to implement tests

codecov-commenter commented 1 year ago

Codecov Report

Merging #752 (f4eef3f) into main (ee266d9) will increase coverage by 0.05%. The diff coverage is 94.11%.

@@            Coverage Diff             @@
##             main     #752      +/-   ##
==========================================
+ Coverage   89.84%   89.90%   +0.05%     
==========================================
  Files          45       45              
  Lines        3664     3713      +49     
==========================================
+ Hits         3292     3338      +46     
- Misses        372      375       +3     
Files Coverage Δ
bambi/terms/response.py 79.68% <100.00%> (+0.32%) :arrow_up:
bambi/transformations.py 97.87% <100.00%> (+0.45%) :arrow_up:
bambi/terms/utils.py 91.30% <85.71%> (-2.45%) :arrow_down:
bambi/backend/terms.py 96.14% <88.23%> (-0.52%) :arrow_down:

:mega: Codecov offers a browser extension for seamless coverage viewing on GitHub. Try it in Chrome or Firefox today!