fgivenx

fgivenx: A Python package for functional posterior plotting - Published in JOSS (2018)

https://github.com/handley-lab/fgivenx

Science Score: 59.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
    Found 6 DOI reference(s) in README
  • Academic publication links
    Links to: arxiv.org, joss.theoj.org, zenodo.org
  • Committers with academic emails
    4 of 9 committers (44.4%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (15.3%) to scientific vocabulary

Keywords

astrophysics astrostatistics bayesian-inference cosmology matplotlib plotting statistics

Keywords from Contributors

nested-sampling fastkde mcmc samples

Scientific Fields

Engineering Computer Science - 40% confidence
Last synced: 6 months ago · JSON representation

Repository

Functional Posterior Plotter

Basic Info
Statistics
  • Stars: 22
  • Watchers: 4
  • Forks: 11
  • Open Issues: 5
  • Releases: 15
Topics
astrophysics astrostatistics bayesian-inference cosmology matplotlib plotting statistics
Created over 8 years ago · Last pushed 8 months ago
Metadata Files
Readme Contributing License Code of conduct

README.rst

=====================================
fgivenx: Functional Posterior Plotter  
=====================================
:fgivenx:  Functional Posterior Plotter 
:Author: Will Handley
:Version: 2.5.0
:Homepage: https://github.com/handley-lab/fgivenx
:Documentation: http://fgivenx.readthedocs.io/

.. image:: https://github.com/handley-lab/fgivenx/workflows/CI/badge.svg?branch=master
   :target: https://github.com/handley-lab/fgivenx/actions?query=workflow%3ACI+branch%3Amaster
   :alt: Build Status
.. image:: https://codecov.io/gh/handley-lab/fgivenx/branch/master/graph/badge.svg
   :target: https://codecov.io/gh/handley-lab/fgivenx
   :alt: Test Coverage Status
.. image:: https://badge.fury.io/py/fgivenx.svg
   :target: https://badge.fury.io/py/fgivenx
   :alt: PyPi location
.. image:: https://readthedocs.org/projects/fgivenx/badge/?version=latest
   :target: https://fgivenx.readthedocs.io/en/latest/?badge=latest
   :alt: Documentation Status
.. image:: http://joss.theoj.org/papers/cf6f8ac309d6a18b6d6cf08b64aa3f62/status.svg
   :target: http://joss.theoj.org/papers/cf6f8ac309d6a18b6d6cf08b64aa3f62
   :alt: Review Status
.. image:: https://zenodo.org/badge/100947684.svg
   :target: https://zenodo.org/badge/latestdoi/100947684
   :alt: Permanent DOI
.. image:: https://img.shields.io/badge/arXiv-1908.01711-b31b1b.svg
   :target: https://arxiv.org/abs/1908.01711
   :alt: Open-access paper

Description
===========

``fgivenx`` is a python package for plotting posteriors of functions. It is
currently used in astronomy, but will be of use to any scientists performing
Bayesian analyses which have predictive posteriors that are functions.

This package allows one to plot a predictive posterior of a function,
dependent on sampled parameters. We assume one has a Bayesian posterior
``Post(theta|D,M)`` described by a set of posterior samples ``{theta_i}~Post``.
If there is a function parameterised by theta ``y=f(x;theta)``, then this script
will produce a contour plot of the conditional posterior ``P(y|x,D,M)`` in the
``(x,y)`` plane.

The driving routines are ``fgivenx.plot_contours``, ``fgivenx.plot_lines`` and
``fgivenx.plot_dkl``. The code is compatible with getdist, and has a loading function
provided by ``fgivenx.samples_from_getdist_chains``.

|image0|

Getting Started
===============

Users can install using pip:

.. code:: bash

   pip install fgivenx

from source:

.. code:: bash

   git clone https://github.com/handley-lab/fgivenx
   cd fgivenx
   python setup.py install --user

or for those on `Arch linux `__ it is
available on the
`AUR `__

You can check that things are working by running the test suite (You may
encounter warnings if the optional dependency ``joblib`` is not installed):

.. code:: bash

   pip install pytest pytest-runner pytest-mpl
   export MPLBACKEND=Agg
   pytest 

   # or, equivalently
   git clone https://github.com/handley-lab/fgivenx
   cd fgivenx
   python setup.py test

Check the dependencies listed in the next section are installed. You can then use the
``fgivenx`` module from your scripts.

Some users of OSX or `Anaconda `__ may find ``QueueManagerThread`` errors if `Pillow `__ is not installed (run ``pip install pillow``).

If you want to use parallelisation, have progress bars or getdist compatibility
you should install the additional optional dependencies:

.. code:: bash

   pip install joblib tqdm getdist
   # or, equivalently
   pip install -r  requirements.txt

You may encounter warnings if you don't have the optional dependency ``joblib``
installed.

Dependencies
=============
Basic requirements:

* Python 2.7+ or 3.4+
* `matplotlib `__
* `numpy `__
* `scipy `__

Documentation:

* `sphinx `__
* `numpydoc `__

Tests:

* `pytest `__
* `pytest-mpl `__

Optional extras:

* `joblib `__ (parallelisation) [`+ pillow `__ on some systems]
* `tqdm `__ (progress bars)
* `getdist `__ (reading of getdist compatible files)


Documentation
=============

Full Documentation is hosted at
`ReadTheDocs `__.
To build your own local copy of the documentation you'll need to install
`sphinx `__. You can then run:

.. code:: bash

   cd docs
   make html

Citation
========

If you use ``fgivenx`` to generate plots for a publication, please cite
as: ::

   Handley, (2018). fgivenx: A Python package for functional posterior
   plotting . Journal of Open Source Software, 3(28), 849,
   https://doi.org/10.21105/joss.00849

or using the BibTeX:

.. code:: bibtex

   @article{fgivenx,
       doi = {10.21105/joss.00849},
       url = {http://dx.doi.org/10.21105/joss.00849},
       year  = {2018},
       month = {Aug},
       publisher = {The Open Journal},
       volume = {3},
       number = {28},
       author = {Will Handley},
       title = {fgivenx: Functional Posterior Plotter},
       journal = {The Journal of Open Source Software}
   }

Example Usage
=============



Plot user-generated samples
---------------------------

.. code:: python

    import numpy
    import matplotlib.pyplot as plt
    from fgivenx import plot_contours, plot_lines, plot_dkl


    # Model definitions
    # =================
    # Define a simple straight line function, parameters theta=(m,c)
    def f(x, theta):
        m, c = theta
        return m * x + c


    numpy.random.seed(1)

    # Posterior samples
    nsamples = 1000
    ms = numpy.random.normal(loc=-5, scale=1, size=nsamples)
    cs = numpy.random.normal(loc=2, scale=1, size=nsamples)
    samples = numpy.array([(m, c) for m, c in zip(ms, cs)]).copy()

    # Prior samples
    ms = numpy.random.normal(loc=0, scale=5, size=nsamples)
    cs = numpy.random.normal(loc=0, scale=5, size=nsamples)
    prior_samples = numpy.array([(m, c) for m, c in zip(ms, cs)]).copy()

    # Set the x range to plot on
    xmin, xmax = -2, 2
    nx = 100
    x = numpy.linspace(xmin, xmax, nx)

    # Set the cache
    cache = 'cache/test'
    prior_cache = cache + '_prior'

    # Plotting
    # ========
    fig, axes = plt.subplots(2, 2)

    # Sample plot
    # -----------
    ax_samples = axes[0, 0]
    ax_samples.set_ylabel(r'$c$')
    ax_samples.set_xlabel(r'$m$')
    ax_samples.plot(prior_samples.T[0], prior_samples.T[1], 'b.')
    ax_samples.plot(samples.T[0], samples.T[1], 'r.')

    # Line plot
    # ---------
    ax_lines = axes[0, 1]
    ax_lines.set_ylabel(r'$y = m x + c$')
    ax_lines.set_xlabel(r'$x$')
    plot_lines(f, x, prior_samples, ax_lines, color='b', cache=prior_cache)
    plot_lines(f, x, samples, ax_lines, color='r', cache=cache)

    # Predictive posterior plot
    # -------------------------
    ax_fgivenx = axes[1, 1]
    ax_fgivenx.set_ylabel(r'$P(y|x)$')
    ax_fgivenx.set_xlabel(r'$x$')
    cbar = plot_contours(f, x, prior_samples, ax_fgivenx,
                         colors=plt.cm.Blues_r, lines=False,
                         cache=prior_cache)
    cbar = plot_contours(f, x, samples, ax_fgivenx, cache=cache)

    # DKL plot
    # --------
    ax_dkl = axes[1, 0]
    ax_dkl.set_ylabel(r'$D_\mathrm{KL}$')
    ax_dkl.set_xlabel(r'$x$')
    ax_dkl.set_ylim(bottom=0, top=2.0)
    plot_dkl(f, x, samples, prior_samples, ax_dkl,
             cache=cache, prior_cache=prior_cache)


    ax_lines.sharex(ax_fgivenx)
    ax_dkl.sharex(ax_fgivenx)
    ax_lines.sharey(ax_fgivenx)
    ax_fgivenx.sharey(ax_samples)

    fig.tight_layout()
    fig.savefig('plot.png')

|image0|

Plot GetDist chains
-------------------

.. code:: python

    import numpy
    import matplotlib.pyplot as plt
    from fgivenx import plot_contours, samples_from_getdist_chains

    file_root = './plik_HM_TT_lowl/base_plikHM_TT_lowl'
    samples, weights = samples_from_getdist_chains(['logA', 'ns'], file_root)

    def PPS(k, theta):
        logA, ns = theta
        return logA + (ns - 1) * numpy.log(k)
        
    k = numpy.logspace(-4,1,100)
    cbar = plot_contours(PPS, k, samples, weights=weights)
    cbar = plt.colorbar(cbar,ticks=[0,1,2,3])
    cbar.set_ticklabels(['',r'$1\sigma$',r'$2\sigma$',r'$3\sigma$'])
    
    plt.xscale('log')
    plt.ylim(2,4)
    plt.ylabel(r'$\ln\left(10^{10}\mathcal{P}_\mathcal{R}\right)$')
    plt.xlabel(r'$k / {\rm Mpc}^{-1}$')
    plt.tight_layout()
    plt.savefig('planck.png')

|image1|

Contributing
============
Want to contribute to ``fgivenx``? Awesome!
There are many ways you can contribute via the 
[GitHub repository](https://github.com/handley-lab/fgivenx), 
see below.

Opening issues
--------------
Open an issue to report bugs or to propose new features.

Proposing pull requests
-----------------------
Pull requests are very welcome. Note that if you are going to propose drastic
changes, be sure to open an issue for discussion first, to make sure that your
PR will be accepted before you spend effort coding it.

.. |image0| image:: https://raw.githubusercontent.com/handley-lab/fgivenx/master/plot.png
.. |image1| image:: https://raw.githubusercontent.com/handley-lab/fgivenx/master/planck.png 

Changelog
=========
:v2.2.0:  Paper accepted
:v2.1.17: 100% coverage
:v2.1.16: Tests fixes
:v2.1.15: Additional plot tests
:v2.1.13: Further bug fix in test suite for image comparison
:v2.1.12: Bug fix in test suite for image comparison
:v2.1.11: Documentation upgrades
:v2.1.10: Added changelog

Owner

  • Name: Will Handley's Research Group
  • Login: handley-lab
  • Kind: organization
  • Email: wh260@cam.ac.uk
  • Location: University of Cambridge

GitHub Events

Total
  • Create event: 3
  • Issues event: 1
  • Watch event: 2
  • Delete event: 5
  • Member event: 1
  • Issue comment event: 23
  • Push event: 19
  • Pull request event: 7
  • Pull request review event: 12
  • Pull request review comment event: 3
  • Fork event: 2
Last Year
  • Create event: 3
  • Issues event: 1
  • Watch event: 2
  • Delete event: 5
  • Member event: 1
  • Issue comment event: 23
  • Push event: 19
  • Pull request event: 7
  • Pull request review event: 12
  • Pull request review comment event: 3
  • Fork event: 2

Committers

Last synced: 7 months ago

All Time
  • Total Commits: 275
  • Total Committers: 9
  • Avg Commits per committer: 30.556
  • Development Distribution Score (DDS): 0.087
Past Year
  • Commits: 5
  • Committers: 3
  • Avg Commits per committer: 1.667
  • Development Distribution Score (DDS): 0.4
Top Committers
Name Email Commits
Will Handley w****0@c****k 251
ejhigson e****n@g****m 11
SonkeHee s****7@c****k 4
Adam Ormondroyd 5****d 3
Adam Ormondroyd 5****d 2
Stefan Heimersheim s****m@r****e 1
Duncan Macleod d****b@g****m 1
Thomas Gessey-Jones t****s@g****m 1
Stefan Heimersheim h****m@a****k 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 12
  • Total pull requests: 23
  • Average time to close issues: 9 months
  • Average time to close pull requests: 3 months
  • Total issue authors: 7
  • Total pull request authors: 7
  • Average comments per issue: 2.0
  • Average comments per pull request: 1.78
  • Merged pull requests: 17
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 0
  • Pull requests: 5
  • Average time to close issues: N/A
  • Average time to close pull requests: about 3 hours
  • Issue authors: 0
  • Pull request authors: 2
  • Average comments per issue: 0
  • Average comments per pull request: 1.8
  • Merged pull requests: 2
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • Stefan-Heimersheim (4)
  • surgithub (2)
  • yuanzunli (2)
  • jpmvferreira (1)
  • duncanmmacleod (1)
  • ThomasEdwardRiley (1)
  • williamjameshandley (1)
Pull Request Authors
  • AdamOrmondroyd (10)
  • williamjameshandley (4)
  • Stefan-Heimersheim (3)
  • ejhigson (2)
  • ThomasGesseyJones (2)
  • htjb (1)
  • duncanmmacleod (1)
Top Labels
Issue Labels
Pull Request Labels

Dependencies

minimal_requirements.txt pypi
  • matplotlib *
  • numpy *
  • scipy *
requirements.txt pypi
  • getdist *
  • joblib *
  • matplotlib *
  • numpy *
  • numpydoc *
  • scipy *
  • sphinx *
  • tqdm *
setup.py pypi
  • matplotlib *
  • numpy *
  • scipy *
.github/workflows/CI.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • codecov/codecov-action v1 composite