-
Notifications
You must be signed in to change notification settings - Fork 21
multimodal hdi feature #164
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
5438272
multimodal hdi
renecotyfanboy 7ab599b
Apply suggestion from @Copilot
renecotyfanboy cdbce0a
Apply suggestion from @Copilot
renecotyfanboy 0c1ed3f
Apply suggestion from @Copilot
renecotyfanboy 64248db
Apply suggestion from @Copilot
renecotyfanboy f1b0db8
Apply suggestion from @Copilot
renecotyfanboy 31594c9
Update src/chainconsumer/plotter.py
renecotyfanboy 4827d2b
fix bugs introduced by copilot
renecotyfanboy a37909f
implement suggestions
renecotyfanboy c593c91
Modify the chain defaults
renecotyfanboy 8da1218
Update usage.mdf
renecotyfanboy 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 hidden or 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 hidden or 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,79 @@ | ||
| """ | ||
| # Multimodal distributions | ||
|
|
||
| `ChainConsumer` can handle cases where the distributions of your chains are multimodal. | ||
| """ | ||
|
|
||
| import numpy as np | ||
| import pandas as pd | ||
|
|
||
| from chainconsumer import Chain, ChainConsumer | ||
| from chainconsumer.statistics import SummaryStatistic | ||
|
|
||
| # %% | ||
| # First, let's build some dummy data | ||
|
|
||
| rng = np.random.default_rng(42) | ||
| size = 60_000 | ||
|
|
||
| eta = rng.normal(loc=0.0, scale=0.8, size=size) | ||
|
|
||
| phi = np.asarray( | ||
| [rng.gamma(shape=2.5, scale=0.4, size=size // 2) - 3.0, 3.0 - rng.gamma(shape=5.0, scale=0.35, size=(size // 2))] | ||
| ).flatten() | ||
|
|
||
| rng.shuffle(phi) | ||
|
|
||
| df = pd.DataFrame({"eta": eta, "phi": phi}) | ||
|
|
||
| # %% | ||
| # To build a multimodal chain, you simply have to pass `multimodal=True` when building the chain. To work, it requires | ||
| # you to specify `SummaryStatistic.HDI` as the summary statistic. | ||
|
|
||
| chain_multimodal = Chain( | ||
| samples=df.copy(), | ||
| name="posterior-multimodal", | ||
| statistics=SummaryStatistic.HDI, | ||
| multimodal=True, # <- Here | ||
| ) | ||
|
|
||
| # %% | ||
| # Now, if you add this `Chain` to a plotter, it will try to look for sub-intervals and display them. | ||
|
|
||
| cc = ChainConsumer() | ||
| cc.add_chain(chain_multimodal) | ||
| fig = cc.plotter.plot() | ||
|
|
||
| # %% | ||
| # Let's compare with what would happen if you don't use a multimodal chain. We use the same data as before but don't | ||
| # tell `ChainConsumer` that we expect the chains to be multimodal. | ||
|
|
||
| chain_unimodal = Chain(samples=df.copy(), name="posterior-unimodal", statistics=SummaryStatistic.HDI, multimodal=False) | ||
|
|
||
| cc.add_chain(chain_unimodal) | ||
| fig = cc.plotter.plot() | ||
renecotyfanboy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # %% | ||
| # Let's try with even more modes. | ||
|
|
||
| eta = np.asarray( | ||
| [ | ||
| rng.normal(loc=-3, scale=0.8, size=size // 3), | ||
| rng.normal(loc=0.0, scale=0.8, size=size // 3), | ||
| rng.normal(loc=+3, scale=0.8, size=size // 3), | ||
| ] | ||
| ).flatten() | ||
|
|
||
|
|
||
| rng.shuffle(eta) | ||
|
|
||
| df = pd.DataFrame({"eta": eta, "phi": phi}) | ||
|
|
||
| chain_multimodal = Chain( | ||
| samples=df.copy(), name="posterior-multimodal", statistics=SummaryStatistic.HDI, multimodal=True | ||
| ) | ||
|
|
||
| cc = ChainConsumer() | ||
| cc.add_chain(chain_multimodal) | ||
| fig = cc.plotter.plot() | ||
| fig.tight_layout() | ||
This file contains hidden or 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,81 @@ | ||
| import matplotlib | ||
| import matplotlib.pyplot as plt | ||
| import numpy as np | ||
| import pandas as pd | ||
| from matplotlib import rc | ||
| from scipy.stats import gamma | ||
|
|
||
| from chainconsumer import Chain, ChainConsumer | ||
| from chainconsumer.statistics import SummaryStatistic | ||
|
|
||
| # Activate latex text rendering | ||
| rc("font", family="serif", serif=["Computer Modern Roman"], size=13) | ||
| rc("text", usetex=True) | ||
| matplotlib.rcParams["text.latex.preamble"] = r"\usepackage{amsmath}" | ||
|
|
||
| x = np.linspace(0, 5, 100) | ||
|
|
||
| loc = 4 | ||
| scale = 0.45 | ||
|
|
||
| fig, axs = plt.subplots(nrows=2, ncols=1, sharex=True, height_ratios=[0.5, 0.5], figsize=(5, 5)) | ||
| axs[0].plot(x, gamma.pdf(x, a=loc, scale=scale), color="black") | ||
| axs[1].plot(x, gamma.cdf(x, a=loc, scale=scale), color="black") | ||
|
|
||
|
|
||
| axs[1].set_xlabel("$x$") | ||
| axs[0].set_ylabel("$P(x)$") | ||
| axs[1].set_ylabel("$C(x)$") | ||
| axs[0].set_xlim(0, 5.0) | ||
| axs[0].set_ylim(0, 0.6) | ||
| axs[1].set_ylim(0, 1) | ||
|
|
||
| samples = pd.DataFrame.from_dict({"gamma": gamma.rvs(size=10_000_000, a=loc, scale=scale)}) | ||
|
|
||
| summary_list = [ | ||
| (SummaryStatistic.MAX, "MAX"), | ||
| (SummaryStatistic.CUMULATIVE, "CUMULATIVE"), | ||
| (SummaryStatistic.MEAN, "MEAN"), | ||
| (SummaryStatistic.HDI, "HDI"), | ||
| ] | ||
|
|
||
| chains = [] | ||
|
|
||
| for summary, name in summary_list: | ||
| chains.append(Chain(samples=samples, statistics=summary, name=name)) | ||
|
|
||
| cc = ChainConsumer() | ||
|
|
||
| summary_result = cc.analysis.get_summary(chains=chains, columns=["gamma"]) | ||
|
|
||
| for (_summary, name), color, linestyle, marker_style in zip( | ||
| summary_list, | ||
| ["r", "g", "b", "y"], | ||
| [":", "--", "-", "-."], | ||
| ["o", "^", "s", "*"], | ||
| strict=False, | ||
| ): | ||
| bound = summary_result[name]["gamma"] | ||
|
|
||
| x_min, x_mid, x_max = bound.lower, bound.center, bound.upper | ||
|
|
||
| axs[0].scatter(x_mid, gamma.pdf(x_mid, a=loc, scale=scale), label=name, zorder=10, color=color, marker=marker_style) | ||
| axs[1].scatter(x_mid, gamma.cdf(x_mid, a=loc, scale=scale), zorder=10, color=color, marker=marker_style) | ||
|
|
||
| axs[0].vlines( | ||
| x=x_min, ymin=0, ymax=gamma.pdf(x_min, a=loc, scale=scale), color=color, linestyle=linestyle, alpha=0.5 | ||
| ) | ||
| axs[0].vlines( | ||
| x=x_max, ymin=0, ymax=gamma.pdf(x_max, a=loc, scale=scale), color=color, linestyle=linestyle, alpha=0.5 | ||
| ) | ||
|
|
||
| axs[1].hlines( | ||
| xmin=0, xmax=x_min, y=gamma.cdf(x_min, a=loc, scale=scale), color=color, linestyle=linestyle, alpha=0.5 | ||
| ) | ||
| axs[1].hlines( | ||
| xmin=0, xmax=x_max, y=gamma.cdf(x_max, a=loc, scale=scale), color=color, linestyle=linestyle, alpha=0.5 | ||
| ) | ||
|
|
||
| axs[0].legend(fontsize=8) | ||
| plt.tight_layout() | ||
| plt.savefig("stats.png", bbox_inches="tight") |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or 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
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.
Uh oh!
There was an error while loading. Please reload this page.