Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Quartile int #288

Merged
merged 2 commits into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions preliz/internal/distribution_helper.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import re
import numpy as np
from scipy.special import gamma

Expand Down Expand Up @@ -92,6 +93,22 @@ def valid_distribution(self):
raise ValueError(f"{self.__class__.__name__} is not supported")


def process_extra(input_string):
pattern = r"(\w+)\((.*?)\)"
matches = re.findall(pattern, input_string)
result_dict = {}
for match in matches:
name = match[0]
args = match[1].split(",")
arg_dict = {}
for arg in args:
key, value = arg.split("=")
arg_dict[key.strip()] = float(value)
result_dict[name] = arg_dict

return result_dict


init_vals = {
"AsymmetricLaplace": {"kappa": 1.0, "mu": 0.0, "b": 1.0},
"Beta": {"alpha": 2, "beta": 2},
Expand Down
30 changes: 30 additions & 0 deletions preliz/internal/optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,36 @@ def fit_to_sample(selected_distributions, sample, x_min, x_max):
return fitted


def fit_to_quartile(dist_names, q1, q2, q3, extra_pros):
error = np.inf

for distribution in get_distributions(dist_names):
if distribution.__class__.__name__ in extra_pros:
distribution._parametrization(**extra_pros[distribution.__class__.__name__])
if distribution.__class__.__name__ == "BetaScaled":
update_bounds_beta_scaled(
distribution,
extra_pros[distribution.__class__.__name__]["lower"],
extra_pros[distribution.__class__.__name__]["upper"],
)
if distribution._check_endpoints(q1, q3, raise_error=False):

none_idx, fixed = get_fixed_params(distribution)

distribution._fit_moments(
mean=q2, sigma=(q3 - q1) / 1.35
) # pylint:disable=protected-access

optimize_quartile(distribution, (q1, q2, q3), none_idx, fixed)

r_error, _ = relative_error(distribution, q1, q3, 0.5)
if r_error < error:
fitted_dist = distribution
error = r_error

return fitted_dist


def update_bounds_beta_scaled(dist, x_min, x_max):
dist.lower = x_min
dist.upper = x_max
Expand Down
17 changes: 17 additions & 0 deletions preliz/internal/plot_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,3 +498,20 @@ def check_inside_notebook(need_widget=False):
tb_as_str = traceback.format_exc()
# Print only the last line of the traceback, which contains the error message
print(tb_as_str.strip().rsplit("\n", maxsplit=1)[-1], file=sys.stdout)


def representations(fitted_dist, kind_plot, ax):
if kind_plot == "pdf":
fitted_dist.plot_pdf(pointinterval=True, legend="title", ax=ax)
ax.set_yticks([])

for bound in fitted_dist.support:
if np.isfinite(bound):
ax.plot(bound, 0, "ko")

elif kind_plot == "cdf":
fitted_dist.plot_cdf(pointinterval=True, legend="title", ax=ax)

elif kind_plot == "ppf":
fitted_dist.plot_ppf(pointinterval=True, legend="title", ax=ax)
ax.set_xlim(-0.01, 1)
63 changes: 63 additions & 0 deletions preliz/tests/quartile_int.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "81849101",
"metadata": {},
"outputs": [],
"source": [
"%matplotlib widget\n",
"import pytest\n",
"import ipytest\n",
"ipytest.autoconfig()\n",
"\n",
"from preliz import quartile_int"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "1630c205",
"metadata": {},
"outputs": [],
"source": [
"%%ipytest\n",
"\n",
"@pytest.mark.parametrize(\"q1, q2, q3, dist_names, figsize\", [\n",
" (1, 2, 3, None, None), # Test default behavior\n",
" (-1, 2, 3, [\"Poisson\", \"Normal\"], None), # Test custom list of distributions\n",
" (-1, 2, 3, None, (10, 8)), # Test custom figsize\n",
"])\n",
"def test_quartile_int(q1, q2, q3, dist_names, figsize):\n",
" quartile_int(q1, q2, q3, dist_names, figsize)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "test",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.0"
},
"vscode": {
"interpreter": {
"hash": "5b344a7d0839c309585d2ae27435157813d3b4ade1fa431f12bd272ea9135317"
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}
9 changes: 9 additions & 0 deletions preliz/tests/test_distributions_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from preliz.internal.distribution_helper import process_extra


def test_process_extra():
ref0 = {"TruncatedNormal": {"lower": -3, "upper": 3}}
ref1 = {"StudentT": {"nu": 3.4}, "Normal": {"mu": 3.0}}

assert process_extra("TruncatedNormal(lower=-3, upper=3)") == ref0
assert process_extra("StudentT(nu=3.4),Normal(mu=3)") == ref1
3 changes: 2 additions & 1 deletion preliz/unidimensional/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from .maxent import maxent
from .mle import mle
from .quartile import quartile
from .quartile_int import quartile_int
from .roulette import roulette


__all__ = ["maxent", "mle", "roulette", "quartile"]
__all__ = ["maxent", "mle", "roulette", "quartile", "quartile_int"]
Loading