-
-
Notifications
You must be signed in to change notification settings - Fork 398
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
Draft plot_bpv (bayesian p-value) #1222
Merged
Merged
Changes from 11 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f6b112d
draft new plot
aloctavodia 0283beb
add matplotlib backend
aloctavodia 40f8931
fix doc style
aloctavodia 48066d3
clean arguments
aloctavodia 5a27a6f
add bokeh plot
aloctavodia b021105
fix conflict plot_utils
aloctavodia 8089468
add examples
aloctavodia d3a55b4
Merge branch 'master' into plot_bpv
aloctavodia 1066491
add tests
aloctavodia 59c5f6b
remove logging fix doc style
aloctavodia d06cd5e
blackify
aloctavodia 73c89b6
improve docstring, explain option and add reference, rename mean argu…
aloctavodia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
"""Bokeh Bayesian p-value Posterior predictive plot.""" | ||
import numpy as np | ||
from bokeh.models import BoxAnnotation | ||
from bokeh.models.annotations import Title | ||
from scipy import stats | ||
|
||
from . import backend_kwarg_defaults | ||
from .. import show_layout | ||
from ...kdeplot import plot_kde | ||
from ...plot_utils import ( | ||
_create_axes_grid, | ||
sample_reference_distribution, | ||
is_valid_quantile, | ||
) | ||
from ....numeric_utils import _fast_kde | ||
|
||
|
||
def plot_bpv( | ||
ax, | ||
length_plotters, | ||
rows, | ||
cols, | ||
obs_plotters, | ||
pp_plotters, | ||
total_pp_samples, | ||
kind, | ||
t_stat, | ||
bpv, | ||
mean, | ||
reference, | ||
n_ref, | ||
hdi_prob, | ||
color, | ||
figsize, | ||
ax_labelsize, | ||
markersize, | ||
linewidth, | ||
plot_ref_kwargs, | ||
backend_kwargs, | ||
show, | ||
): | ||
"""Bokeh bpv plot.""" | ||
if backend_kwargs is None: | ||
backend_kwargs = {} | ||
|
||
backend_kwargs = { | ||
**backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"),), | ||
**backend_kwargs, | ||
} | ||
if ax is None: | ||
_, axes = _create_axes_grid( | ||
length_plotters, | ||
rows, | ||
cols, | ||
figsize=figsize, | ||
backend="bokeh", | ||
backend_kwargs=backend_kwargs, | ||
) | ||
else: | ||
axes = np.atleast_2d(ax) | ||
|
||
if len([item for item in axes.ravel() if not None]) != length_plotters: | ||
raise ValueError( | ||
"Found {} variables to plot but {} axes instances. They must be equal.".format( | ||
length_plotters, len(axes) | ||
) | ||
) | ||
|
||
for i, ax_i in enumerate((item for item in axes.flatten() if item is not None)): | ||
var_name, _, obs_vals = obs_plotters[i] | ||
pp_var_name, _, pp_vals = pp_plotters[i] | ||
|
||
obs_vals = obs_vals.flatten() | ||
pp_vals = pp_vals.reshape(total_pp_samples, -1) | ||
|
||
if kind == "p_value": | ||
tstat_pit = np.mean(pp_vals <= obs_vals, axis=-1) | ||
tstat_pit_dens, xmin, xmax = _fast_kde(tstat_pit) | ||
x_s = np.linspace(xmin, xmax, len(tstat_pit_dens)) | ||
ax_i.line(x_s, tstat_pit_dens, line_width=linewidth, color=color) | ||
# ax_i.set_yticks([]) | ||
if reference is not None: | ||
dist = stats.beta(obs_vals.size / 2, obs_vals.size / 2) | ||
if reference == "analytical": | ||
lwb = dist.ppf((1 - 0.9999) / 2) | ||
upb = 1 - lwb | ||
x = np.linspace(lwb, upb, 500) | ||
dens_ref = dist.pdf(x) | ||
ax_i.line(x, dens_ref, **plot_ref_kwargs) | ||
elif reference == "samples": | ||
x_ss, u_dens = sample_reference_distribution( | ||
dist, (n_ref, tstat_pit_dens.size,) | ||
) | ||
for x_ss_i, u_dens_i in zip(x_ss.T, u_dens.T): | ||
ax_i.line(x_ss_i, u_dens_i, line_width=linewidth, **plot_ref_kwargs) | ||
|
||
elif kind == "u_value": | ||
tstat_pit = np.mean(pp_vals <= obs_vals, axis=0) | ||
tstat_pit_dens, xmin, xmax = _fast_kde(tstat_pit) | ||
x_s = np.linspace(xmin, xmax, len(tstat_pit_dens)) | ||
ax_i.line(x_s, tstat_pit_dens, color=color) | ||
if reference is not None: | ||
if reference == "analytical": | ||
n_obs = obs_vals.size | ||
hdi = stats.beta(n_obs / 2, n_obs / 2).ppf((1 - hdi_prob) / 2) | ||
hdi_odds = (hdi / (1 - hdi), (1 - hdi) / hdi) | ||
ax_i.add_layout( | ||
BoxAnnotation( | ||
bottom=hdi_odds[1], | ||
top=hdi_odds[0], | ||
fill_alpha=plot_ref_kwargs.pop("alpha"), | ||
fill_color=plot_ref_kwargs.pop("color"), | ||
**plot_ref_kwargs, | ||
) | ||
) | ||
|
||
elif reference == "samples": | ||
dist = stats.uniform(0, 1) | ||
x_ss, u_dens = sample_reference_distribution(dist, (tstat_pit_dens.size, n_ref)) | ||
for x_ss_i, u_dens_i in zip(x_ss.T, u_dens.T): | ||
ax_i.line(x_ss_i, u_dens_i, line_width=linewidth, **plot_ref_kwargs) | ||
# ax_i.set_ylim(0, None) | ||
# ax_i.set_xlim(0, 1) | ||
else: | ||
if t_stat in ["mean", "median", "std"]: | ||
if t_stat == "mean": | ||
tfunc = np.mean | ||
elif t_stat == "median": | ||
tfunc = np.median | ||
elif t_stat == "std": | ||
tfunc = np.std | ||
obs_vals = tfunc(obs_vals) | ||
pp_vals = tfunc(pp_vals, axis=1) | ||
elif hasattr(t_stat, "__call__"): | ||
obs_vals = t_stat(obs_vals.flatten()) | ||
pp_vals = t_stat(pp_vals) | ||
elif is_valid_quantile(t_stat): | ||
t_stat = float(t_stat) | ||
obs_vals = np.quantile(obs_vals, q=t_stat) | ||
pp_vals = np.quantile(pp_vals, q=t_stat, axis=1) | ||
else: | ||
raise ValueError(f"T statistics {t_stat} not implemented") | ||
|
||
plot_kde(pp_vals, ax=ax_i, plot_kwargs={"color": color}, backend="bokeh", show=False) | ||
# ax_i.set_yticks([]) | ||
if bpv: | ||
p_value = np.mean(pp_vals <= obs_vals) | ||
ax_i.line(0, 0, legend_label=f"bpv={p_value:.2f}", alpha=0) | ||
|
||
if mean: | ||
ax_i.circle( | ||
obs_vals.mean(), 0, fill_color=color, line_color="black", size=markersize | ||
) | ||
|
||
if var_name != pp_var_name: | ||
xlabel = "{} / {}".format(var_name, pp_var_name) | ||
else: | ||
xlabel = var_name | ||
_title = Title() | ||
_title.text = xlabel | ||
ax_i.title = _title | ||
size = str(int(ax_labelsize)) | ||
ax_i.title.text_font_size = f"{size}pt" | ||
|
||
show_layout(axes, show) | ||
|
||
return axes |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
"""Matplotib Bayesian p-value Posterior predictive plot.""" | ||
import numpy as np | ||
import matplotlib.pyplot as plt | ||
from scipy import stats | ||
|
||
from . import backend_show | ||
from ...kdeplot import plot_kde | ||
from ...plot_utils import ( | ||
make_label, | ||
_create_axes_grid, | ||
sample_reference_distribution, | ||
is_valid_quantile, | ||
) | ||
from ....numeric_utils import _fast_kde | ||
|
||
|
||
def plot_bpv( | ||
ax, | ||
length_plotters, | ||
rows, | ||
cols, | ||
obs_plotters, | ||
pp_plotters, | ||
total_pp_samples, | ||
kind, | ||
t_stat, | ||
bpv, | ||
mean, | ||
reference, | ||
n_ref, | ||
hdi_prob, | ||
color, | ||
figsize, | ||
ax_labelsize, | ||
markersize, | ||
linewidth, | ||
plot_ref_kwargs, | ||
backend_kwargs, | ||
show, | ||
): | ||
"""Matplotlib bpv plot.""" | ||
if ax is None: | ||
_, axes = _create_axes_grid( | ||
length_plotters, rows, cols, figsize=figsize, backend_kwargs=backend_kwargs | ||
) | ||
else: | ||
axes = np.ravel(ax) | ||
if len(axes) != length_plotters: | ||
raise ValueError( | ||
"Found {} variables to plot but {} axes instances. They must be equal.".format( | ||
length_plotters, len(axes) | ||
) | ||
) | ||
|
||
for i, ax_i in enumerate(axes): | ||
var_name, selection, obs_vals = obs_plotters[i] | ||
pp_var_name, _, pp_vals = pp_plotters[i] | ||
|
||
obs_vals = obs_vals.flatten() | ||
pp_vals = pp_vals.reshape(total_pp_samples, -1) | ||
|
||
if kind == "p_value": | ||
tstat_pit = np.mean(pp_vals <= obs_vals, axis=-1) | ||
tstat_pit_dens, xmin, xmax = _fast_kde(tstat_pit) | ||
x_s = np.linspace(xmin, xmax, len(tstat_pit_dens)) | ||
ax_i.plot(x_s, tstat_pit_dens, linewidth=linewidth, color=color) | ||
ax_i.set_yticks([]) | ||
if reference is not None: | ||
dist = stats.beta(obs_vals.size / 2, obs_vals.size / 2) | ||
if reference == "analytical": | ||
lwb = dist.ppf((1 - 0.9999) / 2) | ||
upb = 1 - lwb | ||
x = np.linspace(lwb, upb, 500) | ||
dens_ref = dist.pdf(x) | ||
ax_i.plot(x, dens_ref, **plot_ref_kwargs) | ||
elif reference == "samples": | ||
x_ss, u_dens = sample_reference_distribution( | ||
dist, (n_ref, tstat_pit_dens.size,) | ||
) | ||
ax_i.plot(x_ss, u_dens, linewidth=linewidth, **plot_ref_kwargs) | ||
|
||
elif kind == "u_value": | ||
tstat_pit = np.mean(pp_vals <= obs_vals, axis=0) | ||
tstat_pit_dens, xmin, xmax = _fast_kde(tstat_pit) | ||
x_s = np.linspace(xmin, xmax, len(tstat_pit_dens)) | ||
ax_i.plot(x_s, tstat_pit_dens, color=color) | ||
if reference is not None: | ||
if reference == "analytical": | ||
n_obs = obs_vals.size | ||
hdi = stats.beta(n_obs / 2, n_obs / 2).ppf((1 - hdi_prob) / 2) | ||
hdi_odds = (hdi / (1 - hdi), (1 - hdi) / hdi) | ||
ax_i.axhspan(*hdi_odds, **plot_ref_kwargs) | ||
elif reference == "samples": | ||
dist = stats.uniform(0, 1) | ||
x_ss, u_dens = sample_reference_distribution(dist, (tstat_pit_dens.size, n_ref)) | ||
ax_i.plot(x_ss, u_dens, linewidth=linewidth, **plot_ref_kwargs) | ||
ax_i.set_ylim(0, None) | ||
ax_i.set_xlim(0, 1) | ||
else: | ||
if t_stat in ["mean", "median", "std"]: | ||
if t_stat == "mean": | ||
tfunc = np.mean | ||
elif t_stat == "median": | ||
tfunc = np.median | ||
elif t_stat == "std": | ||
tfunc = np.std | ||
obs_vals = tfunc(obs_vals) | ||
pp_vals = tfunc(pp_vals, axis=1) | ||
elif hasattr(t_stat, "__call__"): | ||
obs_vals = t_stat(obs_vals.flatten()) | ||
pp_vals = t_stat(pp_vals) | ||
elif is_valid_quantile(t_stat): | ||
t_stat = float(t_stat) | ||
obs_vals = np.quantile(obs_vals, q=t_stat) | ||
pp_vals = np.quantile(pp_vals, q=t_stat, axis=1) | ||
else: | ||
raise ValueError(f"T statistics {t_stat} not implemented") | ||
|
||
plot_kde(pp_vals, ax=ax_i, plot_kwargs={"color": color}) | ||
ax_i.set_yticks([]) | ||
if bpv: | ||
p_value = np.mean(pp_vals <= obs_vals) | ||
ax_i.plot(0, 0, label=f"bpv={p_value:.2f}", alpha=0) | ||
ax_i.legend() | ||
|
||
if mean: | ||
ax_i.plot( | ||
obs_vals.mean(), 0, "o", color=color, markeredgecolor="k", markersize=markersize | ||
) | ||
|
||
if var_name != pp_var_name: | ||
xlabel = "{} / {}".format(var_name, pp_var_name) | ||
else: | ||
xlabel = var_name | ||
ax_i.set_title(make_label(xlabel, selection), fontsize=ax_labelsize) | ||
|
||
if backend_show(show): | ||
plt.show() | ||
|
||
return axes |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.