Skip to content
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
51 changes: 28 additions & 23 deletions preliz/distributions/distributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,37 +39,42 @@ def __init__(self):
self.is_frozen = False
self.opt = None

def __repr__(self):
def _get_name(self):
"""Return the display name for this distribution."""
name = self.__class__.__name__
if name in ["Truncated", "Censored", "Hurdle"]:
name += self.dist.__class__.__name__
if name == "Mixture":
name = (
"Mixture"
+ "".join(dict.fromkeys(dist.__class__.__name__ for dist in self.dist))
+ "\n"
name = "Mixture" + "".join(dict.fromkeys(dist.__class__.__name__ for dist in self.dist))
return name

def _get_description(self):
"""Return a string of parameters, or empty string if not frozen."""
if not self.is_frozen:
return ""
return "".join(
(
f"{n}={v:.3g}, "
if np.isscalar(v) or np.ndim(v) == 0
else f"{n}=["
+ "".join(f"{vi:.3g}, " for vi in np.atleast_1d(v)).strip(", ")
+ "], "
)
for n, v in zip(self.param_names, self.params)
).strip(", ")

def __repr__(self):
name = self._get_name()
if self.is_frozen:
if "Mixture" in name:
bolded_name = "\033[1m" + name.strip() + "\033[0m" + "\n"
else:
bolded_name = "\033[1m" + name + "\033[0m"

description = "".join(
(
f"{n}={v:.3g}, "
if np.isscalar(v) or np.ndim(v) == 0
else f"{n}=["
+ "".join(f"{vi:.3g}, " for vi in np.atleast_1d(v)).strip(", ")
+ "], "
)
for n, v in zip(self.param_names, self.params)
).strip(", ")
return f"{name}({self._get_description()})"
return name

return f"{bolded_name}({description})"
else:
return name
def _repr_html_(self):
name = self._get_name()
if self.is_frozen:
desc = self._get_description()
return f"<span style='font-weight:bold'>{name}</span><span'>({desc})</span>"
return f"<span style='font-weight:bold'>{name}</span>"

@property
def params_dict(self):
Expand Down
9 changes: 1 addition & 8 deletions preliz/internal/plot_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,13 +311,6 @@ def side_legend(legend, ax):
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))


def repr_to_matplotlib(distribution):
string = repr(distribution)
string = string.replace("\x1b[1m", r"$\bf{")
string = string.replace("\x1b[0m", "}$")
return string


def get_moments(dist, moments):
names = {
"m": "μ",
Expand Down Expand Up @@ -727,7 +720,7 @@ def set_label(dist, legend, moments, ax):
if isinstance(legend, str) and legend not in ["title", "legend"]:
label = legend
else:
label = repr_to_matplotlib(dist)
label = str(dist)

if moments is not None:
label += get_moments(dist, moments)
Expand Down
9 changes: 4 additions & 5 deletions preliz/internal/plot_helper_multivariate.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import numpy as np
from matplotlib import tri

from preliz.internal.plot_helper import repr_to_matplotlib
from preliz.internal.special import gammaln


Expand Down Expand Up @@ -194,7 +193,7 @@ def plot_dirichlet(
ax.set_ylim(*ylim)

if legend == "title":
fig.text(0.5, 1, repr_to_matplotlib(dist), ha="center", va="center")
fig.text(0.5, 1, dist, ha="center", va="center")

elif dim == 3:
dirichlet_ = DirichletOnSimplex(alpha)
Expand All @@ -203,7 +202,7 @@ def plot_dirichlet(
_, axes = plt.subplots(1, 1)
dirichlet_.plot(ax=axes)
if legend == "title":
axes.set_title(repr_to_matplotlib(dist))
axes.set_title(dist)
else:
raise ValueError("joint only works for Dirichlet of dim=3")

Expand Down Expand Up @@ -354,14 +353,14 @@ def plot_mvnormal(
if xy_lim != "auto" and representation != "cdf":
ax.set_ylim(*ylim)
if legend == "title":
fig.text(0.5, 1, repr_to_matplotlib(dist), ha="center", va="center")
fig.text(0.5, 1, dist, ha="center", va="center")

elif dim == 2:
if axes is None:
_, axes = plt.subplots(1, 1)
joint_normal(dist, axes)
if legend == "title":
axes.set_title(repr_to_matplotlib(dist))
axes.set_title(dist)
else:
raise ValueError("joint only works for Multivariate Normal of dim=2")

Expand Down
5 changes: 2 additions & 3 deletions preliz/internal/predictive_helper.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import numpy as np

from preliz.internal.distribution_helper import get_distributions
from preliz.internal.plot_helper import repr_to_matplotlib
from preliz.unidimensional import mle


Expand All @@ -11,7 +10,7 @@ def back_fitting_ppa(model, subset, new_families=True):

for name, dist in model.items():
dist._fit_mle(subset[name])
string += f"{name} = {repr_to_matplotlib(dist)}\n"
string += f"{name} = {dist}\n"

if new_families:
string += "\nYour selection is consistent with the priors (new families):\n"
Expand All @@ -26,7 +25,7 @@ def back_fitting_ppa(model, subset, new_families=True):
elif dist.kind == "discrete":
distributions = get_distributions(set([dist.__class__.__name__] + common_disc))
idx, _ = mle(distributions, subset[name], plot=False)
string += f"{name} = {repr_to_matplotlib(distributions[idx[0]])}\n"
string += f"{name} = {distributions[idx[0]]}\n"

return string, np.concatenate([dist.params for dist in model.values()])

Expand Down
6 changes: 2 additions & 4 deletions preliz/tests/test_posterior_to_prior.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,9 @@

def test_p2p_pymc():
posterior_to_prior(model, idata)
assert 'Gamma\x1b[0m("b", alpha=' in posterior_to_prior(model, idata, new_families="auto")
assert 'Gamma("b", alpha=' in posterior_to_prior(model, idata, new_families="auto")
posterior_to_prior(model, idata, new_families=[LogNormal()])
assert 'Gamma\x1b[0m("b", mu=' in posterior_to_prior(
model, idata, new_families={"b": [Gamma(mu=0)]}
)
assert 'Gamma("b", mu=' in posterior_to_prior(model, idata, new_families={"b": [Gamma(mu=0)]})


# Temporarily disabled bambi test
Expand Down
Loading