diff --git a/.coveragerc b/.coveragerc deleted file mode 100644 index 16086ff6..00000000 --- a/.coveragerc +++ /dev/null @@ -1,15 +0,0 @@ -[run] -relative_files = True -source = pyrolite -omit = - # Omit test, docs, draft and data files - test/* - docs/* - **/data - draft/* - - # Omit extensions with extra dependencies - pyrolite/util/database.py - - # Ignore _version.py - */_version.py diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index 720b5188..f106fc24 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -18,18 +18,6 @@ jobs: matrix: os: [ubuntu-latest, windows-latest, macos-latest] python-version: [3.8, 3.9, "3.10", "3.11"] - # exclude: - # # excludes py38 on macOS, which seems to stall currently - # - os: macos-latest - # python-version: 3.8 - # - os: macos-latest - # python-version: 3.9 - # - os: macos-latest - # python-version: "3.10" - # - os: macos-latest - # python-version: "3.11" - # - os: windows-latest - # python-version: "3.11" steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 @@ -41,26 +29,24 @@ jobs: run: | python -m pip install --upgrade pip # upgrade pip pip install wheel - pip install -q pytest pytest-runner pytest-cov coverage codacy-coverage - pip install coveralls - pip install .[skl,stats] + pip install .[skl,stats,test] codacy-coverage - name: Test Windows if: runner.os == 'Windows' env: MPLBACKEND: Agg - run: python setup.py test + run: pytest - name: Test MacOS if: runner.os == 'macOS' - run: python setup.py test + run: pytest - name: Prep Linux if: runner.os == 'Linux' run: | - sudo apt-get install jq curl # codacy requirement + sudo apt-get install jq curl # codacy requirement sudo apt-get install xvfb - name: Test Linux if: runner.os == 'Linux' run: | - xvfb-run python setup.py test + xvfb-run pytest - name: Coveralls env: COVERALLS_SERVICE_NAME: github diff --git a/.gitignore b/.gitignore index 26d63477..d9212868 100644 --- a/.gitignore +++ b/.gitignore @@ -106,7 +106,5 @@ venv.bak/ # classifier model builds *.clsf.gz -doc/examples/scratch\.py - # local alphamelts install folder pyrolite/data/alphamelts/localinstall/* diff --git a/.readthedocs.yml b/.readthedocs.yml index 951f8d24..bb84a5f3 100644 --- a/.readthedocs.yml +++ b/.readthedocs.yml @@ -5,6 +5,11 @@ # Required version: 2 +build: + os: ubuntu-22.04 + tools: + python: "3.10" + # Build documentation in the docs/ directory with Sphinx sphinx: configuration: docs/source/conf.py @@ -21,4 +26,8 @@ formats: # Optionally set the version of Python and requirements required to build your docs python: install: - - requirements: docs/docs_require.txt + - method: pip + path: . + extra_requirements: + - docs + - skl # for sklearn-based examples diff --git a/MANIFEST.in b/MANIFEST.in index 594ec486..20a0dfff 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -9,4 +9,4 @@ recursive-include pyrolite/data/radii * recursive-include pyrolite/data/timescale * recursive-include pyrolite/data/testing * recursive-include pyrolite/data/_config * -# global-exclude __pycache__ +global-exclude **/__pycache__/* diff --git a/README.md b/README.md index d4044807..25a0dc31 100644 --- a/README.md +++ b/README.md @@ -65,9 +65,9 @@ If you use pyrolite extensively for your research, citation of the software woul [![Formatted with Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/python/black) [![Code Quality](https://api.codacy.com/project/badge/Grade/fd9912a3faae43bf84a47e3da685d84c)](https://app.codacy.com/gh/morganjwilliams/pyrolite/dashboard?utm_source=github.com&utm_medium=referral&utm_content=morganjwilliams/pyrolite&utm_campaign=Badge_Grade) -| **master** | **develop** | +| **main** | **develop** | |:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:| -| [![Unit Tests on Master](https://github.com/morganjwilliams/pyrolite/workflows/Unittest/badge.svg?branch=main)](https://github.com/morganjwilliams/pyrolite/actions?query=workflow:Unittest+branch:main) | [![Unit Tests on Develop](https://github.com/morganjwilliams/pyrolite/workflows/Unittest/badge.svg?branch=develop)](https://github.com/morganjwilliams/pyrolite/actions?query=workflow:Unittest+branch:develop) | +| [![Unit Tests on main](https://github.com/morganjwilliams/pyrolite/workflows/Unittest/badge.svg?branch=main)](https://github.com/morganjwilliams/pyrolite/actions?query=workflow:Unittest+branch:main) | [![Unit Tests on Develop](https://github.com/morganjwilliams/pyrolite/workflows/Unittest/badge.svg?branch=develop)](https://github.com/morganjwilliams/pyrolite/actions?query=workflow:Unittest+branch:develop) | | [![Coverage Status](https://coveralls.io/repos/github/morganjwilliams/pyrolite/badge.svg?branch=main)](https://coveralls.io/github/morganjwilliams/pyrolite?branch=main) | [![Coverage Status](https://coveralls.io/repos/github/morganjwilliams/pyrolite/badge.svg?branch=develop)](https://coveralls.io/github/morganjwilliams/pyrolite?branch=develop) | **Maintainer**: Morgan Williams (morgan.williams _at_ csiro.au) diff --git a/binder/environment.yml b/binder/environment.yml index 909ec8bf..3f1ec6e3 100644 --- a/binder/environment.yml +++ b/binder/environment.yml @@ -7,8 +7,5 @@ channels: dependencies: - python=3.10 - pip - - matplotlib - - scipy>=1.2 - - pandas>=0.23 - pip: - - -e git+https://github.com/morganjwilliams/pyrolite.git@develop#egg=pyrolite[dev,skl] + - -e git+https://github.com/morganjwilliams/pyrolite.git@develop#egg=pyrolite[dev,skl,excel] diff --git a/docs/docs_require.txt b/docs/docs_require.txt deleted file mode 100644 index b0ec97f6..00000000 --- a/docs/docs_require.txt +++ /dev/null @@ -1 +0,0 @@ -.[docs,skl] diff --git a/docs/source/.gitignore b/docs/source/.gitignore new file mode 100644 index 00000000..25c57ff6 --- /dev/null +++ b/docs/source/.gitignore @@ -0,0 +1,4 @@ +/examples/* +/tutorials/* +/data/* +/_backreferences/* \ No newline at end of file diff --git a/docs/source/dev/changelog.rst b/docs/source/dev/changelog.rst index 089b2c05..c4561508 100644 --- a/docs/source/dev/changelog.rst +++ b/docs/source/dev/changelog.rst @@ -10,15 +10,23 @@ All notable changes to this project will be documented here. If you're keen to check something out before its released, you can use a `development install `__ . +`0.3.4`_ +-------------- + +* **Bugfix**: `Tom Buckle `__ contributed a PR with + some minor bugfixes for the CIPW Norm. +* Various maintainence updates, including migrating the pacakge to use `pyproject.toml`. + `0.3.3`_ -------------- -* **New Contributor**: `Sarah Shi `__ -* **New Contributor**: `Ondrej Lexa `__ +* **New Contributor**: `Sarah Shi `__ +* **New Contributor**: `Ondrej Lexa `__ * **Bugfix**: Updated docs builds to be compatible with recent versions of `sphinx-gallery`. * **Bugfix**: Updated some :mod:`pandas` assignment, aggregation and similar operations to be compatible with more recent versions of Pandas. -* Addedd explict Python 3.10 support. +* Added explicit Python 3.10 and 3.11 support. +* Removed Python 3.7 support (now end of life). :mod:`pyrolite.mineral` @@ -1337,8 +1345,9 @@ All notable changes to this project will be documented here. `GitHub `__ for reference, but were :code:`alpha` versions which were never considered stable. -.. _Development: https://github.com/morganjwilliams/pyrolite/compare/0.3.3...develop -.. _0.3.3: https://github.com/morganjwilliams/pyrolite/compare/0.3.1...0.3.2 +.. _Development: https://github.com/morganjwilliams/pyrolite/compare/0.3.4...develop +.. _0.3.4: https://github.com/morganjwilliams/pyrolite/compare/0.3.3...0.3.4 +.. _0.3.3: https://github.com/morganjwilliams/pyrolite/compare/0.3.2...0.3.3 .. _0.3.2: https://github.com/morganjwilliams/pyrolite/compare/0.3.1...0.3.2 .. _0.3.1: https://github.com/morganjwilliams/pyrolite/compare/0.3.0...0.3.1 .. _0.3.0: https://github.com/morganjwilliams/pyrolite/compare/0.2.8...0.3.0 diff --git a/docs/source/examples/comp/compositional_data.ipynb b/docs/source/examples/comp/compositional_data.ipynb deleted file mode 100644 index 4b99ff97..00000000 --- a/docs/source/examples/comp/compositional_data.ipynb +++ /dev/null @@ -1,259 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nCompositional Data?\n--------------------\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "pyrolite comes with a few datasets from Aitchison (1984) built in which we can use\nas examples:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pyrolite.plot import pyroplot\nfrom pyrolite.data.Aitchison import load_kongite\n\ndf = load_kongite()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For compositional data, everything is relative (thanks to the closure property), so we\ntend to use ratios to express differences or changes between things. However,\nif we make incorrect assumptions about the nature of our data, we can get some incorrect\nanswers. Say you want to know the average ratio between A and B:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "A_on_B = df[\"A\"] / df[\"B\"]\nA_on_B.mean() # 2.8265837788402983" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Equally, you could have chosen to calculate the average ratio between B and A\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "B_on_A = df[\"B\"] / df[\"A\"]\nB_on_A.mean() # 0.4709565704852008" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You expect these to be invertable, such that A_on_B = 1 / B_on_A; but not so!\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "A_on_B.mean() / (1 / B_on_A.mean()) # 1.3311982026717262" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Similarly, the relative variances are different:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "np.std(A_on_B) / A_on_B.mean() # 0.6295146309597085\nnp.std(B_on_A) / B_on_A.mean() # 0.5020948201979953" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This improves when using logratios in place of simple ratios, prior to exponentiating means\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "logA_on_B = (df[\"A\"] / df[\"B\"]).apply(np.log)\nlogB_on_A = (df[\"B\"] / df[\"A\"]).apply(np.log)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The logratios are invertible:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "np.exp(logA_on_B.mean()) # 2.4213410747400514\n1 / np.exp(logB_on_A.mean()) # 2.421341074740052" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The logratios also have the same variance:\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "(np.std(logA_on_B) / logA_on_B.mean()) ** 2 # 0.36598579018127086\n(np.std(logB_on_A) / logB_on_A.mean()) ** 2 # 0.36598579018127086" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These peculiarities result from incorrect assumptions regarding the distribution of the\ndata: ratios of compositional components are typically *lognormally* distributed, rather\nthan *normally* distributed, and the compositional components themselves commonly have\na `Poisson distribution `__ .\nThese distributions contrast significantly with the normal distribution at the core of\nmost statistical tests. We can compare distributions with similar means and variances\nbut different forms, and note that the normal distribution has one immediate\nfailure, in that it has non-zero probability density below 0, and we know that you can't\nhave negative atoms!\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from scipy.stats import norm, poisson, lognorm\n\nmeans = [[10, 10], [10, 20], [20, 100], [1000, 50]]\nfig, ax = plt.subplots(len(means), 4, figsize=(11, 8))\nax[0, 0].set_title(\"A\")\nax[0, 1].set_title(\"B\")\nax[0, 2].set_title(\"Normal Fit to B/A\")\nax[0, 3].set_title(\"Lognormal Fit to B/A\")\nax[-1, 0].set_xlabel(\"A\")\nax[-1, 1].set_xlabel(\"B\")\nax[-1, 2].set_xlabel(\"B/A\")\nax[-1, 3].set_xlabel(\"B/A\")\nfor ix, (m1, m2) in enumerate(means):\n p1, p2 = poisson(mu=m1), poisson(mu=m2)\n y1, y2 = p1.rvs(2000), p2.rvs(2000)\n ratios = y2[y1 > 0] / y1[y1 > 0]\n\n y1min, y1max = y1.min(), y1.max()\n y2min, y2max = y2.min(), y2.max()\n ax[ix, 0].hist(\n y1,\n color=\"0.5\",\n alpha=0.6,\n label=\"A\",\n bins=np.linspace(y1min - 0.5, y1max + 0.5, (y1max - y1min) + 1),\n )\n ax[ix, 1].hist(\n y2,\n color=\"0.5\",\n alpha=0.6,\n label=\"B\",\n bins=np.linspace(y2min - 0.5, y2max + 0.5, (y2max - y2min) + 1),\n )\n\n # normal distribution fit\n H, binedges, patches = ax[ix, 2].hist(\n ratios, color=\"Purple\", alpha=0.6, label=\"Ratios\", bins=100\n )\n loc, scale = norm.fit(ratios, loc=0)\n pdf = norm.pdf(binedges, loc, scale)\n twin2 = ax[ix, 2].twinx()\n twin2.set_ylim(0, 1.1 * np.max(pdf))\n twin2.plot(binedges, pdf, color=\"k\", ls=\"--\", label=\"Normal Fit\")\n\n # log-normal distribution fit\n H, binedges, patches = ax[ix, 3].hist(\n ratios, color=\"Green\", alpha=0.6, label=\"Ratios\", bins=100\n )\n s, loc, scale = lognorm.fit(ratios, loc=0)\n pdf = lognorm.pdf(binedges, s, loc, scale)\n twin3 = ax[ix, 3].twinx()\n twin3.set_ylim(0, 1.1 * np.max(pdf))\n twin3.plot(binedges, pdf, color=\"k\", ls=\"--\", label=\"Lognormal Fit\")\n\n for a in [*ax[ix, :], twin2, twin3]:\n a.set_yticks([])\n\nplt.tight_layout()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The form of these distributions is a reflection of the fact that geochemical data\nis at is core a measure of relative quantities of atoms. Quantities of atoms have\ndiscrete distributions (i.e. you can have precisely 0, 1 or 6.02 x 10^23 atoms, but 1.23\natoms is not a sensible state of affairs); if you were to count them in a shiny\nmachine, the amount of atoms you might measure over a given period will have a Poisson\ndistribution. If you measure two components, the probability density distribution of the\nratio is well approximated by a lognormal distribution (note this doesn't consider\ninherent covariance):\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.plot.axes import share_axes, subaxes\nfrom pyrolite.util.distributions import lognorm_to_norm, norm_to_lognorm\n\n# starting from a normal distribution, then creating similar non-normal distributions\nmean, sd = 2.5, 1.5 #\nlogmu, logs = norm_to_lognorm(mean, sd) # parameters for equival\nnormrv = norm(loc=mean, scale=sd)\nlognormrv = lognorm(s=logs, scale=logmu)\npoissonrv = poisson(mu=mean)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can visualise the similarities and differences between these distributions:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(2, 3, figsize=(8, 4))\nax = ax.flat\nfor a in ax:\n a.subax = subaxes(a, side=\"bottom\")\n\nshare_axes(ax[:3], which=\"x\")\nshare_axes(ax[3:], which=\"x\")\nax[0].set_xlim(-2, 10)\nax[3].set_xscale(\"log\")\nax[3].set_xlim(0.1, 10)\n\nfor a in ax:\n a.axvline(0, color=\"k\", lw=0.5, ls=\"--\")\n\n# xs at which to evaluate the pdfs\nx = np.linspace(-5, 15.0, 1001)\n\nfor ix, dist in enumerate([normrv, lognormrv, poissonrv]):\n _xs = dist.rvs(size=10000) # random sample\n _ys = -0.05 + np.random.randn(10000) / 100 # random offsets for visualisation\n for a in [ax[ix], ax[ix + 3]]:\n a.annotate(\n \"mean={:.2f}, var={:.2f}\".format(np.mean(_xs), np.var(_xs)),\n xy=(0.05, 1.05),\n ha=\"left\",\n va=\"bottom\",\n xycoords=a.transAxes,\n )\n a.subax.scatter(_xs, _ys, s=2, color=\"k\", alpha=0.01)\n if dist != poissonrv: # cont. distribution\n a.plot(x, dist.pdf(x), color=\"Purple\", alpha=0.6, label=\"pdf\")\n else: # discrete distribution\n a.vlines(\n x[x >= 0],\n 0,\n dist.pmf(x[x >= 0]),\n color=\"Purple\",\n alpha=0.6,\n label=\"pmf\",\n )\n\nfig.suptitle(\"Data Distributions: Normal, Lognormal, Poisson\", y=1.1)\nplt.tight_layout()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Accounting for these inherent features of geochemical data will allow you to\naccurately estimate means and variances, and from this enables the use of\nstandardised statistical measures - as long as you're log-transforming your data.\nWhen performing multivariate analysis, use log-ratio transformations (including the\nadditive logratio :func:`~pyrolite.comp.codata.alr`, centred logratio\n:func:`~pyrolite.comp.codata.clr` and isometric logratio\n:func:`~pyrolite.comp.codata.ilr`). In this case, the logratio-mean is implemented for\nyou:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.comp.codata import logratiomean\nimport itertools\n\nfig, ax = plt.subplots(2, 2, figsize=(12, 12), subplot_kw=dict(projection=\"ternary\"))\nax = ax.flat\n\nfor columns, a in zip(itertools.combinations([\"A\", \"B\", \"C\", \"D\"], 3), ax):\n columns = list(columns)\n\n df.loc[:, columns].pyroplot.scatter(\n ax=a, color=\"k\", marker=\".\", label=df.name, no_ticks=True\n )\n\n df.mean().loc[columns].pyroplot.scatter(\n ax=a,\n edgecolors=\"red\",\n linewidths=2,\n c=\"none\",\n s=50,\n label=\"Arithmetic Mean\",\n no_ticks=True,\n )\n\n logratiomean(df.loc[:, columns]).pyroplot.scatter(\n ax=a,\n edgecolors=\"k\",\n linewidths=2,\n c=\"none\",\n s=50,\n label=\"Geometric Mean\",\n axlabels=True,\n no_ticks=True,\n )\n a.legend(frameon=False, facecolor=None, loc=(0.8, 0.5))" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/comp/compositional_data.py b/docs/source/examples/comp/compositional_data.py deleted file mode 100644 index 4ff767aa..00000000 --- a/docs/source/examples/comp/compositional_data.py +++ /dev/null @@ -1,231 +0,0 @@ -""" -Compositional Data? --------------------- -""" - -######################################################################################## -# pyrolite comes with a few datasets from Aitchison (1984) built in which we can use -# as examples: -# -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from pyrolite.plot import pyroplot -from pyrolite.data.Aitchison import load_kongite - -df = load_kongite() -######################################################################################## -# For compositional data, everything is relative (thanks to the closure property), so we -# tend to use ratios to express differences or changes between things. However, -# if we make incorrect assumptions about the nature of our data, we can get some incorrect -# answers. Say you want to know the average ratio between A and B: -# -A_on_B = df["A"] / df["B"] -A_on_B.mean() # 2.8265837788402983 -######################################################################################## -# Equally, you could have chosen to calculate the average ratio between B and A -# -B_on_A = df["B"] / df["A"] -B_on_A.mean() # 0.4709565704852008 -######################################################################################## -# You expect these to be invertable, such that A_on_B = 1 / B_on_A; but not so! -# -A_on_B.mean() / (1 / B_on_A.mean()) # 1.3311982026717262 -######################################################################################## -# Similarly, the relative variances are different: -# -np.std(A_on_B) / A_on_B.mean() # 0.6295146309597085 -np.std(B_on_A) / B_on_A.mean() # 0.5020948201979953 -######################################################################################## -# This improves when using logratios in place of simple ratios, prior to exponentiating means -# -logA_on_B = (df["A"] / df["B"]).apply(np.log) -logB_on_A = (df["B"] / df["A"]).apply(np.log) -######################################################################################## -# The logratios are invertible: -# -np.exp(logA_on_B.mean()) # 2.4213410747400514 -1 / np.exp(logB_on_A.mean()) # 2.421341074740052 -######################################################################################## -# The logratios also have the same variance: -(np.std(logA_on_B) / logA_on_B.mean()) ** 2 # 0.36598579018127086 -(np.std(logB_on_A) / logB_on_A.mean()) ** 2 # 0.36598579018127086 - -######################################################################################## -# These peculiarities result from incorrect assumptions regarding the distribution of the -# data: ratios of compositional components are typically *lognormally* distributed, rather -# than *normally* distributed, and the compositional components themselves commonly have -# a `Poisson distribution `__ . -# These distributions contrast significantly with the normal distribution at the core of -# most statistical tests. We can compare distributions with similar means and variances -# but different forms, and note that the normal distribution has one immediate -# failure, in that it has non-zero probability density below 0, and we know that you can't -# have negative atoms! -# -from scipy.stats import norm, poisson, lognorm - -means = [[10, 10], [10, 20], [20, 100], [1000, 50]] -fig, ax = plt.subplots(len(means), 4, figsize=(11, 8)) -ax[0, 0].set_title("A") -ax[0, 1].set_title("B") -ax[0, 2].set_title("Normal Fit to B/A") -ax[0, 3].set_title("Lognormal Fit to B/A") -ax[-1, 0].set_xlabel("A") -ax[-1, 1].set_xlabel("B") -ax[-1, 2].set_xlabel("B/A") -ax[-1, 3].set_xlabel("B/A") -for ix, (m1, m2) in enumerate(means): - p1, p2 = poisson(mu=m1), poisson(mu=m2) - y1, y2 = p1.rvs(2000), p2.rvs(2000) - ratios = y2[y1 > 0] / y1[y1 > 0] - - y1min, y1max = y1.min(), y1.max() - y2min, y2max = y2.min(), y2.max() - ax[ix, 0].hist( - y1, - color="0.5", - alpha=0.6, - label="A", - bins=np.linspace(y1min - 0.5, y1max + 0.5, (y1max - y1min) + 1), - ) - ax[ix, 1].hist( - y2, - color="0.5", - alpha=0.6, - label="B", - bins=np.linspace(y2min - 0.5, y2max + 0.5, (y2max - y2min) + 1), - ) - - # normal distribution fit - H, binedges, patches = ax[ix, 2].hist( - ratios, color="Purple", alpha=0.6, label="Ratios", bins=100 - ) - loc, scale = norm.fit(ratios, loc=0) - pdf = norm.pdf(binedges, loc, scale) - twin2 = ax[ix, 2].twinx() - twin2.set_ylim(0, 1.1 * np.max(pdf)) - twin2.plot(binedges, pdf, color="k", ls="--", label="Normal Fit") - - # log-normal distribution fit - H, binedges, patches = ax[ix, 3].hist( - ratios, color="Green", alpha=0.6, label="Ratios", bins=100 - ) - s, loc, scale = lognorm.fit(ratios, loc=0) - pdf = lognorm.pdf(binedges, s, loc, scale) - twin3 = ax[ix, 3].twinx() - twin3.set_ylim(0, 1.1 * np.max(pdf)) - twin3.plot(binedges, pdf, color="k", ls="--", label="Lognormal Fit") - - for a in [*ax[ix, :], twin2, twin3]: - a.set_yticks([]) - -plt.tight_layout() -######################################################################################## -# The form of these distributions is a reflection of the fact that geochemical data -# is at is core a measure of relative quantities of atoms. Quantities of atoms have -# discrete distributions (i.e. you can have precisely 0, 1 or 6.02 x 10^23 atoms, but 1.23 -# atoms is not a sensible state of affairs); if you were to count them in a shiny -# machine, the amount of atoms you might measure over a given period will have a Poisson -# distribution. If you measure two components, the probability density distribution of the -# ratio is well approximated by a lognormal distribution (note this doesn't consider -# inherent covariance): -# -from pyrolite.util.plot.axes import share_axes, subaxes -from pyrolite.util.distributions import lognorm_to_norm, norm_to_lognorm - -# starting from a normal distribution, then creating similar non-normal distributions -mean, sd = 2.5, 1.5 # -logmu, logs = norm_to_lognorm(mean, sd) # parameters for equival -normrv = norm(loc=mean, scale=sd) -lognormrv = lognorm(s=logs, scale=logmu) -poissonrv = poisson(mu=mean) -######################################################################################## -# We can visualise the similarities and differences between these distributions: -# -fig, ax = plt.subplots(2, 3, figsize=(8, 4)) -ax = ax.flat -for a in ax: - a.subax = subaxes(a, side="bottom") - -share_axes(ax[:3], which="x") -share_axes(ax[3:], which="x") -ax[0].set_xlim(-2, 10) -ax[3].set_xscale("log") -ax[3].set_xlim(0.1, 10) - -for a in ax: - a.axvline(0, color="k", lw=0.5, ls="--") - -# xs at which to evaluate the pdfs -x = np.linspace(-5, 15.0, 1001) - -for ix, dist in enumerate([normrv, lognormrv, poissonrv]): - _xs = dist.rvs(size=10000) # random sample - _ys = -0.05 + np.random.randn(10000) / 100 # random offsets for visualisation - for a in [ax[ix], ax[ix + 3]]: - a.annotate( - "mean={:.2f}, var={:.2f}".format(np.mean(_xs), np.var(_xs)), - xy=(0.05, 1.05), - ha="left", - va="bottom", - xycoords=a.transAxes, - ) - a.subax.scatter(_xs, _ys, s=2, color="k", alpha=0.01) - if dist != poissonrv: # cont. distribution - a.plot(x, dist.pdf(x), color="Purple", alpha=0.6, label="pdf") - else: # discrete distribution - a.vlines( - x[x >= 0], - 0, - dist.pmf(x[x >= 0]), - color="Purple", - alpha=0.6, - label="pmf", - ) - -fig.suptitle("Data Distributions: Normal, Lognormal, Poisson", y=1.1) -plt.tight_layout() -######################################################################################## -# Accounting for these inherent features of geochemical data will allow you to -# accurately estimate means and variances, and from this enables the use of -# standardised statistical measures - as long as you're log-transforming your data. -# When performing multivariate analysis, use log-ratio transformations (including the -# additive logratio :func:`~pyrolite.comp.codata.alr`, centred logratio -# :func:`~pyrolite.comp.codata.clr` and isometric logratio -# :func:`~pyrolite.comp.codata.ilr`). In this case, the logratio-mean is implemented for -# you: -# -from pyrolite.comp.codata import logratiomean -import itertools - -fig, ax = plt.subplots(2, 2, figsize=(12, 12), subplot_kw=dict(projection="ternary")) -ax = ax.flat - -for columns, a in zip(itertools.combinations(["A", "B", "C", "D"], 3), ax): - columns = list(columns) - - df.loc[:, columns].pyroplot.scatter( - ax=a, color="k", marker=".", label=df.name, no_ticks=True - ) - - df.mean().loc[columns].pyroplot.scatter( - ax=a, - edgecolors="red", - linewidths=2, - c="none", - s=50, - label="Arithmetic Mean", - no_ticks=True, - ) - - logratiomean(df.loc[:, columns]).pyroplot.scatter( - ax=a, - edgecolors="k", - linewidths=2, - c="none", - s=50, - label="Geometric Mean", - axlabels=True, - no_ticks=True, - ) - a.legend(frameon=False, facecolor=None, loc=(0.8, 0.5)) diff --git a/docs/source/examples/comp/compositional_data.py.md5 b/docs/source/examples/comp/compositional_data.py.md5 deleted file mode 100644 index 2fadfff8..00000000 --- a/docs/source/examples/comp/compositional_data.py.md5 +++ /dev/null @@ -1 +0,0 @@ -5fdc4df2c1e50519bd2342f0717f4345 \ No newline at end of file diff --git a/docs/source/examples/comp/compositional_data.rst b/docs/source/examples/comp/compositional_data.rst deleted file mode 100644 index a3d59176..00000000 --- a/docs/source/examples/comp/compositional_data.rst +++ /dev/null @@ -1,449 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_comp_compositional_data.py: - - -Compositional Data? --------------------- - -pyrolite comes with a few datasets from Aitchison (1984) built in which we can use -as examples: - - - -.. code-block:: default - - import numpy as np - import pandas as pd - import matplotlib.pyplot as plt - from pyrolite.plot import pyroplot - from pyrolite.data.Aitchison import load_kongite - - df = load_kongite() - - - - - - - -For compositional data, everything is relative (thanks to the closure property), so we -tend to use ratios to express differences or changes between things. However, -if we make incorrect assumptions about the nature of our data, we can get some incorrect -answers. Say you want to know the average ratio between A and B: - - - -.. code-block:: default - - A_on_B = df["A"] / df["B"] - A_on_B.mean() # 2.8265837788402983 - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - 2.8265837788402983 - - - -Equally, you could have chosen to calculate the average ratio between B and A - - - -.. code-block:: default - - B_on_A = df["B"] / df["A"] - B_on_A.mean() # 0.4709565704852008 - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - 0.4709565704852008 - - - -You expect these to be invertable, such that A_on_B = 1 / B_on_A; but not so! - - - -.. code-block:: default - - A_on_B.mean() / (1 / B_on_A.mean()) # 1.3311982026717262 - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - 1.3311982026717262 - - - -Similarly, the relative variances are different: - - - -.. code-block:: default - - np.std(A_on_B) / A_on_B.mean() # 0.6295146309597085 - np.std(B_on_A) / B_on_A.mean() # 0.5020948201979953 - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - 0.5020948201979953 - - - -This improves when using logratios in place of simple ratios, prior to exponentiating means - - - -.. code-block:: default - - logA_on_B = (df["A"] / df["B"]).apply(np.log) - logB_on_A = (df["B"] / df["A"]).apply(np.log) - - - - - - - -The logratios are invertible: - - - -.. code-block:: default - - np.exp(logA_on_B.mean()) # 2.4213410747400514 - 1 / np.exp(logB_on_A.mean()) # 2.421341074740052 - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - 2.421341074740052 - - - -The logratios also have the same variance: - - -.. code-block:: default - - (np.std(logA_on_B) / logA_on_B.mean()) ** 2 # 0.36598579018127086 - (np.std(logB_on_A) / logB_on_A.mean()) ** 2 # 0.36598579018127086 - - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - 0.36598579018127086 - - - -These peculiarities result from incorrect assumptions regarding the distribution of the -data: ratios of compositional components are typically *lognormally* distributed, rather -than *normally* distributed, and the compositional components themselves commonly have -a `Poisson distribution `__ . -These distributions contrast significantly with the normal distribution at the core of -most statistical tests. We can compare distributions with similar means and variances -but different forms, and note that the normal distribution has one immediate -failure, in that it has non-zero probability density below 0, and we know that you can't -have negative atoms! - - - -.. code-block:: default - - from scipy.stats import norm, poisson, lognorm - - means = [[10, 10], [10, 20], [20, 100], [1000, 50]] - fig, ax = plt.subplots(len(means), 4, figsize=(11, 8)) - ax[0, 0].set_title("A") - ax[0, 1].set_title("B") - ax[0, 2].set_title("Normal Fit to B/A") - ax[0, 3].set_title("Lognormal Fit to B/A") - ax[-1, 0].set_xlabel("A") - ax[-1, 1].set_xlabel("B") - ax[-1, 2].set_xlabel("B/A") - ax[-1, 3].set_xlabel("B/A") - for ix, (m1, m2) in enumerate(means): - p1, p2 = poisson(mu=m1), poisson(mu=m2) - y1, y2 = p1.rvs(2000), p2.rvs(2000) - ratios = y2[y1 > 0] / y1[y1 > 0] - - y1min, y1max = y1.min(), y1.max() - y2min, y2max = y2.min(), y2.max() - ax[ix, 0].hist( - y1, - color="0.5", - alpha=0.6, - label="A", - bins=np.linspace(y1min - 0.5, y1max + 0.5, (y1max - y1min) + 1), - ) - ax[ix, 1].hist( - y2, - color="0.5", - alpha=0.6, - label="B", - bins=np.linspace(y2min - 0.5, y2max + 0.5, (y2max - y2min) + 1), - ) - - # normal distribution fit - H, binedges, patches = ax[ix, 2].hist( - ratios, color="Purple", alpha=0.6, label="Ratios", bins=100 - ) - loc, scale = norm.fit(ratios, loc=0) - pdf = norm.pdf(binedges, loc, scale) - twin2 = ax[ix, 2].twinx() - twin2.set_ylim(0, 1.1 * np.max(pdf)) - twin2.plot(binedges, pdf, color="k", ls="--", label="Normal Fit") - - # log-normal distribution fit - H, binedges, patches = ax[ix, 3].hist( - ratios, color="Green", alpha=0.6, label="Ratios", bins=100 - ) - s, loc, scale = lognorm.fit(ratios, loc=0) - pdf = lognorm.pdf(binedges, s, loc, scale) - twin3 = ax[ix, 3].twinx() - twin3.set_ylim(0, 1.1 * np.max(pdf)) - twin3.plot(binedges, pdf, color="k", ls="--", label="Lognormal Fit") - - for a in [*ax[ix, :], twin2, twin3]: - a.set_yticks([]) - - plt.tight_layout() - - - -.. image:: /examples/comp/images/sphx_glr_compositional_data_001.png - :class: sphx-glr-single-img - - - - - -The form of these distributions is a reflection of the fact that geochemical data -is at is core a measure of relative quantities of atoms. Quantities of atoms have -discrete distributions (i.e. you can have precisely 0, 1 or 6.02 x 10^23 atoms, but 1.23 -atoms is not a sensible state of affairs); if you were to count them in a shiny -machine, the amount of atoms you might measure over a given period will have a Poisson -distribution. If you measure two components, the probability density distribution of the -ratio is well approximated by a lognormal distribution (note this doesn't consider -inherent covariance): - - - -.. code-block:: default - - from pyrolite.util.plot.axes import share_axes, subaxes - from pyrolite.util.distributions import lognorm_to_norm, norm_to_lognorm - - # starting from a normal distribution, then creating similar non-normal distributions - mean, sd = 2.5, 1.5 # - logmu, logs = norm_to_lognorm(mean, sd) # parameters for equival - normrv = norm(loc=mean, scale=sd) - lognormrv = lognorm(s=logs, scale=logmu) - poissonrv = poisson(mu=mean) - - - - - - - -We can visualise the similarities and differences between these distributions: - - - -.. code-block:: default - - fig, ax = plt.subplots(2, 3, figsize=(8, 4)) - ax = ax.flat - for a in ax: - a.subax = subaxes(a, side="bottom") - - share_axes(ax[:3], which="x") - share_axes(ax[3:], which="x") - ax[0].set_xlim(-2, 10) - ax[3].set_xscale("log") - ax[3].set_xlim(0.1, 10) - - for a in ax: - a.axvline(0, color="k", lw=0.5, ls="--") - - # xs at which to evaluate the pdfs - x = np.linspace(-5, 15.0, 1001) - - for ix, dist in enumerate([normrv, lognormrv, poissonrv]): - _xs = dist.rvs(size=10000) # random sample - _ys = -0.05 + np.random.randn(10000) / 100 # random offsets for visualisation - for a in [ax[ix], ax[ix + 3]]: - a.annotate( - "mean={:.2f}, var={:.2f}".format(np.mean(_xs), np.var(_xs)), - xy=(0.05, 1.05), - ha="left", - va="bottom", - xycoords=a.transAxes, - ) - a.subax.scatter(_xs, _ys, s=2, color="k", alpha=0.01) - if dist != poissonrv: # cont. distribution - a.plot(x, dist.pdf(x), color="Purple", alpha=0.6, label="pdf") - else: # discrete distribution - a.vlines( - x[x >= 0], - 0, - dist.pmf(x[x >= 0]), - color="Purple", - alpha=0.6, - label="pmf", - ) - - fig.suptitle("Data Distributions: Normal, Lognormal, Poisson", y=1.1) - plt.tight_layout() - - - -.. image:: /examples/comp/images/sphx_glr_compositional_data_002.png - :class: sphx-glr-single-img - - - - - -Accounting for these inherent features of geochemical data will allow you to -accurately estimate means and variances, and from this enables the use of -standardised statistical measures - as long as you're log-transforming your data. -When performing multivariate analysis, use log-ratio transformations (including the -additive logratio :func:`~pyrolite.comp.codata.alr`, centred logratio -:func:`~pyrolite.comp.codata.clr` and isometric logratio -:func:`~pyrolite.comp.codata.ilr`). In this case, the logratio-mean is implemented for -you: - - - -.. code-block:: default - - from pyrolite.comp.codata import logratiomean - import itertools - - fig, ax = plt.subplots(2, 2, figsize=(12, 12), subplot_kw=dict(projection="ternary")) - ax = ax.flat - - for columns, a in zip(itertools.combinations(["A", "B", "C", "D"], 3), ax): - columns = list(columns) - - df.loc[:, columns].pyroplot.scatter( - ax=a, color="k", marker=".", label=df.name, no_ticks=True - ) - - df.mean().loc[columns].pyroplot.scatter( - ax=a, - edgecolors="red", - linewidths=2, - c="none", - s=50, - label="Arithmetic Mean", - no_ticks=True, - ) - - logratiomean(df.loc[:, columns]).pyroplot.scatter( - ax=a, - edgecolors="k", - linewidths=2, - c="none", - s=50, - label="Geometric Mean", - axlabels=True, - no_ticks=True, - ) - a.legend(frameon=False, facecolor=None, loc=(0.8, 0.5)) - - - -.. image:: /examples/comp/images/sphx_glr_compositional_data_003.png - :class: sphx-glr-single-img - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 8.415 seconds) - - -.. _sphx_glr_download_examples_comp_compositional_data.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/comp/compositional_data.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: compositional_data.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: compositional_data.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/comp/compositional_data_codeobj.pickle b/docs/source/examples/comp/compositional_data_codeobj.pickle deleted file mode 100644 index ac1bbf01..00000000 Binary files a/docs/source/examples/comp/compositional_data_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/comp/images/sphx_glr_compositional_data_001.png b/docs/source/examples/comp/images/sphx_glr_compositional_data_001.png deleted file mode 100644 index f85b8ed0..00000000 Binary files a/docs/source/examples/comp/images/sphx_glr_compositional_data_001.png and /dev/null differ diff --git a/docs/source/examples/comp/images/sphx_glr_compositional_data_002.png b/docs/source/examples/comp/images/sphx_glr_compositional_data_002.png deleted file mode 100644 index e4fa3284..00000000 Binary files a/docs/source/examples/comp/images/sphx_glr_compositional_data_002.png and /dev/null differ diff --git a/docs/source/examples/comp/images/sphx_glr_compositional_data_003.png b/docs/source/examples/comp/images/sphx_glr_compositional_data_003.png deleted file mode 100644 index 5840345d..00000000 Binary files a/docs/source/examples/comp/images/sphx_glr_compositional_data_003.png and /dev/null differ diff --git a/docs/source/examples/comp/images/sphx_glr_logratiomeans_001.png b/docs/source/examples/comp/images/sphx_glr_logratiomeans_001.png deleted file mode 100644 index 04de2c71..00000000 Binary files a/docs/source/examples/comp/images/sphx_glr_logratiomeans_001.png and /dev/null differ diff --git a/docs/source/examples/comp/images/sphx_glr_logratiomeans_002.png b/docs/source/examples/comp/images/sphx_glr_logratiomeans_002.png deleted file mode 100644 index 3d2d8210..00000000 Binary files a/docs/source/examples/comp/images/sphx_glr_logratiomeans_002.png and /dev/null differ diff --git a/docs/source/examples/comp/images/sphx_glr_logratiomeans_003.png b/docs/source/examples/comp/images/sphx_glr_logratiomeans_003.png deleted file mode 100644 index 6782c030..00000000 Binary files a/docs/source/examples/comp/images/sphx_glr_logratiomeans_003.png and /dev/null differ diff --git a/docs/source/examples/comp/images/thumb/sphx_glr_compositional_data_thumb.png b/docs/source/examples/comp/images/thumb/sphx_glr_compositional_data_thumb.png deleted file mode 100644 index 71d8b75b..00000000 Binary files a/docs/source/examples/comp/images/thumb/sphx_glr_compositional_data_thumb.png and /dev/null differ diff --git a/docs/source/examples/comp/images/thumb/sphx_glr_logratiomeans_thumb.png b/docs/source/examples/comp/images/thumb/sphx_glr_logratiomeans_thumb.png deleted file mode 100644 index 1be01a76..00000000 Binary files a/docs/source/examples/comp/images/thumb/sphx_glr_logratiomeans_thumb.png and /dev/null differ diff --git a/docs/source/examples/comp/images/thumb/sphx_glr_logtransforms_thumb.png b/docs/source/examples/comp/images/thumb/sphx_glr_logtransforms_thumb.png deleted file mode 100644 index cee34ef4..00000000 Binary files a/docs/source/examples/comp/images/thumb/sphx_glr_logtransforms_thumb.png and /dev/null differ diff --git a/docs/source/examples/comp/logratiomeans.ipynb b/docs/source/examples/comp/logratiomeans.ipynb deleted file mode 100644 index c5240762..00000000 --- a/docs/source/examples/comp/logratiomeans.ipynb +++ /dev/null @@ -1,137 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nLog Ratio Means\n-----------------\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\nimport pandas as pd\nimport pyrolite.comp\nfrom pyrolite.comp.codata import ILR, inverse_ILR, close\nfrom pyrolite.util.synthetic import random_cov_matrix\nimport matplotlib.pyplot as plt\nfrom pyrolite.plot import pyroplot\n\n\nnp.random.seed(82)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "def random_compositional_trend(m1, m2, c1, c2, resolution=20, size=1000):\n \"\"\"\n Generate a compositional trend between two compositions with independent\n variances.\n \"\"\"\n # generate means intermediate between m1 and m2\n mv = np.vstack([ILR(close(m1)).reshape(1, -1), ILR(close(m2)).reshape(1, -1)])\n ms = np.apply_along_axis(lambda x: np.linspace(*x, resolution), 0, mv)\n # generate covariance matricies intermediate between c1 and c2\n cv = np.vstack([c1.reshape(1, -1), c2.reshape(1, -1)])\n cs = np.apply_along_axis(lambda x: np.linspace(*x, resolution), 0, cv)\n cs = cs.reshape(cs.shape[0], *c1.shape)\n # generate samples from each\n samples = np.vstack(\n [\n np.random.multivariate_normal(m.flatten(), cs[ix], size=size // resolution)\n for ix, m in enumerate(ms)\n ]\n )\n # combine together.\n return inverse_ILR(samples)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First we create an array of compositions which represent a trend.\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "m1, m2 = np.array([[0.3, 0.1, 2.1]]), np.array([[0.5, 2.5, 0.05]])\nc1, c2 = (\n random_cov_matrix(2, sigmas=[0.15, 0.05]),\n random_cov_matrix(2, sigmas=[0.05, 0.2]),\n)\n\ntrend = pd.DataFrame(\n random_compositional_trend(m1, m2, c1, c2, resolution=100, size=5000),\n columns=[\"A\", \"B\", \"C\"],\n)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can visualise this compositional trend with a density plot.\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = trend.pyroplot.density(mode=\"density\", bins=100)\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First we can see where the geometric mean would fall:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "geomean = trend.mean(axis=0).to_frame().T\nax = geomean.pyroplot.scatter(ax=ax, marker=\"o\", color=\"r\", zorder=2, label=\"GeoMean\")\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, we can also see where the logratio mean would fall:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ILRmean = trend.pyrocomp.logratiomean(transform='ILR')\nax = ILRmean.pyroplot.scatter(ax=ax, marker=\"D\", color=\"k\", label=\"LogMean\")\nplt.show()" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/comp/logratiomeans.py b/docs/source/examples/comp/logratiomeans.py deleted file mode 100644 index 36d915ed..00000000 --- a/docs/source/examples/comp/logratiomeans.py +++ /dev/null @@ -1,68 +0,0 @@ -""" -Log Ratio Means ------------------ -""" -import numpy as np -import pandas as pd -import pyrolite.comp -from pyrolite.comp.codata import ILR, inverse_ILR, close -from pyrolite.util.synthetic import random_cov_matrix -import matplotlib.pyplot as plt -from pyrolite.plot import pyroplot - -# sphinx_gallery_thumbnail_number = 3 - -np.random.seed(82) -######################################################################################## -def random_compositional_trend(m1, m2, c1, c2, resolution=20, size=1000): - """ - Generate a compositional trend between two compositions with independent - variances. - """ - # generate means intermediate between m1 and m2 - mv = np.vstack([ILR(close(m1)).reshape(1, -1), ILR(close(m2)).reshape(1, -1)]) - ms = np.apply_along_axis(lambda x: np.linspace(*x, resolution), 0, mv) - # generate covariance matricies intermediate between c1 and c2 - cv = np.vstack([c1.reshape(1, -1), c2.reshape(1, -1)]) - cs = np.apply_along_axis(lambda x: np.linspace(*x, resolution), 0, cv) - cs = cs.reshape(cs.shape[0], *c1.shape) - # generate samples from each - samples = np.vstack( - [ - np.random.multivariate_normal(m.flatten(), cs[ix], size=size // resolution) - for ix, m in enumerate(ms) - ] - ) - # combine together. - return inverse_ILR(samples) -######################################################################################## -# First we create an array of compositions which represent a trend. -# -m1, m2 = np.array([[0.3, 0.1, 2.1]]), np.array([[0.5, 2.5, 0.05]]) -c1, c2 = ( - random_cov_matrix(2, sigmas=[0.15, 0.05]), - random_cov_matrix(2, sigmas=[0.05, 0.2]), -) - -trend = pd.DataFrame( - random_compositional_trend(m1, m2, c1, c2, resolution=100, size=5000), - columns=["A", "B", "C"], -) -######################################################################################## -# We can visualise this compositional trend with a density plot. -# -ax = trend.pyroplot.density(mode="density", bins=100) -plt.show() -######################################################################################## -# First we can see where the geometric mean would fall: -# -geomean = trend.mean(axis=0).to_frame().T -ax = geomean.pyroplot.scatter(ax=ax, marker="o", color="r", zorder=2, label="GeoMean") -plt.show() -######################################################################################## -# Finally, we can also see where the logratio mean would fall: -# - -ILRmean = trend.pyrocomp.logratiomean(transform='ILR') -ax = ILRmean.pyroplot.scatter(ax=ax, marker="D", color="k", label="LogMean") -plt.show() diff --git a/docs/source/examples/comp/logratiomeans.py.md5 b/docs/source/examples/comp/logratiomeans.py.md5 deleted file mode 100644 index eaebfa1c..00000000 --- a/docs/source/examples/comp/logratiomeans.py.md5 +++ /dev/null @@ -1 +0,0 @@ -8223de0d20edbff7691560f5abe09cb6 \ No newline at end of file diff --git a/docs/source/examples/comp/logratiomeans.rst b/docs/source/examples/comp/logratiomeans.rst deleted file mode 100644 index 1f92ef1c..00000000 --- a/docs/source/examples/comp/logratiomeans.rst +++ /dev/null @@ -1,177 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_comp_logratiomeans.py: - - -Log Ratio Means ------------------ - - -.. code-block:: default - - import numpy as np - import pandas as pd - import pyrolite.comp - from pyrolite.comp.codata import ILR, inverse_ILR, close - from pyrolite.util.synthetic import random_cov_matrix - import matplotlib.pyplot as plt - from pyrolite.plot import pyroplot - - - np.random.seed(82) - - - - - - - - -.. code-block:: default - - def random_compositional_trend(m1, m2, c1, c2, resolution=20, size=1000): - """ - Generate a compositional trend between two compositions with independent - variances. - """ - # generate means intermediate between m1 and m2 - mv = np.vstack([ILR(close(m1)).reshape(1, -1), ILR(close(m2)).reshape(1, -1)]) - ms = np.apply_along_axis(lambda x: np.linspace(*x, resolution), 0, mv) - # generate covariance matricies intermediate between c1 and c2 - cv = np.vstack([c1.reshape(1, -1), c2.reshape(1, -1)]) - cs = np.apply_along_axis(lambda x: np.linspace(*x, resolution), 0, cv) - cs = cs.reshape(cs.shape[0], *c1.shape) - # generate samples from each - samples = np.vstack( - [ - np.random.multivariate_normal(m.flatten(), cs[ix], size=size // resolution) - for ix, m in enumerate(ms) - ] - ) - # combine together. - return inverse_ILR(samples) - - - - - - - -First we create an array of compositions which represent a trend. - - - -.. code-block:: default - - m1, m2 = np.array([[0.3, 0.1, 2.1]]), np.array([[0.5, 2.5, 0.05]]) - c1, c2 = ( - random_cov_matrix(2, sigmas=[0.15, 0.05]), - random_cov_matrix(2, sigmas=[0.05, 0.2]), - ) - - trend = pd.DataFrame( - random_compositional_trend(m1, m2, c1, c2, resolution=100, size=5000), - columns=["A", "B", "C"], - ) - - - - - - - -We can visualise this compositional trend with a density plot. - - - -.. code-block:: default - - ax = trend.pyroplot.density(mode="density", bins=100) - plt.show() - - - -.. image:: /examples/comp/images/sphx_glr_logratiomeans_001.png - :class: sphx-glr-single-img - - - - - -First we can see where the geometric mean would fall: - - - -.. code-block:: default - - geomean = trend.mean(axis=0).to_frame().T - ax = geomean.pyroplot.scatter(ax=ax, marker="o", color="r", zorder=2, label="GeoMean") - plt.show() - - - -.. image:: /examples/comp/images/sphx_glr_logratiomeans_002.png - :class: sphx-glr-single-img - - - - - -Finally, we can also see where the logratio mean would fall: - - - -.. code-block:: default - - - ILRmean = trend.pyrocomp.logratiomean(transform='ILR') - ax = ILRmean.pyroplot.scatter(ax=ax, marker="D", color="k", label="LogMean") - plt.show() - - - -.. image:: /examples/comp/images/sphx_glr_logratiomeans_003.png - :class: sphx-glr-single-img - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 3.873 seconds) - - -.. _sphx_glr_download_examples_comp_logratiomeans.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/comp/logratiomeans.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: logratiomeans.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: logratiomeans.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/comp/logratiomeans_codeobj.pickle b/docs/source/examples/comp/logratiomeans_codeobj.pickle deleted file mode 100644 index 604c0119..00000000 Binary files a/docs/source/examples/comp/logratiomeans_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/comp/logtransforms.ipynb b/docs/source/examples/comp/logtransforms.ipynb deleted file mode 100644 index 58df5bdc..00000000 --- a/docs/source/examples/comp/logtransforms.ipynb +++ /dev/null @@ -1,194 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nLog-transforms\n----------------\n\npyrolite includes a few functions for dealing with compositional data, at the heart of\nwhich are i) closure (i.e. everything sums to 100%) and ii) log-transforms to deal with\nthe compositional space. The commonly used log-transformations include the\nAdditive Log-Ratio (:func:`~pyrolite.comp.pyrocomp.ALR`), Centred Log-Ratio\n(:func:`~pyrolite.comp.pyrocomp.CLR`), and Isometric Log-Ratio\n(:func:`~pyrolite.comp.pyrocomp.ILR`) [#ref_1]_ [#ref_2]_.\n\nThis example will show you how to access and use some of these functions in pyrolite.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First let's create some example data:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.synthetic import test_df, random_cov_matrix\n\ndf = test_df(\n index_length=100,\n cov=random_cov_matrix(sigmas=[0.1, 0.05, 0.3, 0.6], dim=4, seed=32),\n seed=32,\n)\ndf.describe()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let's have a look at some of the log-transforms, which can be accessed directly from\nyour dataframes (via :class:`pyrolite.comp.pyrocomp`), after you've imported\n:mod:`pyrolite.comp`. Note that the transformations will return *new* dataframes,\nrather than modify their inputs. For example:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.comp\n\nlr_df = df.pyrocomp.CLR() # using a centred log-ratio transformation" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The transformations are implemented such that the column names generally make it\nevident which transformations have been applied:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "lr_df.columns" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To invert these transformations, you can call the respective inverse transform:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "back_transformed = lr_df.pyrocomp.inverse_CLR()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Given we haven't done anything to our dataframe in the meantime, we should be back\nwhere we started, and our values should all be equal within numerical precision.\nTo verify this, we can use :func:`numpy.allclose`:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n\nnp.allclose(back_transformed, df)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In addition to easy access to the transforms, there's also a convenience function\nfor taking a log-transformed mean (log-transforming, taking a mean, and inverse log\ntransforming; :func:`~pyrolite.comp.codata.pyrocomp.logratiomean`):\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyrocomp.logratiomean()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "While this function defaults to using :func:`~pyrolite.comp.codata.clr`,\nyou can specify other log-transforms to use:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyrocomp.logratiomean(transform=\"CLR\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Notably, however, the logratio means should all give you the same result:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "np.allclose(\n df.pyrocomp.logratiomean(transform=\"CLR\"),\n df.pyrocomp.logratiomean(transform=\"ALR\"),\n) & np.allclose(\n df.pyrocomp.logratiomean(transform=\"CLR\"),\n df.pyrocomp.logratiomean(transform=\"ILR\"),\n)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ".. [#ref_1] Aitchison, J., 1984. The statistical analysis of geochemical compositions.\n Journal of the International Association for Mathematical Geology 16, 531\u2013564.\n doi: `10.1007/BF01029316 `__\n\n.. [#ref_2] Egozcue, J.J., Pawlowsky-Glahn, V., Mateu-Figueras, G.,\n Barcel\u00f3-Vidal, C., 2003.\n Isometric Logratio Transformations for Compositional Data Analysis.\n Mathematical Geology 35, 279\u2013300.\n doi: `10.1023/A:1023818214614 `__\n\n.. seealso::\n\n Examples:\n `Log Ratio Means `__,\n `Compositional Data `__,\n `Ternary Plots <../ternary.html>`__\n\n Tutorials:\n `Ternary Density Plots <../../tutorials/ternary_density.html>`__,\n `Making the Logo <../../tutorials/logo.html>`__\n\n Modules and Functions:\n :mod:`pyrolite.comp.codata`,\n :func:`~pyrolite.comp.codata.boxcox`,\n :func:`~pyrolite.comp.pyrocomp.renormalise`\n\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/comp/logtransforms.py b/docs/source/examples/comp/logtransforms.py deleted file mode 100644 index 56e0ea1b..00000000 --- a/docs/source/examples/comp/logtransforms.py +++ /dev/null @@ -1,100 +0,0 @@ -""" -Log-transforms ----------------- - -pyrolite includes a few functions for dealing with compositional data, at the heart of -which are i) closure (i.e. everything sums to 100%) and ii) log-transforms to deal with -the compositional space. The commonly used log-transformations include the -Additive Log-Ratio (:func:`~pyrolite.comp.pyrocomp.ALR`), Centred Log-Ratio -(:func:`~pyrolite.comp.pyrocomp.CLR`), and Isometric Log-Ratio -(:func:`~pyrolite.comp.pyrocomp.ILR`) [#ref_1]_ [#ref_2]_. - -This example will show you how to access and use some of these functions in pyrolite. -""" - -######################################################################################## -# First let's create some example data: -# -from pyrolite.util.synthetic import test_df, random_cov_matrix - -df = test_df( - index_length=100, - cov=random_cov_matrix(sigmas=[0.1, 0.05, 0.3, 0.6], dim=4, seed=32), - seed=32, -) -df.describe() -######################################################################################## -# Let's have a look at some of the log-transforms, which can be accessed directly from -# your dataframes (via :class:`pyrolite.comp.pyrocomp`), after you've imported -# :mod:`pyrolite.comp`. Note that the transformations will return *new* dataframes, -# rather than modify their inputs. For example: -# -import pyrolite.comp - -lr_df = df.pyrocomp.CLR() # using a centred log-ratio transformation -######################################################################################## -# The transformations are implemented such that the column names generally make it -# evident which transformations have been applied: -# -lr_df.columns -######################################################################################## -# To invert these transformations, you can call the respective inverse transform: -# -back_transformed = lr_df.pyrocomp.inverse_CLR() -######################################################################################## -# Given we haven't done anything to our dataframe in the meantime, we should be back -# where we started, and our values should all be equal within numerical precision. -# To verify this, we can use :func:`numpy.allclose`: -# -import numpy as np - -np.allclose(back_transformed, df) -######################################################################################## -# In addition to easy access to the transforms, there's also a convenience function -# for taking a log-transformed mean (log-transforming, taking a mean, and inverse log -# transforming; :func:`~pyrolite.comp.codata.pyrocomp.logratiomean`): -# - -df.pyrocomp.logratiomean() -######################################################################################## -# While this function defaults to using :func:`~pyrolite.comp.codata.clr`, -# you can specify other log-transforms to use: -# -df.pyrocomp.logratiomean(transform="CLR") -######################################################################################## -# Notably, however, the logratio means should all give you the same result: -# -np.allclose( - df.pyrocomp.logratiomean(transform="CLR"), - df.pyrocomp.logratiomean(transform="ALR"), -) & np.allclose( - df.pyrocomp.logratiomean(transform="CLR"), - df.pyrocomp.logratiomean(transform="ILR"), -) - -######################################################################################## -# .. [#ref_1] Aitchison, J., 1984. The statistical analysis of geochemical compositions. -# Journal of the International Association for Mathematical Geology 16, 531–564. -# doi: `10.1007/BF01029316 `__ -# -# .. [#ref_2] Egozcue, J.J., Pawlowsky-Glahn, V., Mateu-Figueras, G., -# Barceló-Vidal, C., 2003. -# Isometric Logratio Transformations for Compositional Data Analysis. -# Mathematical Geology 35, 279–300. -# doi: `10.1023/A:1023818214614 `__ -# -# .. seealso:: -# -# Examples: -# `Log Ratio Means `__, -# `Compositional Data `__, -# `Ternary Plots <../ternary.html>`__ -# -# Tutorials: -# `Ternary Density Plots <../../tutorials/ternary_density.html>`__, -# `Making the Logo <../../tutorials/logo.html>`__ -# -# Modules and Functions: -# :mod:`pyrolite.comp.codata`, -# :func:`~pyrolite.comp.codata.boxcox`, -# :func:`~pyrolite.comp.pyrocomp.renormalise` diff --git a/docs/source/examples/comp/logtransforms.py.md5 b/docs/source/examples/comp/logtransforms.py.md5 deleted file mode 100644 index c058ecf9..00000000 --- a/docs/source/examples/comp/logtransforms.py.md5 +++ /dev/null @@ -1 +0,0 @@ -c0e6f769c233c73a0899bffae6797928 \ No newline at end of file diff --git a/docs/source/examples/comp/logtransforms.rst b/docs/source/examples/comp/logtransforms.rst deleted file mode 100644 index d4cb786c..00000000 --- a/docs/source/examples/comp/logtransforms.rst +++ /dev/null @@ -1,369 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_comp_logtransforms.py: - - -Log-transforms ----------------- - -pyrolite includes a few functions for dealing with compositional data, at the heart of -which are i) closure (i.e. everything sums to 100%) and ii) log-transforms to deal with -the compositional space. The commonly used log-transformations include the -Additive Log-Ratio (:func:`~pyrolite.comp.pyrocomp.ALR`), Centred Log-Ratio -(:func:`~pyrolite.comp.pyrocomp.CLR`), and Isometric Log-Ratio -(:func:`~pyrolite.comp.pyrocomp.ILR`) [#ref_1]_ [#ref_2]_. - -This example will show you how to access and use some of these functions in pyrolite. - -First let's create some example data: - - - -.. code-block:: default - - from pyrolite.util.synthetic import test_df, random_cov_matrix - - df = test_df( - index_length=100, - cov=random_cov_matrix(sigmas=[0.1, 0.05, 0.3, 0.6], dim=4, seed=32), - seed=32, - ) - df.describe() - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SiO2CaOMgOFeOTiO2
count100.000000100.000000100.000000100.000000100.000000
mean0.2401690.3893360.0926220.1054410.172431
std0.0373490.0170430.0082040.0278240.057136
min0.1216000.3381560.0723720.0459540.073863
25%0.2158400.3788660.0879370.0842280.131423
50%0.2394990.3903810.0926160.1026840.168427
75%0.2626760.4005740.0986410.1210290.207193
max0.3430310.4300640.1110530.1800040.407645
-
-
-
- -Let's have a look at some of the log-transforms, which can be accessed directly from -your dataframes (via :class:`pyrolite.comp.pyrocomp`), after you've imported -:mod:`pyrolite.comp`. Note that the transformations will return *new* dataframes, -rather than modify their inputs. For example: - - - -.. code-block:: default - - import pyrolite.comp - - lr_df = df.pyrocomp.CLR() # using a centred log-ratio transformation - - - - - - - -The transformations are implemented such that the column names generally make it -evident which transformations have been applied: - - - -.. code-block:: default - - lr_df.columns - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - Index(['CLR(SiO2/g)', 'CLR(CaO/g)', 'CLR(MgO/g)', 'CLR(FeO/g)', 'CLR(TiO2/g)'], dtype='object') - - - -To invert these transformations, you can call the respective inverse transform: - - - -.. code-block:: default - - back_transformed = lr_df.pyrocomp.inverse_CLR() - - - - - - - -Given we haven't done anything to our dataframe in the meantime, we should be back -where we started, and our values should all be equal within numerical precision. -To verify this, we can use :func:`numpy.allclose`: - - - -.. code-block:: default - - import numpy as np - - np.allclose(back_transformed, df) - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - True - - - -In addition to easy access to the transforms, there's also a convenience function -for taking a log-transformed mean (log-transforming, taking a mean, and inverse log -transforming; :func:`~pyrolite.comp.codata.pyrocomp.logratiomean`): - - - -.. code-block:: default - - - df.pyrocomp.logratiomean() - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - SiO2 0.241138 - CaO 0.395404 - MgO 0.093779 - FeO 0.103583 - TiO2 0.166095 - dtype: float64 - - - -While this function defaults to using :func:`~pyrolite.comp.codata.clr`, -you can specify other log-transforms to use: - - - -.. code-block:: default - - df.pyrocomp.logratiomean(transform="CLR") - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - SiO2 0.241138 - CaO 0.395404 - MgO 0.093779 - FeO 0.103583 - TiO2 0.166095 - dtype: float64 - - - -Notably, however, the logratio means should all give you the same result: - - - -.. code-block:: default - - np.allclose( - df.pyrocomp.logratiomean(transform="CLR"), - df.pyrocomp.logratiomean(transform="ALR"), - ) & np.allclose( - df.pyrocomp.logratiomean(transform="CLR"), - df.pyrocomp.logratiomean(transform="ILR"), - ) - - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - True - - - -.. [#ref_1] Aitchison, J., 1984. The statistical analysis of geochemical compositions. - Journal of the International Association for Mathematical Geology 16, 531–564. - doi: `10.1007/BF01029316 `__ - -.. [#ref_2] Egozcue, J.J., Pawlowsky-Glahn, V., Mateu-Figueras, G., - Barceló-Vidal, C., 2003. - Isometric Logratio Transformations for Compositional Data Analysis. - Mathematical Geology 35, 279–300. - doi: `10.1023/A:1023818214614 `__ - -.. seealso:: - - Examples: - `Log Ratio Means `__, - `Compositional Data `__, - `Ternary Plots <../ternary.html>`__ - - Tutorials: - `Ternary Density Plots <../../tutorials/ternary_density.html>`__, - `Making the Logo <../../tutorials/logo.html>`__ - - Modules and Functions: - :mod:`pyrolite.comp.codata`, - :func:`~pyrolite.comp.codata.boxcox`, - :func:`~pyrolite.comp.pyrocomp.renormalise` - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 0.025 seconds) - - -.. _sphx_glr_download_examples_comp_logtransforms.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/comp/logtransforms.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: logtransforms.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: logtransforms.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/comp/logtransforms_codeobj.pickle b/docs/source/examples/comp/logtransforms_codeobj.pickle deleted file mode 100644 index 56dd8457..00000000 Binary files a/docs/source/examples/comp/logtransforms_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/comp/sg_execution_times.rst b/docs/source/examples/comp/sg_execution_times.rst deleted file mode 100644 index ee0fca67..00000000 --- a/docs/source/examples/comp/sg_execution_times.rst +++ /dev/null @@ -1,16 +0,0 @@ - -:orphan: - -.. _sphx_glr_examples_comp_sg_execution_times: - -Computation times -================= -**00:03.898** total execution time for **examples_comp** files: - -+---------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_comp_logratiomeans.py` (``logratiomeans.py``) | 00:03.873 | 0.0 MB | -+---------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_comp_logtransforms.py` (``logtransforms.py``) | 00:00.025 | 0.0 MB | -+---------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_comp_compositional_data.py` (``compositional_data.py``) | 00:00.000 | 0.0 MB | -+---------------------------------------------------------------------------------+-----------+--------+ diff --git a/docs/source/examples/geochem/convert_chemistry.ipynb b/docs/source/examples/geochem/convert_chemistry.ipynb deleted file mode 100644 index 0d113788..00000000 --- a/docs/source/examples/geochem/convert_chemistry.ipynb +++ /dev/null @@ -1,137 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nElement-Oxide Transformation\n============================\n\nOne of pyrolite's strengths is converting mixed elemental and oxide data to a new\nform. The simplest way to perform this is by using the\n:func:`~pyrolite.geochem.transform.convert_chemistry` function. Note that by default\npyrolite assumes that data are in the same units.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.geochem\nimport pandas as pd\n\npd.set_option(\"precision\", 3) # smaller outputs" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here we create some synthetic data to work with, which has some variables in Wt% and\nsome in ppm. Notably some elements are present in more than one column (Ca, Na):\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.synthetic import test_df\n\ndf = test_df(cols=[\"MgO\", \"SiO2\", \"FeO\", \"CaO\", \"Na2O\", \"Te\", \"K\", \"Na\"]) * 100\ndf.pyrochem.elements *= 100 # elements in ppm" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.head(2)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As the units are heterogeneous, we'll need to convert the data frame to a single set of\nunits (here we use Wt%):\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyrochem.elements = df.pyrochem.elements.pyrochem.scale('ppm', 'wt%') # ppm to wt%" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can transform this chemical data to a new set of compositional variables.\nHere we i) convert CaO to Ca, ii) aggregate Na2O and Na to Na and iii) calculate\nmass ratios for Na/Te and MgO/SiO2.\nNote that you can also use this function to calculate mass ratios:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyrochem.convert_chemistry(\n to=[\"MgO\", \"SiO2\", \"FeO\", \"Ca\", \"Te\", \"Na\", \"Na/Te\", \"MgO/SiO2\"]\n).head(2)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You can also specify molar ratios for iron redox, which will result in multiple iron\nspecies within the single dataframe:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyrochem.convert_chemistry(to=[{\"FeO\": 0.9, \"Fe2O3\": 0.1}]).head(2)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/geochem/convert_chemistry.py b/docs/source/examples/geochem/convert_chemistry.py deleted file mode 100644 index 60cd8b48..00000000 --- a/docs/source/examples/geochem/convert_chemistry.py +++ /dev/null @@ -1,42 +0,0 @@ -""" -Element-Oxide Transformation -============================ - -One of pyrolite's strengths is converting mixed elemental and oxide data to a new -form. The simplest way to perform this is by using the -:func:`~pyrolite.geochem.transform.convert_chemistry` function. Note that by default -pyrolite assumes that data are in the same units. -""" -import pyrolite.geochem -import pandas as pd - -pd.set_option("precision", 3) # smaller outputs -######################################################################################## -# Here we create some synthetic data to work with, which has some variables in Wt% and -# some in ppm. Notably some elements are present in more than one column (Ca, Na): -# -from pyrolite.util.synthetic import test_df - -df = test_df(cols=["MgO", "SiO2", "FeO", "CaO", "Na2O", "Te", "K", "Na"]) * 100 -df.pyrochem.elements *= 100 # elements in ppm -######################################################################################## -df.head(2) -######################################################################################## -# As the units are heterogeneous, we'll need to convert the data frame to a single set of -# units (here we use Wt%): -# -df.pyrochem.elements = df.pyrochem.elements.pyrochem.scale('ppm', 'wt%') # ppm to wt% -######################################################################################## -# We can transform this chemical data to a new set of compositional variables. -# Here we i) convert CaO to Ca, ii) aggregate Na2O and Na to Na and iii) calculate -# mass ratios for Na/Te and MgO/SiO2. -# Note that you can also use this function to calculate mass ratios: -# -df.pyrochem.convert_chemistry( - to=["MgO", "SiO2", "FeO", "Ca", "Te", "Na", "Na/Te", "MgO/SiO2"] -).head(2) -######################################################################################## -# You can also specify molar ratios for iron redox, which will result in multiple iron -# species within the single dataframe: -# -df.pyrochem.convert_chemistry(to=[{"FeO": 0.9, "Fe2O3": 0.1}]).head(2) diff --git a/docs/source/examples/geochem/convert_chemistry.py.md5 b/docs/source/examples/geochem/convert_chemistry.py.md5 deleted file mode 100644 index a3ed1bb3..00000000 --- a/docs/source/examples/geochem/convert_chemistry.py.md5 +++ /dev/null @@ -1 +0,0 @@ -5d867c24d3885de674c072b9d5fadf08 \ No newline at end of file diff --git a/docs/source/examples/geochem/convert_chemistry.rst b/docs/source/examples/geochem/convert_chemistry.rst deleted file mode 100644 index 54b713b3..00000000 --- a/docs/source/examples/geochem/convert_chemistry.rst +++ /dev/null @@ -1,302 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_geochem_convert_chemistry.py: - - -Element-Oxide Transformation -============================ - -One of pyrolite's strengths is converting mixed elemental and oxide data to a new -form. The simplest way to perform this is by using the -:func:`~pyrolite.geochem.transform.convert_chemistry` function. Note that by default -pyrolite assumes that data are in the same units. - - -.. code-block:: default - - import pyrolite.geochem - import pandas as pd - - pd.set_option("precision", 3) # smaller outputs - - - - - - - -Here we create some synthetic data to work with, which has some variables in Wt% and -some in ppm. Notably some elements are present in more than one column (Ca, Na): - - - -.. code-block:: default - - from pyrolite.util.synthetic import test_df - - df = test_df(cols=["MgO", "SiO2", "FeO", "CaO", "Na2O", "Te", "K", "Na"]) * 100 - df.pyrochem.elements *= 100 # elements in ppm - - - - - - - - -.. code-block:: default - - df.head(2) - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MgOSiO2FeOCaONa2OTeKNa
03.9025.0446.06045.1562.777444.7782275.896985.441
14.2945.0766.22544.3702.845417.6002240.4561060.880
-
-
-
- -As the units are heterogeneous, we'll need to convert the data frame to a single set of -units (here we use Wt%): - - - -.. code-block:: default - - df.pyrochem.elements = df.pyrochem.elements.pyrochem.scale('ppm', 'wt%') # ppm to wt% - - - - - - - -We can transform this chemical data to a new set of compositional variables. -Here we i) convert CaO to Ca, ii) aggregate Na2O and Na to Na and iii) calculate -mass ratios for Na/Te and MgO/SiO2. -Note that you can also use this function to calculate mass ratios: - - - -.. code-block:: default - - df.pyrochem.convert_chemistry( - to=["MgO", "SiO2", "FeO", "Ca", "Te", "Na", "Na/Te", "MgO/SiO2"] - ).head(2) - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MgOSiO2FeOCaTeNaNa/TeMgO/SiO2
03.9025.0446.06032.2730.0442.15948.5380.774
14.2945.0766.22531.7110.0422.21753.0860.846
-
-
-
- -You can also specify molar ratios for iron redox, which will result in multiple iron -species within the single dataframe: - - - -.. code-block:: default - - df.pyrochem.convert_chemistry(to=[{"FeO": 0.9, "Fe2O3": 0.1}]).head(2) - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - -
FeOFe2O3
05.4540.673
15.6030.692
-
-
-
- - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 0.259 seconds) - - -.. _sphx_glr_download_examples_geochem_convert_chemistry.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/geochem/convert_chemistry.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: convert_chemistry.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: convert_chemistry.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/geochem/convert_chemistry_codeobj.pickle b/docs/source/examples/geochem/convert_chemistry_codeobj.pickle deleted file mode 100644 index ecd45c0c..00000000 Binary files a/docs/source/examples/geochem/convert_chemistry_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/geochem/images/sphx_glr_ionic_radii_001.png b/docs/source/examples/geochem/images/sphx_glr_ionic_radii_001.png deleted file mode 100644 index d5efd725..00000000 Binary files a/docs/source/examples/geochem/images/sphx_glr_ionic_radii_001.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/sphx_glr_lambdas_001.png b/docs/source/examples/geochem/images/sphx_glr_lambdas_001.png deleted file mode 100644 index fc88ee4a..00000000 Binary files a/docs/source/examples/geochem/images/sphx_glr_lambdas_001.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/sphx_glr_lambdas_002.png b/docs/source/examples/geochem/images/sphx_glr_lambdas_002.png deleted file mode 100644 index 52a099f3..00000000 Binary files a/docs/source/examples/geochem/images/sphx_glr_lambdas_002.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/sphx_glr_lambdas_003.png b/docs/source/examples/geochem/images/sphx_glr_lambdas_003.png deleted file mode 100644 index 69e2c11e..00000000 Binary files a/docs/source/examples/geochem/images/sphx_glr_lambdas_003.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/sphx_glr_mineral_lattice_001.png b/docs/source/examples/geochem/images/sphx_glr_mineral_lattice_001.png deleted file mode 100644 index bd306f31..00000000 Binary files a/docs/source/examples/geochem/images/sphx_glr_mineral_lattice_001.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/sphx_glr_mineral_lattice_002.png b/docs/source/examples/geochem/images/sphx_glr_mineral_lattice_002.png deleted file mode 100644 index 548b4e2e..00000000 Binary files a/docs/source/examples/geochem/images/sphx_glr_mineral_lattice_002.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/sphx_glr_mineral_lattice_003.png b/docs/source/examples/geochem/images/sphx_glr_mineral_lattice_003.png deleted file mode 100644 index 8e0b5d0c..00000000 Binary files a/docs/source/examples/geochem/images/sphx_glr_mineral_lattice_003.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/sphx_glr_normalization_001.png b/docs/source/examples/geochem/images/sphx_glr_normalization_001.png deleted file mode 100644 index 7df316a0..00000000 Binary files a/docs/source/examples/geochem/images/sphx_glr_normalization_001.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/thumb/sphx_glr_convert_chemistry_thumb.png b/docs/source/examples/geochem/images/thumb/sphx_glr_convert_chemistry_thumb.png deleted file mode 100644 index cee34ef4..00000000 Binary files a/docs/source/examples/geochem/images/thumb/sphx_glr_convert_chemistry_thumb.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/thumb/sphx_glr_indexes_selectors_thumb.png b/docs/source/examples/geochem/images/thumb/sphx_glr_indexes_selectors_thumb.png deleted file mode 100644 index cee34ef4..00000000 Binary files a/docs/source/examples/geochem/images/thumb/sphx_glr_indexes_selectors_thumb.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/thumb/sphx_glr_ionic_radii_thumb.png b/docs/source/examples/geochem/images/thumb/sphx_glr_ionic_radii_thumb.png deleted file mode 100644 index 7d1d9b32..00000000 Binary files a/docs/source/examples/geochem/images/thumb/sphx_glr_ionic_radii_thumb.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/thumb/sphx_glr_lambdas_thumb.png b/docs/source/examples/geochem/images/thumb/sphx_glr_lambdas_thumb.png deleted file mode 100644 index 10d0f7fd..00000000 Binary files a/docs/source/examples/geochem/images/thumb/sphx_glr_lambdas_thumb.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/thumb/sphx_glr_mineral_endmembers_thumb.png b/docs/source/examples/geochem/images/thumb/sphx_glr_mineral_endmembers_thumb.png deleted file mode 100644 index cee34ef4..00000000 Binary files a/docs/source/examples/geochem/images/thumb/sphx_glr_mineral_endmembers_thumb.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/thumb/sphx_glr_mineral_lattice_thumb.png b/docs/source/examples/geochem/images/thumb/sphx_glr_mineral_lattice_thumb.png deleted file mode 100644 index d7d621fb..00000000 Binary files a/docs/source/examples/geochem/images/thumb/sphx_glr_mineral_lattice_thumb.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/thumb/sphx_glr_mineral_mindb_thumb.png b/docs/source/examples/geochem/images/thumb/sphx_glr_mineral_mindb_thumb.png deleted file mode 100644 index cee34ef4..00000000 Binary files a/docs/source/examples/geochem/images/thumb/sphx_glr_mineral_mindb_thumb.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/thumb/sphx_glr_normalization_thumb.png b/docs/source/examples/geochem/images/thumb/sphx_glr_normalization_thumb.png deleted file mode 100644 index 23d4d288..00000000 Binary files a/docs/source/examples/geochem/images/thumb/sphx_glr_normalization_thumb.png and /dev/null differ diff --git a/docs/source/examples/geochem/images/thumb/sphx_glr_scaling_thumb.png b/docs/source/examples/geochem/images/thumb/sphx_glr_scaling_thumb.png deleted file mode 100644 index cee34ef4..00000000 Binary files a/docs/source/examples/geochem/images/thumb/sphx_glr_scaling_thumb.png and /dev/null differ diff --git a/docs/source/examples/geochem/indexes_selectors.ipynb b/docs/source/examples/geochem/indexes_selectors.ipynb deleted file mode 100644 index 4394a675..00000000 --- a/docs/source/examples/geochem/indexes_selectors.ipynb +++ /dev/null @@ -1,218 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nGeochemical Indexes and Selectors\n==================================\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.geochem\nimport pandas as pd\n\npd.set_option(\"precision\", 3) # smaller outputs" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.synthetic import test_df\n\ndf = test_df(cols=[\"CaO\", \"MgO\", \"SiO2\", \"FeO\", \"Mn\", \"Ti\", \"La\", \"Lu\", \"Mg/Fe\"])" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.head(2).pyrochem.oxides" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.head(2).pyrochem.elements" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.head(2).pyrochem.REE" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.head(2).pyrochem.compositional" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyrochem.list_oxides" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyrochem.list_elements" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyrochem.list_REE" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyrochem.list_compositional" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "All elements (up to U):\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.geochem.ind import common_elements, common_oxides, REE\n\ncommon_elements() # string return" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "All elements, returned as a list of `~periodictable.core.Formula`:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "common_elements(output=\"formula\") # periodictable.core.Formula return" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Oxides for elements with positive charges (up to U):\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "common_oxides()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "REE()" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/geochem/indexes_selectors.py b/docs/source/examples/geochem/indexes_selectors.py deleted file mode 100644 index 9e74a1ed..00000000 --- a/docs/source/examples/geochem/indexes_selectors.py +++ /dev/null @@ -1,65 +0,0 @@ -""" -Geochemical Indexes and Selectors -================================== - -""" -import pyrolite.geochem -import pandas as pd - -pd.set_option("precision", 3) # smaller outputs -######################################################################################## -from pyrolite.util.synthetic import test_df - -df = test_df(cols=["CaO", "MgO", "SiO2", "FeO", "Mn", "Ti", "La", "Lu", "Mg/Fe"]) -######################################################################################## - -df.head(2).pyrochem.oxides - -######################################################################################## - -df.head(2).pyrochem.elements - -######################################################################################## - -df.head(2).pyrochem.REE - -######################################################################################## - -df.head(2).pyrochem.compositional - -######################################################################################## - -df.pyrochem.list_oxides - -######################################################################################## - -df.pyrochem.list_elements - -######################################################################################## - -df.pyrochem.list_REE - -######################################################################################## - -df.pyrochem.list_compositional - -######################################################################################## -# All elements (up to U): -# -from pyrolite.geochem.ind import common_elements, common_oxides, REE - -common_elements() # string return - -######################################################################################## -# All elements, returned as a list of `~periodictable.core.Formula`: -# -common_elements(output="formula") # periodictable.core.Formula return - -######################################################################################## -# Oxides for elements with positive charges (up to U): -# -common_oxides() - -######################################################################################## - -REE() diff --git a/docs/source/examples/geochem/indexes_selectors.py.md5 b/docs/source/examples/geochem/indexes_selectors.py.md5 deleted file mode 100644 index 16489f7b..00000000 --- a/docs/source/examples/geochem/indexes_selectors.py.md5 +++ /dev/null @@ -1 +0,0 @@ -85e05af7aa2fc5d760ceabf4230593ac \ No newline at end of file diff --git a/docs/source/examples/geochem/indexes_selectors.rst b/docs/source/examples/geochem/indexes_selectors.rst deleted file mode 100644 index a5027946..00000000 --- a/docs/source/examples/geochem/indexes_selectors.rst +++ /dev/null @@ -1,494 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_geochem_indexes_selectors.py: - - -Geochemical Indexes and Selectors -================================== - - -.. code-block:: default - - import pyrolite.geochem - import pandas as pd - - pd.set_option("precision", 3) # smaller outputs - - - - - - - - -.. code-block:: default - - from pyrolite.util.synthetic import test_df - - df = test_df(cols=["CaO", "MgO", "SiO2", "FeO", "Mn", "Ti", "La", "Lu", "Mg/Fe"]) - - - - - - - - -.. code-block:: default - - - df.head(2).pyrochem.oxides - - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaOMgOSiO2FeO
00.0060.1430.0880.141
10.0060.1550.1140.158
-
-
-
- - -.. code-block:: default - - - df.head(2).pyrochem.elements - - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
MnTiLaLu
00.0300.0260.0480.091
10.0250.0270.0490.081
-
-
-
- - -.. code-block:: default - - - df.head(2).pyrochem.REE - - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - -
LaLu
00.0480.091
10.0490.081
-
-
-
- - -.. code-block:: default - - - df.head(2).pyrochem.compositional - - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaOMgOSiO2FeOMnTiLaLu
00.0060.1430.0880.1410.0300.0260.0480.091
10.0060.1550.1140.1580.0250.0270.0490.081
-
-
-
- - -.. code-block:: default - - - df.pyrochem.list_oxides - - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['CaO', 'MgO', 'SiO2', 'FeO'] - - - - -.. code-block:: default - - - df.pyrochem.list_elements - - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['Mn', 'Ti', 'La', 'Lu'] - - - - -.. code-block:: default - - - df.pyrochem.list_REE - - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['La', 'Lu'] - - - - -.. code-block:: default - - - df.pyrochem.list_compositional - - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['CaO', 'MgO', 'SiO2', 'FeO', 'Mn', 'Ti', 'La', 'Lu'] - - - -All elements (up to U): - - - -.. code-block:: default - - from pyrolite.geochem.ind import common_elements, common_oxides, REE - - common_elements() # string return - - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U'] - - - -All elements, returned as a list of `~periodictable.core.Formula`: - - - -.. code-block:: default - - common_elements(output="formula") # periodictable.core.Formula return - - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - [H, He, Li, Be, B, C, N, O, F, Ne, Na, Mg, Al, Si, P, S, Cl, Ar, K, Ca, Sc, Ti, V, Cr, Mn, Fe, Co, Ni, Cu, Zn, Ga, Ge, As, Se, Br, Kr, Rb, Sr, Y, Zr, Nb, Mo, Tc, Ru, Rh, Pd, Ag, Cd, In, Sn, Sb, Te, I, Xe, Cs, Ba, La, Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb, Lu, Hf, Ta, W, Re, Os, Ir, Pt, Au, Hg, Tl, Pb, Bi, Po, At, Rn, Fr, Ra, Ac, Th, Pa, U] - - - -Oxides for elements with positive charges (up to U): - - - -.. code-block:: default - - common_oxides() - - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['Th2O', 'ThO', 'Th2O3', 'ThO2', 'Se2O', 'SeO', 'Se2O3', 'SeO2', 'Se2O5', 'SeO3', 'Sb2O', 'SbO', 'Sb2O3', 'SbO2', 'Sb2O5', 'Ta2O', 'TaO', 'Ta2O3', 'TaO2', 'Ta2O5', 'N2O', 'NO', 'N2O3', 'NO2', 'N2O5', 'Sr2O', 'SrO', 'Co2O', 'CoO', 'Co2O3', 'CoO2', 'Co2O5', 'Cu2O', 'CuO', 'Cu2O3', 'CuO2', 'Tc2O', 'TcO', 'Tc2O3', 'TcO2', 'Tc2O5', 'TcO3', 'Tc2O7', 'Al2O', 'AlO', 'Al2O3', 'Zn2O', 'ZnO', 'V2O', 'VO', 'V2O3', 'VO2', 'V2O5', 'Ba2O', 'BaO', 'NdO', 'Nd2O3', 'NdO2', 'Hg2O', 'HgO', 'HgO2', 'TmO', 'Tm2O3', 'DyO', 'Dy2O3', 'DyO2', 'Tl2O', 'TlO', 'Tl2O3', 'As2O', 'AsO', 'As2O3', 'AsO2', 'As2O5', 'S2O', 'SO', 'S2O3', 'SO2', 'S2O5', 'SO3', 'CeO', 'Ce2O3', 'CeO2', 'Be2O', 'BeO', 'Sn2O', 'SnO', 'Sn2O3', 'SnO2', 'Br2O', 'Br2O3', 'BrO2', 'Br2O5', 'Br2O7', 'HoO', 'Ho2O3', 'Mg2O', 'MgO', 'Cs2O', 'Gd2O', 'GdO', 'Gd2O3', 'YbO', 'Yb2O3', 'Si2O', 'SiO', 'Si2O3', 'SiO2', 'Ru2O', 'RuO', 'Ru2O3', 'RuO2', 'Ru2O5', 'RuO3', 'Ru2O7', 'RuO4', 'RaO', 'Sc2O', 'ScO', 'Sc2O3', 'SmO', 'Sm2O3', 'Mn2O', 'MnO', 'Mn2O3', 'MnO2', 'Mn2O5', 'MnO3', 'Mn2O7', 'H2O', 'Li2O', 'In2O', 'InO', 'In2O3', 'C2O', 'CO', 'C2O3', 'CO2', 'K2O', 'Ge2O', 'GeO', 'Ge2O3', 'GeO2', 'W2O', 'WO', 'W2O3', 'WO2', 'W2O5', 'WO3', 'Rb2O', 'Nb2O', 'NbO', 'Nb2O3', 'NbO2', 'Nb2O5', 'Fe2O', 'FeO', 'Fe2O3', 'FeO2', 'Fe2O5', 'FeO3', 'Fe2O7', 'Ni2O', 'NiO', 'Ni2O3', 'NiO2', 'Pa2O3', 'PaO2', 'Pa2O5', 'Ac2O3', 'B2O', 'BO', 'B2O3', 'Fr2O', 'ErO', 'Er2O3', 'Rh2O', 'RhO', 'Rh2O3', 'RhO2', 'Rh2O5', 'RhO3', 'Pd2O', 'PdO', 'Pd2O3', 'PdO2', 'Pd2O5', 'PdO3', 'Pb2O', 'PbO', 'Pb2O3', 'PbO2', 'Re2O', 'ReO', 'Re2O3', 'ReO2', 'Re2O5', 'ReO3', 'Re2O7', 'La2O', 'LaO', 'La2O3', 'Bi2O', 'BiO', 'Bi2O3', 'BiO2', 'Bi2O5', 'Pt2O', 'PtO', 'Pt2O3', 'PtO2', 'Pt2O5', 'PtO3', 'Zr2O', 'ZrO', 'Zr2O3', 'ZrO2', 'RnO', 'RnO3', 'Tb2O', 'TbO', 'Tb2O3', 'TbO2', 'At2O', 'At2O3', 'At2O5', 'At2O7', 'PoO', 'PoO2', 'Po2O5', 'PoO3', 'P2O', 'PO', 'P2O3', 'PO2', 'P2O5', 'EuO', 'Eu2O3', 'Hf2O', 'HfO', 'Hf2O3', 'HfO2', 'Cl2O', 'ClO', 'Cl2O3', 'ClO2', 'Cl2O5', 'ClO3', 'Cl2O7', 'Cd2O', 'CdO', 'U2O', 'UO', 'U2O3', 'UO2', 'U2O5', 'UO3', 'Te2O', 'TeO', 'Te2O3', 'TeO2', 'Te2O5', 'TeO3', 'Mo2O', 'MoO', 'Mo2O3', 'MoO2', 'Mo2O5', 'MoO3', 'Ag2O', 'AgO', 'Ag2O3', 'AgO2', 'PrO', 'Pr2O3', 'PrO2', 'Pr2O5', 'Ca2O', 'CaO', 'LuO', 'Lu2O3', 'Os2O', 'OsO', 'Os2O3', 'OsO2', 'Os2O5', 'OsO3', 'Os2O7', 'OsO4', 'Au2O', 'AuO', 'Au2O3', 'Au2O5', 'Ga2O', 'GaO', 'Ga2O3', 'Na2O', 'I2O', 'I2O3', 'IO2', 'I2O5', 'IO3', 'I2O7', 'Y2O', 'YO', 'Y2O3', 'PmO', 'Pm2O3', 'Ir2O', 'IrO', 'Ir2O3', 'IrO2', 'Ir2O5', 'IrO3', 'Ir2O7', 'IrO4', 'Ir2O9', 'Cr2O', 'CrO', 'Cr2O3', 'CrO2', 'Cr2O5', 'CrO3', 'Ti2O', 'TiO', 'Ti2O3', 'TiO2', 'FeOT', 'Fe2O3T', 'LOI'] - - - - -.. code-block:: default - - - REE() - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['La', 'Ce', 'Pr', 'Nd', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu'] - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 0.361 seconds) - - -.. _sphx_glr_download_examples_geochem_indexes_selectors.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/geochem/indexes_selectors.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: indexes_selectors.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: indexes_selectors.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/geochem/indexes_selectors_codeobj.pickle b/docs/source/examples/geochem/indexes_selectors_codeobj.pickle deleted file mode 100644 index 8dbb6d4a..00000000 Binary files a/docs/source/examples/geochem/indexes_selectors_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/geochem/ionic_radii.ipynb b/docs/source/examples/geochem/ionic_radii.ipynb deleted file mode 100644 index 259dc8e6..00000000 --- a/docs/source/examples/geochem/ionic_radii.ipynb +++ /dev/null @@ -1,133 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nIonic Radii\n=============\n\n:mod:`pyrolite` incldues a few sets of reference tables for ionic radii in aangstroms\n(\u00c5) from [Shannon1976]_ and [WhittakerMuntus1970]_, each with tables indexed\nby element, ionic charge and coordination. The easiset way to access these is via\nthe :func:`~pyrolite.geochem.ind.get_ionic_radii` function. The function can be used\nto get radii for individual elements:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.geochem.ind import get_ionic_radii, REE\n\nCu_radii = get_ionic_radii(\"Cu\")\nprint(Cu_radii)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Note that this function returned a series of the possible radii, given specific\ncharges and coordinations of the Cu ion. If we completely specify these, we'll get\na single number back:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "Cu2plus6fold_radii = get_ionic_radii(\"Cu\", coordination=6, charge=2)\nprint(Cu2plus6fold_radii)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You can also pass lists to the function. For example, if you wanted to get the Shannon\nionic radii of Rare Earth Elements (REE) in eight-fold coordination with a valence of\n+3, you should use the following:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "shannon_ionic_radii = get_ionic_radii(REE(), coordination=8, charge=3)\nprint(shannon_ionic_radii)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The function defaults to using the Shannon ionic radii consistent with [Pauling1960]_,\nbut you can adjust to use the set you like with the `pauling` boolean argument\n(:code:`pauling=False` to use Shannon's 'Crystal Radii') or the `source` argument\n(:code:`source='Whittaker'` to use the [WhittakerMuntus1970]_ dataset):\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "shannon_crystal_radii = get_ionic_radii(REE(), coordination=8, charge=3, pauling=False)\nwhittaker_ionic_radii = get_ionic_radii(\n REE(), coordination=8, charge=3, source=\"Whittaker\"\n)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can see what the differences between these look like across the REE:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1)\n\nax.plot(shannon_ionic_radii, marker=\"D\", label=\"Shannon Ionic Radii\")\nax.plot(shannon_crystal_radii, marker=\"D\", label=\"Shannon Crystal Radii\")\nax.plot(whittaker_ionic_radii, marker=\"D\", label=\"Whittaker & Muntus\\nIonic Radii\")\n{a: b for (a, b) in zip(REE(), whittaker_ionic_radii)}\nax.set_xticks(range(len(REE())))\nax.set_xticklabels(REE())\nax.set_ylabel(\"Ionic Radius ($\\AA$)\")\nax.set_title(\"Rare Earth Element Ionic Radii\")\nax.legend(facecolor=None, frameon=False, bbox_to_anchor=(1, 1))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ".. seealso::\n\n Examples:\n `lambdas: Parameterising REE Profiles `__,\n `REE Radii Plot <../plotting/REE_radii_plot.html>`__\n\n Functions:\n :func:`~pyrolite.geochem.ind.get_ionic_radii`,\n :func:`pyrolite.geochem.ind.REE`,\n :func:`~pyrolite.geochem.pyrochem.lambda_lnREE`,\n\n\nReferences\n----------\n.. [Shannon1976] Shannon RD (1976). Revised effective ionic radii and systematic\n studies of interatomic distances in halides and chalcogenides.\n Acta Crystallographica Section A 32:751\u2013767.\n `doi: 10.1107/S0567739476001551 `__.\n.. [WhittakerMuntus1970] Whittaker, E.J.W., Muntus, R., 1970.\n Ionic radii for use in geochemistry.\n Geochimica et Cosmochimica Acta 34, 945\u2013956.\n `doi: 10.1016/0016-7037(70)90077-3 `__.\n.. [Pauling1960] Pauling, L., 1960. The Nature of the Chemical Bond.\n Cornell University Press, Ithaca, NY.\n\n\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/geochem/ionic_radii.py b/docs/source/examples/geochem/ionic_radii.py deleted file mode 100644 index 9899b873..00000000 --- a/docs/source/examples/geochem/ionic_radii.py +++ /dev/null @@ -1,81 +0,0 @@ -""" -Ionic Radii -============= - -:mod:`pyrolite` incldues a few sets of reference tables for ionic radii in aangstroms -(Å) from [Shannon1976]_ and [WhittakerMuntus1970]_, each with tables indexed -by element, ionic charge and coordination. The easiset way to access these is via -the :func:`~pyrolite.geochem.ind.get_ionic_radii` function. The function can be used -to get radii for individual elements: -""" -from pyrolite.geochem.ind import get_ionic_radii, REE - -Cu_radii = get_ionic_radii("Cu") -print(Cu_radii) -######################################################################################## -# Note that this function returned a series of the possible radii, given specific -# charges and coordinations of the Cu ion. If we completely specify these, we'll get -# a single number back: -# -Cu2plus6fold_radii = get_ionic_radii("Cu", coordination=6, charge=2) -print(Cu2plus6fold_radii) -######################################################################################## -# You can also pass lists to the function. For example, if you wanted to get the Shannon -# ionic radii of Rare Earth Elements (REE) in eight-fold coordination with a valence of -# +3, you should use the following: -# -shannon_ionic_radii = get_ionic_radii(REE(), coordination=8, charge=3) -print(shannon_ionic_radii) -######################################################################################## -# The function defaults to using the Shannon ionic radii consistent with [Pauling1960]_, -# but you can adjust to use the set you like with the `pauling` boolean argument -# (:code:`pauling=False` to use Shannon's 'Crystal Radii') or the `source` argument -# (:code:`source='Whittaker'` to use the [WhittakerMuntus1970]_ dataset): -# -shannon_crystal_radii = get_ionic_radii(REE(), coordination=8, charge=3, pauling=False) -whittaker_ionic_radii = get_ionic_radii( - REE(), coordination=8, charge=3, source="Whittaker" -) -######################################################################################## -# We can see what the differences between these look like across the REE: -# -import matplotlib.pyplot as plt - -fig, ax = plt.subplots(1) - -ax.plot(shannon_ionic_radii, marker="D", label="Shannon Ionic Radii") -ax.plot(shannon_crystal_radii, marker="D", label="Shannon Crystal Radii") -ax.plot(whittaker_ionic_radii, marker="D", label="Whittaker & Muntus\nIonic Radii") -{a: b for (a, b) in zip(REE(), whittaker_ionic_radii)} -ax.set_xticks(range(len(REE()))) -ax.set_xticklabels(REE()) -ax.set_ylabel("Ionic Radius ($\AA$)") -ax.set_title("Rare Earth Element Ionic Radii") -ax.legend(facecolor=None, frameon=False, bbox_to_anchor=(1, 1)) - -######################################################################################## -# .. seealso:: -# -# Examples: -# `lambdas: Parameterising REE Profiles `__, -# `REE Radii Plot <../plotting/REE_radii_plot.html>`__ -# -# Functions: -# :func:`~pyrolite.geochem.ind.get_ionic_radii`, -# :func:`pyrolite.geochem.ind.REE`, -# :func:`~pyrolite.geochem.pyrochem.lambda_lnREE`, -# -# -# References -# ---------- -# .. [Shannon1976] Shannon RD (1976). Revised effective ionic radii and systematic -# studies of interatomic distances in halides and chalcogenides. -# Acta Crystallographica Section A 32:751–767. -# `doi: 10.1107/S0567739476001551 `__. -# .. [WhittakerMuntus1970] Whittaker, E.J.W., Muntus, R., 1970. -# Ionic radii for use in geochemistry. -# Geochimica et Cosmochimica Acta 34, 945–956. -# `doi: 10.1016/0016-7037(70)90077-3 `__. -# .. [Pauling1960] Pauling, L., 1960. The Nature of the Chemical Bond. -# Cornell University Press, Ithaca, NY. -# diff --git a/docs/source/examples/geochem/ionic_radii.py.md5 b/docs/source/examples/geochem/ionic_radii.py.md5 deleted file mode 100644 index 683f1dd3..00000000 --- a/docs/source/examples/geochem/ionic_radii.py.md5 +++ /dev/null @@ -1 +0,0 @@ -367d15ad918a1ba88555d02234815b6b \ No newline at end of file diff --git a/docs/source/examples/geochem/ionic_radii.rst b/docs/source/examples/geochem/ionic_radii.rst deleted file mode 100644 index 8233ca9d..00000000 --- a/docs/source/examples/geochem/ionic_radii.rst +++ /dev/null @@ -1,213 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_geochem_ionic_radii.py: - - -Ionic Radii -============= - -:mod:`pyrolite` incldues a few sets of reference tables for ionic radii in aangstroms -(Å) from [Shannon1976]_ and [WhittakerMuntus1970]_, each with tables indexed -by element, ionic charge and coordination. The easiset way to access these is via -the :func:`~pyrolite.geochem.ind.get_ionic_radii` function. The function can be used -to get radii for individual elements: - - -.. code-block:: default - - from pyrolite.geochem.ind import get_ionic_radii, REE - - Cu_radii = get_ionic_radii("Cu") - print(Cu_radii) - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - index - Cu2+IV 0.57 - Cu2+IVSQ 0.57 - Cu2+V 0.65 - Cu2+VI 0.73 - Name: ionicradius, dtype: float64 - - - - -Note that this function returned a series of the possible radii, given specific -charges and coordinations of the Cu ion. If we completely specify these, we'll get -a single number back: - - - -.. code-block:: default - - Cu2plus6fold_radii = get_ionic_radii("Cu", coordination=6, charge=2) - print(Cu2plus6fold_radii) - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - 0.73 - - - - -You can also pass lists to the function. For example, if you wanted to get the Shannon -ionic radii of Rare Earth Elements (REE) in eight-fold coordination with a valence of -+3, you should use the following: - - - -.. code-block:: default - - shannon_ionic_radii = get_ionic_radii(REE(), coordination=8, charge=3) - print(shannon_ionic_radii) - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - [1.16, 1.143, 1.126, 1.109, 1.079, 1.0659999999999998, 1.053, 1.04, 1.0270000000000001, 1.015, 1.004, 0.9940000000000001, 0.985, 0.977] - - - - -The function defaults to using the Shannon ionic radii consistent with [Pauling1960]_, -but you can adjust to use the set you like with the `pauling` boolean argument -(:code:`pauling=False` to use Shannon's 'Crystal Radii') or the `source` argument -(:code:`source='Whittaker'` to use the [WhittakerMuntus1970]_ dataset): - - - -.. code-block:: default - - shannon_crystal_radii = get_ionic_radii(REE(), coordination=8, charge=3, pauling=False) - whittaker_ionic_radii = get_ionic_radii( - REE(), coordination=8, charge=3, source="Whittaker" - ) - - - - - - - -We can see what the differences between these look like across the REE: - - - -.. code-block:: default - - import matplotlib.pyplot as plt - - fig, ax = plt.subplots(1) - - ax.plot(shannon_ionic_radii, marker="D", label="Shannon Ionic Radii") - ax.plot(shannon_crystal_radii, marker="D", label="Shannon Crystal Radii") - ax.plot(whittaker_ionic_radii, marker="D", label="Whittaker & Muntus\nIonic Radii") - {a: b for (a, b) in zip(REE(), whittaker_ionic_radii)} - ax.set_xticks(range(len(REE()))) - ax.set_xticklabels(REE()) - ax.set_ylabel("Ionic Radius ($\AA$)") - ax.set_title("Rare Earth Element Ionic Radii") - ax.legend(facecolor=None, frameon=False, bbox_to_anchor=(1, 1)) - - - - -.. image:: /examples/geochem/images/sphx_glr_ionic_radii_001.png - :class: sphx-glr-single-img - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - - - - -.. seealso:: - - Examples: - `lambdas: Parameterising REE Profiles `__, - `REE Radii Plot <../plotting/REE_radii_plot.html>`__ - - Functions: - :func:`~pyrolite.geochem.ind.get_ionic_radii`, - :func:`pyrolite.geochem.ind.REE`, - :func:`~pyrolite.geochem.pyrochem.lambda_lnREE`, - - -References ----------- -.. [Shannon1976] Shannon RD (1976). Revised effective ionic radii and systematic - studies of interatomic distances in halides and chalcogenides. - Acta Crystallographica Section A 32:751–767. - `doi: 10.1107/S0567739476001551 `__. -.. [WhittakerMuntus1970] Whittaker, E.J.W., Muntus, R., 1970. - Ionic radii for use in geochemistry. - Geochimica et Cosmochimica Acta 34, 945–956. - `doi: 10.1016/0016-7037(70)90077-3 `__. -.. [Pauling1960] Pauling, L., 1960. The Nature of the Chemical Bond. - Cornell University Press, Ithaca, NY. - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 0.269 seconds) - - -.. _sphx_glr_download_examples_geochem_ionic_radii.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/geochem/ionic_radii.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: ionic_radii.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: ionic_radii.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/geochem/ionic_radii_codeobj.pickle b/docs/source/examples/geochem/ionic_radii_codeobj.pickle deleted file mode 100644 index 0fb5f01a..00000000 Binary files a/docs/source/examples/geochem/ionic_radii_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/geochem/lambdas.ipynb b/docs/source/examples/geochem/lambdas.ipynb deleted file mode 100644 index 5652f01e..00000000 --- a/docs/source/examples/geochem/lambdas.ipynb +++ /dev/null @@ -1,151 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nlambdas: Parameterising REE Profiles\n=====================================\n\nOrthogonal polynomial decomposition can be used for dimensional reduction of smooth\nfunction over an independent variable, producing an array of independent values\nrepresenting the relative weights for each order of component polynomial. This is an\neffective method to parameterise and compare the nature of smooth profiles.\n\nIn geochemistry, the most applicable use case is for reduction Rare Earth Element (REE)\nprofiles. The REE are a collection of elements with broadly similar physicochemical\nproperties (the lanthanides), which vary with ionic radii. Given their similar behaviour\nand typically smooth function of normalised abundance vs. ionic radii, the REE profiles\nand their shapes can be effectively parameterised and dimensionally reduced (14 elements\nsummarised by 3-4 shape parameters).\n\nHere we generate some example data, reduce these to lambda values, and visualise the\nresults.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pyrolite.plot\n\n\nnp.random.seed(82)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First we'll generate some example synthetic data based around Depleted Morb Mantle:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.synthetic import example_spider_data\n\ndf = example_spider_data(\n noise_level=0.05,\n nobs=100,\n start=\"DMM_WH2005\",\n norm_to=\"Chondrite_PON\",\n offsets={\"Eu\": 0.2},\n)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let's have a quick look at what this REE data looks like:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyroplot.REE(alpha=0.05, c=\"k\", unity_line=True)\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "From this REE data we can fit a series of orthogonal polynomials, and subsequently used\nthe regression coefficients ('lambdas') as a parameterisation of the REE\npattern/profile. This example data is already normalised to Chondrite, so to avoid\ndouble-normalising, we pass :code:`norm_to=None`:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ls = df.pyrochem.lambda_lnREE(degree=4, norm_to=None)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "So what's actually happening here? To get some idea of what these \u03bb coefficients\ncorrespond to, we can pull this process apart and visualse our REE profiles as\nthe sum of the series of orthogonal polynomial components of increasing order.\nAs lambdas represent the coefficients for the regression of log-transformed normalised\ndata, we'll first need to take the logarithm.\n\nWith our data, we've then fit a function of ionic radius with the form\n$f(r) = \\lambda_0 + \\lambda_1 f_1 + \\lambda_2 f_2 + \\lambda_3 f_3...$\nwhere the polynomial components of increasing order are $f_1 = (r - \\beta_0)$,\n$f_2 = (r - \\gamma_0)(r - \\gamma_1)$,\n$f_3 = (r - \\delta_0)(r - \\delta_1)(r - \\delta_2)$ and so on. The parameters\n$\\beta$, $\\gamma$, $\\delta$ are pre-computed such that the\npolynomial components are indeed independent. Here we can visualise how these\npolynomial components are summed to produce the regressed profile, using the last REE\nprofile we generated above as an example:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.lambdas import plot_lambdas_components\n\nax = df.iloc[-1, :].apply(np.log).pyroplot.REE(color=\"k\", label=\"Data\", logy=False)\n\nplot_lambdas_components(ls.iloc[-1, :], ax=ax)\n\nax.legend(frameon=False, facecolor=None, bbox_to_anchor=(1, 1))\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Note that we've not used Eu in this regression - Eu anomalies are a deviation from\nthe 'smooth profile' we need to use this method. Consider this if your data might also\nexhibit significant Ce anomalies, you might need to exclude this data.\n\nNow that we've gone through a brief introduction to how the lambdas are generated,\nlet's quickly check what the coefficient values themselves look like:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(1, 3, figsize=(9, 3))\nfor ix in range(ls.columns.size - 1):\n ls[ls.columns[ix : ix + 2]].pyroplot.scatter(ax=ax[ix], alpha=0.1, c=\"k\")\n\nplt.tight_layout()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "But what do these parameters correspond to? From the deconstructed orthogonal\npolynomial above, we can see that $\\lambda_0$ parameterises relative enrichement\n(this is the mean value of the logarithm of Chondrite-normalised REE abundances),\n$\\lambda_1$ parameterises a linear slope (here, LREE enrichemnt), and higher\norder terms describe curvature of the REE pattern. Through this parameterisation,\nthe REE profile can be effectively described and directly linked to geochemical\nprocesses. While the amount of data we need to describe the patterns is lessened,\nthe values themselves are more meaningful and readily used to describe the profiles\nand their physical significance.\n\nThe visualisation of $\\lambda_1$-$\\lambda_2$ can be particularly useful\nwhere you're trying to compare REE profiles.\n\nWe've used a synthetic dataset here which is by design approximately normally\ndistrtibuted, so the values themeselves here are not particularly revealing,\nbut they do illustrate the expected mangitudes of values for each of the parameters.\n\nFor more on using orthogonal polynomials to describe geochemical pattern data, dig\ninto the paper which introduced the method to geochemists:\nO\u2019Neill, H.S.C., 2016. The Smoothness and Shapes of Chondrite-normalized Rare Earth\nElement Patterns in Basalts. J Petrology 57, 1463\u20131508.\n`doi: 10.1093/petrology/egw047 `__.\n\n.. seealso::\n\n Examples:\n `Ionic Radii `__,\n `REE Radii Plot <../plotting/REE_radii_plot.html>`__\n\n Functions:\n :func:`~pyrolite.geochem.pyrochem.lambda_lnREE`,\n :func:`~pyrolite.geochem.ind.get_ionic_radii`,\n :func:`pyrolite.plot.pyroplot.REE`\n\n\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/geochem/lambdas.py b/docs/source/examples/geochem/lambdas.py deleted file mode 100644 index 9633ff7d..00000000 --- a/docs/source/examples/geochem/lambdas.py +++ /dev/null @@ -1,125 +0,0 @@ -""" -lambdas: Parameterising REE Profiles -===================================== - -Orthogonal polynomial decomposition can be used for dimensional reduction of smooth -function over an independent variable, producing an array of independent values -representing the relative weights for each order of component polynomial. This is an -effective method to parameterise and compare the nature of smooth profiles. - -In geochemistry, the most applicable use case is for reduction Rare Earth Element (REE) -profiles. The REE are a collection of elements with broadly similar physicochemical -properties (the lanthanides), which vary with ionic radii. Given their similar behaviour -and typically smooth function of normalised abundance vs. ionic radii, the REE profiles -and their shapes can be effectively parameterised and dimensionally reduced (14 elements -summarised by 3-4 shape parameters). - -Here we generate some example data, reduce these to lambda values, and visualise the -results. -""" -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import pyrolite.plot - -# sphinx_gallery_thumbnail_number = 2 - -np.random.seed(82) -######################################################################################## -# First we'll generate some example synthetic data based around Depleted Morb Mantle: -# -from pyrolite.util.synthetic import example_spider_data - -df = example_spider_data( - noise_level=0.05, - nobs=100, - start="DMM_WH2005", - norm_to="Chondrite_PON", - offsets={"Eu": 0.2}, -) -######################################################################################## -# Let's have a quick look at what this REE data looks like: -# -df.pyroplot.REE(alpha=0.05, c="k", unity_line=True) -plt.show() -######################################################################################## -# From this REE data we can fit a series of orthogonal polynomials, and subsequently used -# the regression coefficients ('lambdas') as a parameterisation of the REE -# pattern/profile. This example data is already normalised to Chondrite, so to avoid -# double-normalising, we pass :code:`norm_to=None`: -# -ls = df.pyrochem.lambda_lnREE(degree=4, norm_to=None) -######################################################################################## -# So what's actually happening here? To get some idea of what these λ coefficients -# correspond to, we can pull this process apart and visualse our REE profiles as -# the sum of the series of orthogonal polynomial components of increasing order. -# As lambdas represent the coefficients for the regression of log-transformed normalised -# data, we'll first need to take the logarithm. -# -# With our data, we've then fit a function of ionic radius with the form -# :math:`f(r) = \lambda_0 + \lambda_1 f_1 + \lambda_2 f_2 + \lambda_3 f_3...` -# where the polynomial components of increasing order are :math:`f_1 = (r - \beta_0)`, -# :math:`f_2 = (r - \gamma_0)(r - \gamma_1)`, -# :math:`f_3 = (r - \delta_0)(r - \delta_1)(r - \delta_2)` and so on. The parameters -# :math:`\beta`, :math:`\gamma`, :math:`\delta` are pre-computed such that the -# polynomial components are indeed independent. Here we can visualise how these -# polynomial components are summed to produce the regressed profile, using the last REE -# profile we generated above as an example: -# -from pyrolite.util.lambdas import plot_lambdas_components - -ax = df.iloc[-1, :].apply(np.log).pyroplot.REE(color="k", label="Data", logy=False) - -plot_lambdas_components(ls.iloc[-1, :], ax=ax) - -ax.legend(frameon=False, facecolor=None, bbox_to_anchor=(1, 1)) -plt.show() -######################################################################################## -# Note that we've not used Eu in this regression - Eu anomalies are a deviation from -# the 'smooth profile' we need to use this method. Consider this if your data might also -# exhibit significant Ce anomalies, you might need to exclude this data. -# -# Now that we've gone through a brief introduction to how the lambdas are generated, -# let's quickly check what the coefficient values themselves look like: -# - -fig, ax = plt.subplots(1, 3, figsize=(9, 3)) -for ix in range(ls.columns.size - 1): - ls[ls.columns[ix : ix + 2]].pyroplot.scatter(ax=ax[ix], alpha=0.1, c="k") - -plt.tight_layout() -######################################################################################## -# But what do these parameters correspond to? From the deconstructed orthogonal -# polynomial above, we can see that :math:`\lambda_0` parameterises relative enrichement -# (this is the mean value of the logarithm of Chondrite-normalised REE abundances), -# :math:`\lambda_1` parameterises a linear slope (here, LREE enrichemnt), and higher -# order terms describe curvature of the REE pattern. Through this parameterisation, -# the REE profile can be effectively described and directly linked to geochemical -# processes. While the amount of data we need to describe the patterns is lessened, -# the values themselves are more meaningful and readily used to describe the profiles -# and their physical significance. -# -# The visualisation of :math:`\lambda_1`-:math:`\lambda_2` can be particularly useful -# where you're trying to compare REE profiles. -# -# We've used a synthetic dataset here which is by design approximately normally -# distrtibuted, so the values themeselves here are not particularly revealing, -# but they do illustrate the expected mangitudes of values for each of the parameters. -# -# For more on using orthogonal polynomials to describe geochemical pattern data, dig -# into the paper which introduced the method to geochemists: -# O’Neill, H.S.C., 2016. The Smoothness and Shapes of Chondrite-normalized Rare Earth -# Element Patterns in Basalts. J Petrology 57, 1463–1508. -# `doi: 10.1093/petrology/egw047 `__. -# -# .. seealso:: -# -# Examples: -# `Ionic Radii `__, -# `REE Radii Plot <../plotting/REE_radii_plot.html>`__ -# -# Functions: -# :func:`~pyrolite.geochem.pyrochem.lambda_lnREE`, -# :func:`~pyrolite.geochem.ind.get_ionic_radii`, -# :func:`pyrolite.plot.pyroplot.REE` -# diff --git a/docs/source/examples/geochem/lambdas.py.md5 b/docs/source/examples/geochem/lambdas.py.md5 deleted file mode 100644 index 3236c219..00000000 --- a/docs/source/examples/geochem/lambdas.py.md5 +++ /dev/null @@ -1 +0,0 @@ -d459ab8716e91c0d596d252cda9004a8 \ No newline at end of file diff --git a/docs/source/examples/geochem/lambdas.rst b/docs/source/examples/geochem/lambdas.rst deleted file mode 100644 index 0e8415b8..00000000 --- a/docs/source/examples/geochem/lambdas.rst +++ /dev/null @@ -1,235 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_geochem_lambdas.py: - - -lambdas: Parameterising REE Profiles -===================================== - -Orthogonal polynomial decomposition can be used for dimensional reduction of smooth -function over an independent variable, producing an array of independent values -representing the relative weights for each order of component polynomial. This is an -effective method to parameterise and compare the nature of smooth profiles. - -In geochemistry, the most applicable use case is for reduction Rare Earth Element (REE) -profiles. The REE are a collection of elements with broadly similar physicochemical -properties (the lanthanides), which vary with ionic radii. Given their similar behaviour -and typically smooth function of normalised abundance vs. ionic radii, the REE profiles -and their shapes can be effectively parameterised and dimensionally reduced (14 elements -summarised by 3-4 shape parameters). - -Here we generate some example data, reduce these to lambda values, and visualise the -results. - - -.. code-block:: default - - import numpy as np - import pandas as pd - import matplotlib.pyplot as plt - import pyrolite.plot - - - np.random.seed(82) - - - - - - - -First we'll generate some example synthetic data based around Depleted Morb Mantle: - - - -.. code-block:: default - - from pyrolite.util.synthetic import example_spider_data - - df = example_spider_data( - noise_level=0.05, - nobs=100, - start="DMM_WH2005", - norm_to="Chondrite_PON", - offsets={"Eu": 0.2}, - ) - - - - - - - -Let's have a quick look at what this REE data looks like: - - - -.. code-block:: default - - df.pyroplot.REE(alpha=0.05, c="k", unity_line=True) - plt.show() - - - -.. image:: /examples/geochem/images/sphx_glr_lambdas_001.png - :class: sphx-glr-single-img - - - - - -From this REE data we can fit a series of orthogonal polynomials, and subsequently used -the regression coefficients ('lambdas') as a parameterisation of the REE -pattern/profile. This example data is already normalised to Chondrite, so to avoid -double-normalising, we pass :code:`norm_to=None`: - - - -.. code-block:: default - - ls = df.pyrochem.lambda_lnREE(degree=4, norm_to=None) - - - - - - - -So what's actually happening here? To get some idea of what these λ coefficients -correspond to, we can pull this process apart and visualse our REE profiles as -the sum of the series of orthogonal polynomial components of increasing order. -As lambdas represent the coefficients for the regression of log-transformed normalised -data, we'll first need to take the logarithm. - -With our data, we've then fit a function of ionic radius with the form -:math:`f(r) = \lambda_0 + \lambda_1 f_1 + \lambda_2 f_2 + \lambda_3 f_3...` -where the polynomial components of increasing order are :math:`f_1 = (r - \beta_0)`, -:math:`f_2 = (r - \gamma_0)(r - \gamma_1)`, -:math:`f_3 = (r - \delta_0)(r - \delta_1)(r - \delta_2)` and so on. The parameters -:math:`\beta`, :math:`\gamma`, :math:`\delta` are pre-computed such that the -polynomial components are indeed independent. Here we can visualise how these -polynomial components are summed to produce the regressed profile, using the last REE -profile we generated above as an example: - - - -.. code-block:: default - - from pyrolite.util.lambdas import plot_lambdas_components - - ax = df.iloc[-1, :].apply(np.log).pyroplot.REE(color="k", label="Data", logy=False) - - plot_lambdas_components(ls.iloc[-1, :], ax=ax) - - ax.legend(frameon=False, facecolor=None, bbox_to_anchor=(1, 1)) - plt.show() - - - -.. image:: /examples/geochem/images/sphx_glr_lambdas_002.png - :class: sphx-glr-single-img - - - - - -Note that we've not used Eu in this regression - Eu anomalies are a deviation from -the 'smooth profile' we need to use this method. Consider this if your data might also -exhibit significant Ce anomalies, you might need to exclude this data. - -Now that we've gone through a brief introduction to how the lambdas are generated, -let's quickly check what the coefficient values themselves look like: - - - -.. code-block:: default - - - fig, ax = plt.subplots(1, 3, figsize=(9, 3)) - for ix in range(ls.columns.size - 1): - ls[ls.columns[ix : ix + 2]].pyroplot.scatter(ax=ax[ix], alpha=0.1, c="k") - - plt.tight_layout() - - - -.. image:: /examples/geochem/images/sphx_glr_lambdas_003.png - :class: sphx-glr-single-img - - - - - -But what do these parameters correspond to? From the deconstructed orthogonal -polynomial above, we can see that :math:`\lambda_0` parameterises relative enrichement -(this is the mean value of the logarithm of Chondrite-normalised REE abundances), -:math:`\lambda_1` parameterises a linear slope (here, LREE enrichemnt), and higher -order terms describe curvature of the REE pattern. Through this parameterisation, -the REE profile can be effectively described and directly linked to geochemical -processes. While the amount of data we need to describe the patterns is lessened, -the values themselves are more meaningful and readily used to describe the profiles -and their physical significance. - -The visualisation of :math:`\lambda_1`-:math:`\lambda_2` can be particularly useful -where you're trying to compare REE profiles. - -We've used a synthetic dataset here which is by design approximately normally -distrtibuted, so the values themeselves here are not particularly revealing, -but they do illustrate the expected mangitudes of values for each of the parameters. - -For more on using orthogonal polynomials to describe geochemical pattern data, dig -into the paper which introduced the method to geochemists: -O’Neill, H.S.C., 2016. The Smoothness and Shapes of Chondrite-normalized Rare Earth -Element Patterns in Basalts. J Petrology 57, 1463–1508. -`doi: 10.1093/petrology/egw047 `__. - -.. seealso:: - - Examples: - `Ionic Radii `__, - `REE Radii Plot <../plotting/REE_radii_plot.html>`__ - - Functions: - :func:`~pyrolite.geochem.pyrochem.lambda_lnREE`, - :func:`~pyrolite.geochem.ind.get_ionic_radii`, - :func:`pyrolite.plot.pyroplot.REE` - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 4.599 seconds) - - -.. _sphx_glr_download_examples_geochem_lambdas.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/geochem/lambdas.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: lambdas.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: lambdas.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/geochem/lambdas_codeobj.pickle b/docs/source/examples/geochem/lambdas_codeobj.pickle deleted file mode 100644 index 3839244f..00000000 Binary files a/docs/source/examples/geochem/lambdas_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/geochem/mineral_endmembers.ipynb b/docs/source/examples/geochem/mineral_endmembers.ipynb deleted file mode 100644 index 25ede494..00000000 --- a/docs/source/examples/geochem/mineral_endmembers.ipynb +++ /dev/null @@ -1,180 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nMineral Endmember Decomposition\n=================================\n\nA common task when working with mineral chemistry data is to take measured compositions\nand decompose these into relative proportions of mineral endmember compositions.\npyrolite includes some utilities to achieve this and a limited mineral database\nfor looking up endmember compositions. This part of the package is being actively\ndeveloped, so expect expansions and improvements soon.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pandas as pd\nimport numpy as np\nfrom pyrolite.mineral.mindb import get_mineral\nfrom pyrolite.mineral.normative import endmember_decompose" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First we'll start with a composition of an unknown olivine:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "comp = pd.Series({\"MgO\": 42.06, \"SiO2\": 39.19, \"FeO\": 18.75})" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can break this down into olivine endmebmers using the\n:func:`~pyrolite.mineral.transform.endmember_decompose` function:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ed = endmember_decompose(\n pd.DataFrame(comp).T, endmembers=\"olivine\", ord=1, molecular=True\n)\ned" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Equally, if you knew the likely endmembers beforehand, you could specify a list of\nendmembers:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ed = endmember_decompose(\n pd.DataFrame(comp).T, endmembers=[\"forsterite\", \"fayalite\"], ord=1, molecular=True\n)\ned" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can check this by recombining the components with these proportions. We can first\nlookup the compositions for our endmembers:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "em = pd.DataFrame([get_mineral(\"forsterite\"), get_mineral(\"fayalite\")])\nem.loc[:, ~(em == 0).all(axis=0)] # columns not full of zeros" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First we have to convert these element-based compositions to oxide-based compositions:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "emvalues = (\n em.loc[:, [\"Mg\", \"Si\", \"Fe\"]]\n .pyrochem.to_molecular()\n .fillna(0)\n .pyrochem.convert_chemistry(to=[\"MgO\", \"SiO2\", \"FeO\"], molecular=True)\n .fillna(0)\n .pyrocomp.renormalise(scale=1)\n)\nemvalues" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These can now be used with our endmember proportions to regenerate a composition:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "recombined = pd.DataFrame(ed.values.flatten() @ emvalues).T.pyrochem.to_weight()\nrecombined" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To make sure these compositions are within 0.01 percent:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "assert np.allclose(recombined.values, comp.values, rtol=10 ** -4)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/geochem/mineral_endmembers.py b/docs/source/examples/geochem/mineral_endmembers.py deleted file mode 100644 index 01d89e6f..00000000 --- a/docs/source/examples/geochem/mineral_endmembers.py +++ /dev/null @@ -1,62 +0,0 @@ -""" -Mineral Endmember Decomposition -================================= - -A common task when working with mineral chemistry data is to take measured compositions -and decompose these into relative proportions of mineral endmember compositions. -pyrolite includes some utilities to achieve this and a limited mineral database -for looking up endmember compositions. This part of the package is being actively -developed, so expect expansions and improvements soon. -""" -import pandas as pd -import numpy as np -from pyrolite.mineral.mindb import get_mineral -from pyrolite.mineral.normative import endmember_decompose - -######################################################################################## -# First we'll start with a composition of an unknown olivine: -# -comp = pd.Series({"MgO": 42.06, "SiO2": 39.19, "FeO": 18.75}) -######################################################################################## -# We can break this down into olivine endmebmers using the -# :func:`~pyrolite.mineral.transform.endmember_decompose` function: -# -ed = endmember_decompose( - pd.DataFrame(comp).T, endmembers="olivine", ord=1, molecular=True -) -ed -######################################################################################## -# Equally, if you knew the likely endmembers beforehand, you could specify a list of -# endmembers: -# -ed = endmember_decompose( - pd.DataFrame(comp).T, endmembers=["forsterite", "fayalite"], ord=1, molecular=True -) -ed -######################################################################################## -# We can check this by recombining the components with these proportions. We can first -# lookup the compositions for our endmembers: -# -em = pd.DataFrame([get_mineral("forsterite"), get_mineral("fayalite")]) -em.loc[:, ~(em == 0).all(axis=0)] # columns not full of zeros -######################################################################################## -# First we have to convert these element-based compositions to oxide-based compositions: -# -emvalues = ( - em.loc[:, ["Mg", "Si", "Fe"]] - .pyrochem.to_molecular() - .fillna(0) - .pyrochem.convert_chemistry(to=["MgO", "SiO2", "FeO"], molecular=True) - .fillna(0) - .pyrocomp.renormalise(scale=1) -) -emvalues -######################################################################################## -# These can now be used with our endmember proportions to regenerate a composition: -# -recombined = pd.DataFrame(ed.values.flatten() @ emvalues).T.pyrochem.to_weight() -recombined -######################################################################################## -# To make sure these compositions are within 0.01 percent: -# -assert np.allclose(recombined.values, comp.values, rtol=10 ** -4) diff --git a/docs/source/examples/geochem/mineral_endmembers.py.md5 b/docs/source/examples/geochem/mineral_endmembers.py.md5 deleted file mode 100644 index bdeaa316..00000000 --- a/docs/source/examples/geochem/mineral_endmembers.py.md5 +++ /dev/null @@ -1 +0,0 @@ -446a63f38775313a2ee269f5164c84c8 \ No newline at end of file diff --git a/docs/source/examples/geochem/mineral_endmembers.rst b/docs/source/examples/geochem/mineral_endmembers.rst deleted file mode 100644 index 8089dd63..00000000 --- a/docs/source/examples/geochem/mineral_endmembers.rst +++ /dev/null @@ -1,394 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_geochem_mineral_endmembers.py: - - -Mineral Endmember Decomposition -================================= - -A common task when working with mineral chemistry data is to take measured compositions -and decompose these into relative proportions of mineral endmember compositions. -pyrolite includes some utilities to achieve this and a limited mineral database -for looking up endmember compositions. This part of the package is being actively -developed, so expect expansions and improvements soon. - - -.. code-block:: default - - import pandas as pd - import numpy as np - from pyrolite.mineral.mindb import get_mineral - from pyrolite.mineral.normative import endmember_decompose - - - - - - - - -First we'll start with a composition of an unknown olivine: - - - -.. code-block:: default - - comp = pd.Series({"MgO": 42.06, "SiO2": 39.19, "FeO": 18.75}) - - - - - - - -We can break this down into olivine endmebmers using the -:func:`~pyrolite.mineral.transform.endmember_decompose` function: - - - -.. code-block:: default - - ed = endmember_decompose( - pd.DataFrame(comp).T, endmembers="olivine", ord=1, molecular=True - ) - ed - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - -
nameforsteritefayalite
079.99420.006
-
-
-
- -Equally, if you knew the likely endmembers beforehand, you could specify a list of -endmembers: - - - -.. code-block:: default - - ed = endmember_decompose( - pd.DataFrame(comp).T, endmembers=["forsterite", "fayalite"], ord=1, molecular=True - ) - ed - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - -
forsteritefayalite
079.99420.006
-
-
-
- -We can check this by recombining the components with these proportions. We can first -lookup the compositions for our endmembers: - - - -.. code-block:: default - - em = pd.DataFrame([get_mineral("forsterite"), get_mineral("fayalite")]) - em.loc[:, ~(em == 0).all(axis=0)] # columns not full of zeros - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
namegroupformulaMgSiOFe
0forsteriteolivineMg2SiO40.3460.2000.4550.000
1fayaliteolivineFe2SiO40.0000.1380.3140.548
-
-
-
- -First we have to convert these element-based compositions to oxide-based compositions: - - - -.. code-block:: default - - emvalues = ( - em.loc[:, ["Mg", "Si", "Fe"]] - .pyrochem.to_molecular() - .fillna(0) - .pyrochem.convert_chemistry(to=["MgO", "SiO2", "FeO"], molecular=True) - .fillna(0) - .pyrocomp.renormalise(scale=1) - ) - emvalues - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - -
MgOSiO2FeO
00.6670.3330.000
10.0000.3330.667
-
-
-
- -These can now be used with our endmember proportions to regenerate a composition: - - - -.. code-block:: default - - recombined = pd.DataFrame(ed.values.flatten() @ emvalues).T.pyrochem.to_weight() - recombined - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - -
MgOSiO2FeO
042.05939.19118.75
-
-
-
- -To make sure these compositions are within 0.01 percent: - - - -.. code-block:: default - - assert np.allclose(recombined.values, comp.values, rtol=10 ** -4) - - - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 0.294 seconds) - - -.. _sphx_glr_download_examples_geochem_mineral_endmembers.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/geochem/mineral_endmembers.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: mineral_endmembers.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: mineral_endmembers.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/geochem/mineral_endmembers_codeobj.pickle b/docs/source/examples/geochem/mineral_endmembers_codeobj.pickle deleted file mode 100644 index 2e00e97a..00000000 Binary files a/docs/source/examples/geochem/mineral_endmembers_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/geochem/mineral_lattice.ipynb b/docs/source/examples/geochem/mineral_lattice.ipynb deleted file mode 100644 index 703253a4..00000000 --- a/docs/source/examples/geochem/mineral_lattice.ipynb +++ /dev/null @@ -1,151 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nLattice Strain Calculations\n------------------------------\n\n

Note

This example follows that given during a Institute of Advanced Studies Masterclass\n with Jon Blundy at the University of Western Australia on the 29\\ :sup:`th` April\n 2019, and is used here with permission.

\n\n\nPyrolite includes a function for calculating relative lattice strain [#ref_1]_, which\ntogether with the tables of Shannon ionic radii and Young's modulus approximations for\nsilicate and oxide cationic sites enable relatively simple calculation of ionic\npartitioning in common rock forming minerals.\n\nThis example below uses previously characterised calcium and sodium partition\ncoefficients between plagioclase ($CaAl_2Si_2O_8 - NaAlSi_3O8$) and silicate melt\nto estimate partitioning for other cations based on their ionic radii.\n\nA model parameterised using sodium and calcium partition coefficients [#ref_2]_ is then\nused to estimate the partitioning for lanthanum into the trivalent site (largely\noccupied by $Al^{3+}$), and extended to other trivalent cations (here, the Rare\nEarth Elements). The final section of the example highlights the mechanism which\ngenerates plagioclase's hallmark 'europium anomaly', and the effects of variable\neuropium oxidation state on bulk europium partitioning.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\nimport matplotlib.pyplot as plt\nfrom pyrolite.geochem.ind import REE, get_ionic_radii\nfrom pyrolite.mineral.lattice import strain_coefficient" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First, we need to define some of the necessary parameters including temperature, the Young's\nmoduli for the $X^{2+}$ and $X^{3+}$ sites in plagioclase ($E_2$,\n$E_3$), and some reference partition coefficients and radii for calcium and\nsodium:\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "D_Na = 1.35 # Partition coefficient Plag-Melt\nD_Ca = 4.1 # Partition coefficient Plag-Melt\nTc = 900 # Temperature, \u00b0C\nTk = Tc + 273.15 # Temperature, K\nE_2 = 120 * 10 ** 9 # Youngs modulus for 2+ site, Pa\nE_3 = 135 * 10 ** 9 # Youngs modulus for 3+ site, Pa\nr02, r03 = 1.196, 1.294 # fictive ideal cation radii for these sites\nrCa = get_ionic_radii(\"Ca\", charge=2, coordination=8)\nrLa = get_ionic_radii(\"La\", charge=3, coordination=8)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can calculate and plot the partitioning of $X^{2+}$ cations relative to\n$Ca^{2+}$ at a given temperature using their radii and the lattice strain function:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fontsize = 8\nfig, ax = plt.subplots(1)\n\nsite2labels = [\"Na\", \"Ca\", \"Eu\", \"Sr\"]\n# get the Shannon ionic radii for the elements in the 2+ site\nsite2radii = [\n get_ionic_radii(\"Na\", charge=1, coordination=8),\n *[get_ionic_radii(el, charge=2, coordination=8) for el in [\"Ca\", \"Eu\", \"Sr\"]],\n]\n# plot the relative paritioning curve for cations in the 2+ site\nsite2Ds = D_Ca * np.array(\n [strain_coefficient(rCa, rx, r0=r02, E=E_2, T=Tk) for rx in site2radii]\n)\nax.scatter(site2radii, site2Ds, color=\"g\", label=\"$X^{2+}$ Cations\")\n# create an index of radii, and plot the relative paritioning curve for the site\nxs = np.linspace(0.9, 1.3, 200)\ncurve2Ds = D_Ca * strain_coefficient(rCa, xs, r0=r02, E=E_2, T=Tk)\nax.plot(xs, curve2Ds, color=\"0.5\", ls=\"--\")\n# add the element labels next to the points\nfor l, r, d in zip(site2labels, site2radii, site2Ds):\n ax.annotate(\n l, xy=(r, d), xycoords=\"data\", ha=\"left\", va=\"bottom\", fontsize=fontsize\n )\nfig" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "When it comes to estimating the partitioning of $X^{3+}$ cations, we'll need a reference\npoint - here we'll use $D_{La}$ to calculate relative partitioning of the other\nRare Earth Elements, although you may have noticed it is not defined above.\nThrough a handy relationship, we can estimate $D_{La}$\nbased on the easier measured $D_{Ca}$, $D_{Na}$ and temperature [#ref_2]_:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "D_La = (D_Ca ** 2 / D_Na) * np.exp((529 / Tk) - 3.705)\nD_La # 0.48085" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now $D_{La}$ is defined, we can use it as a reference for the other REE:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "site3labels = REE(dropPm=True)\n# get the Shannon ionic radii for the elements in the 3+ site\nsite3radii = [get_ionic_radii(x, charge=3, coordination=8) for x in REE(dropPm=True)]\nsite3Ds = D_La * np.array(\n [strain_coefficient(rLa, rx, r0=r03, E=E_3, T=Tk) for rx in site3radii]\n)\n# plot the relative paritioning curve for cations in the 3+ site\nax.scatter(site3radii, site3Ds, color=\"purple\", label=\"$X^{3+}$ Cations\")\n# plot the relative paritioning curve for the site\ncurve3Ds = D_La * strain_coefficient(rLa, xs, r0=r03, E=E_3, T=Tk)\nax.plot(xs, curve3Ds, color=\"0.5\", ls=\"--\")\n# add the element labels next to the points\nfor l, r, d in zip(site3labels, site3radii, site3Ds):\n ax.annotate(\n l, xy=(r, d), xycoords=\"data\", ha=\"right\", va=\"bottom\", fontsize=fontsize\n )\nax.set_yscale(\"log\")\nax.set_ylabel(\"$D_X$\")\nax.set_xlabel(\"Radii ($\\AA$)\")\nfig" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As europium is commonly present as a mixture of both $Eu^{2+}$\nand $Eu^{3+}$, the effective partitioning of Eu will be intermediate\nbetween that of $D_{Eu^{2+}}$and $D_{Eu^{3+}}$. Using a 60:40 mixture\nof $Eu^{3+}$ : $Eu^{2+}$ as an example, this effective partition\ncoefficient can be calculated:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "X_Eu3 = 0.6\n# calculate D_Eu3 relative to D_La\nD_Eu3 = D_La * strain_coefficient(\n rLa, get_ionic_radii(\"Eu\", charge=3, coordination=8), r0=r03, E=E_3, T=Tk\n)\n# calculate D_Eu2 relative to D_Ca\nD_Eu2 = D_Ca * strain_coefficient(\n rCa, get_ionic_radii(\"Eu\", charge=2, coordination=8), r0=r02, E=E_2, T=Tk\n)\n# calculate the effective parition coefficient\nD_Eu = (1 - X_Eu3) * D_Eu2 + X_Eu3 * D_Eu3\n# show the effective partition coefficient relative to the 2+ and 3+ endmembers\nradii, ds = (\n [get_ionic_radii(\"Eu\", charge=c, coordination=8) for c in [3, 3, 2, 2]],\n [D_Eu3, D_Eu, D_Eu, D_Eu2],\n)\nax.plot(\n radii, ds, ls=\"--\", color=\"0.9\", marker=\"D\", label=\"Effective $D_{Eu}$\", zorder=-1\n)\nax.legend(loc=\"upper left\", bbox_to_anchor=(1.05, 1), frameon=False, facecolor=None)\nfig" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ".. [#ref_1] Blundy, J., Wood, B., 1994. Prediction of crystal\u2013melt partition coefficients\n from elastic moduli. Nature 372, 452.\n doi: `10.1038/372452A0 `__\n\n.. [#ref_2] Dohmen, R., Blundy, J., 2014. A predictive thermodynamic model for element partitioning\n between plagioclase and melt as a function of pressure, temperature and composition.\n American Journal of Science 314, 1319\u20131372.\n doi: `10.2475/09.2014.04 `__\n\n.. seealso::\n\n Examples:\n `Shannon Radii <../indexes/shannon.html>`__,\n `REE Radii Plot <../plotting/REE_v_radii.html>`__\n\n Functions:\n :func:`~pyrolite.mineral.lattice.strain_coefficient`,\n :func:`~pyrolite.mineral.lattice.youngs_modulus_approximation`,\n :func:`~pyrolite.geochem.get_ionic_radii`\n\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/geochem/mineral_lattice.py b/docs/source/examples/geochem/mineral_lattice.py deleted file mode 100644 index 898e0adb..00000000 --- a/docs/source/examples/geochem/mineral_lattice.py +++ /dev/null @@ -1,155 +0,0 @@ -""" -Lattice Strain Calculations ------------------------------- - -.. note:: - - This example follows that given during a Institute of Advanced Studies Masterclass - with Jon Blundy at the University of Western Australia on the 29\ :sup:`th` April - 2019, and is used here with permission. - - -Pyrolite includes a function for calculating relative lattice strain [#ref_1]_, which -together with the tables of Shannon ionic radii and Young's modulus approximations for -silicate and oxide cationic sites enable relatively simple calculation of ionic -partitioning in common rock forming minerals. - -This example below uses previously characterised calcium and sodium partition -coefficients between plagioclase (:math:`CaAl_2Si_2O_8 - NaAlSi_3O8`) and silicate melt -to estimate partitioning for other cations based on their ionic radii. - -A model parameterised using sodium and calcium partition coefficients [#ref_2]_ is then -used to estimate the partitioning for lanthanum into the trivalent site (largely -occupied by :math:`Al^{3+}`), and extended to other trivalent cations (here, the Rare -Earth Elements). The final section of the example highlights the mechanism which -generates plagioclase's hallmark 'europium anomaly', and the effects of variable -europium oxidation state on bulk europium partitioning. -""" -import numpy as np -import matplotlib.pyplot as plt -from pyrolite.geochem.ind import REE, get_ionic_radii -from pyrolite.mineral.lattice import strain_coefficient - -# sphinx_gallery_thumbnail_number = 3 -######################################################################################## -# First, we need to define some of the necessary parameters including temperature, the Young's -# moduli for the :math:`X^{2+}` and :math:`X^{3+}` sites in plagioclase (:math:`E_2`, -# :math:`E_3`), and some reference partition coefficients and radii for calcium and -# sodium: -D_Na = 1.35 # Partition coefficient Plag-Melt -D_Ca = 4.1 # Partition coefficient Plag-Melt -Tc = 900 # Temperature, °C -Tk = Tc + 273.15 # Temperature, K -E_2 = 120 * 10 ** 9 # Youngs modulus for 2+ site, Pa -E_3 = 135 * 10 ** 9 # Youngs modulus for 3+ site, Pa -r02, r03 = 1.196, 1.294 # fictive ideal cation radii for these sites -rCa = get_ionic_radii("Ca", charge=2, coordination=8) -rLa = get_ionic_radii("La", charge=3, coordination=8) -######################################################################################## -# We can calculate and plot the partitioning of :math:`X^{2+}` cations relative to -# :math:`Ca^{2+}` at a given temperature using their radii and the lattice strain function: -# -fontsize = 8 -fig, ax = plt.subplots(1) - -site2labels = ["Na", "Ca", "Eu", "Sr"] -# get the Shannon ionic radii for the elements in the 2+ site -site2radii = [ - get_ionic_radii("Na", charge=1, coordination=8), - *[get_ionic_radii(el, charge=2, coordination=8) for el in ["Ca", "Eu", "Sr"]], -] -# plot the relative paritioning curve for cations in the 2+ site -site2Ds = D_Ca * np.array( - [strain_coefficient(rCa, rx, r0=r02, E=E_2, T=Tk) for rx in site2radii] -) -ax.scatter(site2radii, site2Ds, color="g", label="$X^{2+}$ Cations") -# create an index of radii, and plot the relative paritioning curve for the site -xs = np.linspace(0.9, 1.3, 200) -curve2Ds = D_Ca * strain_coefficient(rCa, xs, r0=r02, E=E_2, T=Tk) -ax.plot(xs, curve2Ds, color="0.5", ls="--") -# add the element labels next to the points -for l, r, d in zip(site2labels, site2radii, site2Ds): - ax.annotate( - l, xy=(r, d), xycoords="data", ha="left", va="bottom", fontsize=fontsize - ) -fig -######################################################################################## -# When it comes to estimating the partitioning of :math:`X^{3+}` cations, we'll need a reference -# point - here we'll use :math:`D_{La}` to calculate relative partitioning of the other -# Rare Earth Elements, although you may have noticed it is not defined above. -# Through a handy relationship, we can estimate :math:`D_{La}` -# based on the easier measured :math:`D_{Ca}`, :math:`D_{Na}` and temperature [#ref_2]_: -# -D_La = (D_Ca ** 2 / D_Na) * np.exp((529 / Tk) - 3.705) -D_La # 0.48085 -######################################################################################## -# Now :math:`D_{La}` is defined, we can use it as a reference for the other REE: -# -site3labels = REE(dropPm=True) -# get the Shannon ionic radii for the elements in the 3+ site -site3radii = [get_ionic_radii(x, charge=3, coordination=8) for x in REE(dropPm=True)] -site3Ds = D_La * np.array( - [strain_coefficient(rLa, rx, r0=r03, E=E_3, T=Tk) for rx in site3radii] -) -# plot the relative paritioning curve for cations in the 3+ site -ax.scatter(site3radii, site3Ds, color="purple", label="$X^{3+}$ Cations") -# plot the relative paritioning curve for the site -curve3Ds = D_La * strain_coefficient(rLa, xs, r0=r03, E=E_3, T=Tk) -ax.plot(xs, curve3Ds, color="0.5", ls="--") -# add the element labels next to the points -for l, r, d in zip(site3labels, site3radii, site3Ds): - ax.annotate( - l, xy=(r, d), xycoords="data", ha="right", va="bottom", fontsize=fontsize - ) -ax.set_yscale("log") -ax.set_ylabel("$D_X$") -ax.set_xlabel("Radii ($\AA$)") -fig -######################################################################################## -# As europium is commonly present as a mixture of both :math:`Eu^{2+}` -# and :math:`Eu^{3+}`, the effective partitioning of Eu will be intermediate -# between that of :math:`D_{Eu^{2+}}`and :math:`D_{Eu^{3+}}`. Using a 60:40 mixture -# of :math:`Eu^{3+}` : :math:`Eu^{2+}` as an example, this effective partition -# coefficient can be calculated: -# -X_Eu3 = 0.6 -# calculate D_Eu3 relative to D_La -D_Eu3 = D_La * strain_coefficient( - rLa, get_ionic_radii("Eu", charge=3, coordination=8), r0=r03, E=E_3, T=Tk -) -# calculate D_Eu2 relative to D_Ca -D_Eu2 = D_Ca * strain_coefficient( - rCa, get_ionic_radii("Eu", charge=2, coordination=8), r0=r02, E=E_2, T=Tk -) -# calculate the effective parition coefficient -D_Eu = (1 - X_Eu3) * D_Eu2 + X_Eu3 * D_Eu3 -# show the effective partition coefficient relative to the 2+ and 3+ endmembers -radii, ds = ( - [get_ionic_radii("Eu", charge=c, coordination=8) for c in [3, 3, 2, 2]], - [D_Eu3, D_Eu, D_Eu, D_Eu2], -) -ax.plot( - radii, ds, ls="--", color="0.9", marker="D", label="Effective $D_{Eu}$", zorder=-1 -) -ax.legend(loc="upper left", bbox_to_anchor=(1.05, 1), frameon=False, facecolor=None) -fig -######################################################################################## -# .. [#ref_1] Blundy, J., Wood, B., 1994. Prediction of crystal–melt partition coefficients -# from elastic moduli. Nature 372, 452. -# doi: `10.1038/372452A0 `__ -# -# .. [#ref_2] Dohmen, R., Blundy, J., 2014. A predictive thermodynamic model for element partitioning -# between plagioclase and melt as a function of pressure, temperature and composition. -# American Journal of Science 314, 1319–1372. -# doi: `10.2475/09.2014.04 `__ -# -# .. seealso:: -# -# Examples: -# `Shannon Radii <../indexes/shannon.html>`__, -# `REE Radii Plot <../plotting/REE_v_radii.html>`__ -# -# Functions: -# :func:`~pyrolite.mineral.lattice.strain_coefficient`, -# :func:`~pyrolite.mineral.lattice.youngs_modulus_approximation`, -# :func:`~pyrolite.geochem.get_ionic_radii` diff --git a/docs/source/examples/geochem/mineral_lattice.py.md5 b/docs/source/examples/geochem/mineral_lattice.py.md5 deleted file mode 100644 index 00d29a90..00000000 --- a/docs/source/examples/geochem/mineral_lattice.py.md5 +++ /dev/null @@ -1 +0,0 @@ -332bf926e1b7c028307e33717c89d8b6 \ No newline at end of file diff --git a/docs/source/examples/geochem/mineral_lattice.rst b/docs/source/examples/geochem/mineral_lattice.rst deleted file mode 100644 index c0598f05..00000000 --- a/docs/source/examples/geochem/mineral_lattice.rst +++ /dev/null @@ -1,297 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_geochem_mineral_lattice.py: - - -Lattice Strain Calculations ------------------------------- - -.. note:: - - This example follows that given during a Institute of Advanced Studies Masterclass - with Jon Blundy at the University of Western Australia on the 29\ :sup:`th` April - 2019, and is used here with permission. - - -Pyrolite includes a function for calculating relative lattice strain [#ref_1]_, which -together with the tables of Shannon ionic radii and Young's modulus approximations for -silicate and oxide cationic sites enable relatively simple calculation of ionic -partitioning in common rock forming minerals. - -This example below uses previously characterised calcium and sodium partition -coefficients between plagioclase (:math:`CaAl_2Si_2O_8 - NaAlSi_3O8`) and silicate melt -to estimate partitioning for other cations based on their ionic radii. - -A model parameterised using sodium and calcium partition coefficients [#ref_2]_ is then -used to estimate the partitioning for lanthanum into the trivalent site (largely -occupied by :math:`Al^{3+}`), and extended to other trivalent cations (here, the Rare -Earth Elements). The final section of the example highlights the mechanism which -generates plagioclase's hallmark 'europium anomaly', and the effects of variable -europium oxidation state on bulk europium partitioning. - - -.. code-block:: default - - import numpy as np - import matplotlib.pyplot as plt - from pyrolite.geochem.ind import REE, get_ionic_radii - from pyrolite.mineral.lattice import strain_coefficient - - - - - - - - -First, we need to define some of the necessary parameters including temperature, the Young's -moduli for the :math:`X^{2+}` and :math:`X^{3+}` sites in plagioclase (:math:`E_2`, -:math:`E_3`), and some reference partition coefficients and radii for calcium and -sodium: - - -.. code-block:: default - - D_Na = 1.35 # Partition coefficient Plag-Melt - D_Ca = 4.1 # Partition coefficient Plag-Melt - Tc = 900 # Temperature, °C - Tk = Tc + 273.15 # Temperature, K - E_2 = 120 * 10 ** 9 # Youngs modulus for 2+ site, Pa - E_3 = 135 * 10 ** 9 # Youngs modulus for 3+ site, Pa - r02, r03 = 1.196, 1.294 # fictive ideal cation radii for these sites - rCa = get_ionic_radii("Ca", charge=2, coordination=8) - rLa = get_ionic_radii("La", charge=3, coordination=8) - - - - - - - -We can calculate and plot the partitioning of :math:`X^{2+}` cations relative to -:math:`Ca^{2+}` at a given temperature using their radii and the lattice strain function: - - - -.. code-block:: default - - fontsize = 8 - fig, ax = plt.subplots(1) - - site2labels = ["Na", "Ca", "Eu", "Sr"] - # get the Shannon ionic radii for the elements in the 2+ site - site2radii = [ - get_ionic_radii("Na", charge=1, coordination=8), - *[get_ionic_radii(el, charge=2, coordination=8) for el in ["Ca", "Eu", "Sr"]], - ] - # plot the relative paritioning curve for cations in the 2+ site - site2Ds = D_Ca * np.array( - [strain_coefficient(rCa, rx, r0=r02, E=E_2, T=Tk) for rx in site2radii] - ) - ax.scatter(site2radii, site2Ds, color="g", label="$X^{2+}$ Cations") - # create an index of radii, and plot the relative paritioning curve for the site - xs = np.linspace(0.9, 1.3, 200) - curve2Ds = D_Ca * strain_coefficient(rCa, xs, r0=r02, E=E_2, T=Tk) - ax.plot(xs, curve2Ds, color="0.5", ls="--") - # add the element labels next to the points - for l, r, d in zip(site2labels, site2radii, site2Ds): - ax.annotate( - l, xy=(r, d), xycoords="data", ha="left", va="bottom", fontsize=fontsize - ) - fig - - - -.. image:: /examples/geochem/images/sphx_glr_mineral_lattice_001.png - :class: sphx-glr-single-img - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - -
- - - -When it comes to estimating the partitioning of :math:`X^{3+}` cations, we'll need a reference -point - here we'll use :math:`D_{La}` to calculate relative partitioning of the other -Rare Earth Elements, although you may have noticed it is not defined above. -Through a handy relationship, we can estimate :math:`D_{La}` -based on the easier measured :math:`D_{Ca}`, :math:`D_{Na}` and temperature [#ref_2]_: - - - -.. code-block:: default - - D_La = (D_Ca ** 2 / D_Na) * np.exp((529 / Tk) - 3.705) - D_La # 0.48085 - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - 0.48084614946362086 - - - -Now :math:`D_{La}` is defined, we can use it as a reference for the other REE: - - - -.. code-block:: default - - site3labels = REE(dropPm=True) - # get the Shannon ionic radii for the elements in the 3+ site - site3radii = [get_ionic_radii(x, charge=3, coordination=8) for x in REE(dropPm=True)] - site3Ds = D_La * np.array( - [strain_coefficient(rLa, rx, r0=r03, E=E_3, T=Tk) for rx in site3radii] - ) - # plot the relative paritioning curve for cations in the 3+ site - ax.scatter(site3radii, site3Ds, color="purple", label="$X^{3+}$ Cations") - # plot the relative paritioning curve for the site - curve3Ds = D_La * strain_coefficient(rLa, xs, r0=r03, E=E_3, T=Tk) - ax.plot(xs, curve3Ds, color="0.5", ls="--") - # add the element labels next to the points - for l, r, d in zip(site3labels, site3radii, site3Ds): - ax.annotate( - l, xy=(r, d), xycoords="data", ha="right", va="bottom", fontsize=fontsize - ) - ax.set_yscale("log") - ax.set_ylabel("$D_X$") - ax.set_xlabel("Radii ($\AA$)") - fig - - - -.. image:: /examples/geochem/images/sphx_glr_mineral_lattice_002.png - :class: sphx-glr-single-img - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - -
- - - -As europium is commonly present as a mixture of both :math:`Eu^{2+}` -and :math:`Eu^{3+}`, the effective partitioning of Eu will be intermediate -between that of :math:`D_{Eu^{2+}}`and :math:`D_{Eu^{3+}}`. Using a 60:40 mixture -of :math:`Eu^{3+}` : :math:`Eu^{2+}` as an example, this effective partition -coefficient can be calculated: - - - -.. code-block:: default - - X_Eu3 = 0.6 - # calculate D_Eu3 relative to D_La - D_Eu3 = D_La * strain_coefficient( - rLa, get_ionic_radii("Eu", charge=3, coordination=8), r0=r03, E=E_3, T=Tk - ) - # calculate D_Eu2 relative to D_Ca - D_Eu2 = D_Ca * strain_coefficient( - rCa, get_ionic_radii("Eu", charge=2, coordination=8), r0=r02, E=E_2, T=Tk - ) - # calculate the effective parition coefficient - D_Eu = (1 - X_Eu3) * D_Eu2 + X_Eu3 * D_Eu3 - # show the effective partition coefficient relative to the 2+ and 3+ endmembers - radii, ds = ( - [get_ionic_radii("Eu", charge=c, coordination=8) for c in [3, 3, 2, 2]], - [D_Eu3, D_Eu, D_Eu, D_Eu2], - ) - ax.plot( - radii, ds, ls="--", color="0.9", marker="D", label="Effective $D_{Eu}$", zorder=-1 - ) - ax.legend(loc="upper left", bbox_to_anchor=(1.05, 1), frameon=False, facecolor=None) - fig - - - -.. image:: /examples/geochem/images/sphx_glr_mineral_lattice_003.png - :class: sphx-glr-single-img - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - -
- - - -.. [#ref_1] Blundy, J., Wood, B., 1994. Prediction of crystal–melt partition coefficients - from elastic moduli. Nature 372, 452. - doi: `10.1038/372452A0 `__ - -.. [#ref_2] Dohmen, R., Blundy, J., 2014. A predictive thermodynamic model for element partitioning - between plagioclase and melt as a function of pressure, temperature and composition. - American Journal of Science 314, 1319–1372. - doi: `10.2475/09.2014.04 `__ - -.. seealso:: - - Examples: - `Shannon Radii <../indexes/shannon.html>`__, - `REE Radii Plot <../plotting/REE_v_radii.html>`__ - - Functions: - :func:`~pyrolite.mineral.lattice.strain_coefficient`, - :func:`~pyrolite.mineral.lattice.youngs_modulus_approximation`, - :func:`~pyrolite.geochem.get_ionic_radii` - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 1.104 seconds) - - -.. _sphx_glr_download_examples_geochem_mineral_lattice.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/geochem/mineral_lattice.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: mineral_lattice.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: mineral_lattice.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/geochem/mineral_lattice_codeobj.pickle b/docs/source/examples/geochem/mineral_lattice_codeobj.pickle deleted file mode 100644 index 0c7b0de1..00000000 Binary files a/docs/source/examples/geochem/mineral_lattice_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/geochem/mineral_mindb.ipynb b/docs/source/examples/geochem/mineral_mindb.ipynb deleted file mode 100644 index e5df6207..00000000 --- a/docs/source/examples/geochem/mineral_mindb.ipynb +++ /dev/null @@ -1,130 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nMineral Database\n====================\n\npyrolite includes a limited mineral database which is useful for\nfor looking up endmember compositions. This part of the package is being actively\ndeveloped, so expect expansions and improvements soon.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pandas as pd\nfrom pyrolite.mineral.mindb import (\n list_groups,\n list_minerals,\n list_formulae,\n get_mineral,\n get_mineral_group,\n)\n\npd.set_option(\"precision\", 3) # smaller outputs" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "From the database, you can get the list of its contents using a few utility\nfunctions:\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "list_groups()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "list_minerals()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "list_formulae()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You can also directly get the composition of specific minerals by name:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "get_mineral(\"forsterite\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If you want to get compositions for all minerals within a specific group, you can\nuse :func:`~pyrolite.mineral.mindb.get_mineral_group`:\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "get_mineral_group(\"olivine\")" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/geochem/mineral_mindb.py b/docs/source/examples/geochem/mineral_mindb.py deleted file mode 100644 index f02921cd..00000000 --- a/docs/source/examples/geochem/mineral_mindb.py +++ /dev/null @@ -1,34 +0,0 @@ -""" -Mineral Database -==================== - -pyrolite includes a limited mineral database which is useful for -for looking up endmember compositions. This part of the package is being actively -developed, so expect expansions and improvements soon. -""" -import pandas as pd -from pyrolite.mineral.mindb import ( - list_groups, - list_minerals, - list_formulae, - get_mineral, - get_mineral_group, -) - -pd.set_option("precision", 3) # smaller outputs -######################################################################################## -# From the database, you can get the list of its contents using a few utility -# functions: -list_groups() -######################################################################################## -list_minerals() -######################################################################################## -list_formulae() -######################################################################################## -# You can also directly get the composition of specific minerals by name: -# -get_mineral("forsterite") -######################################################################################## -# If you want to get compositions for all minerals within a specific group, you can -# use :func:`~pyrolite.mineral.mindb.get_mineral_group`: -get_mineral_group("olivine") diff --git a/docs/source/examples/geochem/mineral_mindb.py.md5 b/docs/source/examples/geochem/mineral_mindb.py.md5 deleted file mode 100644 index c0fe74b0..00000000 --- a/docs/source/examples/geochem/mineral_mindb.py.md5 +++ /dev/null @@ -1 +0,0 @@ -5055145435bf4c03771dd73c0fb9e589 \ No newline at end of file diff --git a/docs/source/examples/geochem/mineral_mindb.rst b/docs/source/examples/geochem/mineral_mindb.rst deleted file mode 100644 index 288df65a..00000000 --- a/docs/source/examples/geochem/mineral_mindb.rst +++ /dev/null @@ -1,269 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_geochem_mineral_mindb.py: - - -Mineral Database -==================== - -pyrolite includes a limited mineral database which is useful for -for looking up endmember compositions. This part of the package is being actively -developed, so expect expansions and improvements soon. - - -.. code-block:: default - - import pandas as pd - from pyrolite.mineral.mindb import ( - list_groups, - list_minerals, - list_formulae, - get_mineral, - get_mineral_group, - ) - - pd.set_option("precision", 3) # smaller outputs - - - - - - - -From the database, you can get the list of its contents using a few utility -functions: - - -.. code-block:: default - - list_groups() - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['amphibole', 'pyroxene', 'mica', 'olivine', 'spinel', 'garnet', 'epidote', 'feldspar'] - - - - -.. code-block:: default - - list_minerals() - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['esseneite', 'anthopyllite', 'allanite', 'fayalite', 'taramite', 'kaersutite', 'ferrotschermakite', 'ferroedenite', 'eastonite', 'polylithionite', 'chromoceladonite', 'ferrosilite', 'hedenbergite', 'winchite', 'spodumene', 'ferropargasite', 'chromite', 'namansilite', 'tremolite', 'grossular', 'piemontite', 'riebeckite', 'anorthite', 'eckermanite', 'spessartine', 'pargasite', 'magnesiohastingsite', 'magnesiochromite', 'manganiceladonite', 'diopside', 'magnetite', 'edenite', 'celadonite', 'siderophyllite', 'richterite', 'ferrokaersutite', 'aluminoceladonite', 'katophorite', 'liebenbergite', 'tschermakite', 'ferroceladonite', 'margarite', 'phengite', 'barroisite', 'ferroaluminoceladonite', 'epidote', 'microcline', 'ferrorichterite', 'majorite', 'phlogopite', 'glaucophane', 'magnesioreibeckite', 'albite', 'forsterite', 'hercynite', 'chromphyllite', 'jadeite', 'morimotoite', 'magnesioarfvedsonite', 'magnesiohornblende', 'ferroeckermanite', 'enstatite', 'spinel', 'hastingsite', 'ferrokatophorite', 'uvarovite', 'muscovite', 'trilithionite', 'arvedsonite', 'almandine', 'kosmochlor', 'magnesioferrite', 'clinozoisite', 'pyrope', 'ferrohornblende', 'aegirine', 'annite', 'paragonite', 'tephroite', 'gedrite', 'johannsenite', 'andradite', 'clintonite'] - - - - -.. code-block:: default - - list_formulae() - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['(Ca2)(Mg5)(Si8)O22(OH)2', 'Ca3Al2(SiO4)3', 'Na(Ca2)(Mg5)(Si7Al)O22(OH)2', 'Mn3Al2(SiO4)3', 'Fe{2+}Al2O4', 'Na(Ca2)(Fe5)(Si7Al)O22(OH)2', 'Na(Ca2)(Fe4Al)(Si6Al2)O22(OH)2', 'K2(Mg2Cr{3+}2)(Si8)O20(OH)4', 'Na(Na2)(Mg4Fe{3+})(Si8)O22(OH)2', 'CaFeSi2O6', 'NaAlSi3O8', 'Na(Ca2)(Mg4Al)(Si6Al2)O22(OH)2', '(Ca2)(Fe4Al)(Si7Al)O22(OH)2', 'Ca2Al2Fe{3+}(Si2O7)(SiO4)O(OH)', '(Ca2)(Mg4Al)(Si7Al)O22(OH)2', 'NaFe{3+}Si2O6', 'Na(NaCa)(Mg5)(Si8)O22(OH)2', 'Na(Na2)(Mg4Al)(Si8)O22(OH)2', 'CaAl2Si2O8', 'MgFe{3+}2O4', 'Ca2Al2Mn{3+}(Si2O7)(SiO4)O(OH)', 'NaMn{3+}Si2O6', 'K2(Al3Li3)(Si6Al2)O20(OH)4', 'Na(Na2)(Fe4Al)(Si8)O22(OH)2', 'Mn2SiO4', 'Ca3Fe{3+}2(SiO4)3', 'Ca2(Mg4Al2)(Si2Al6)O20(OH)4', 'Na2(Al4)(Si6Al2)O20(OH)4', 'K2(Fe{3+}2Mg2)(Si8)O20(OH)4', 'Mg2Si2O6', '(Ca2)(Fe3Al2)(Si6Al2)O22(OH)2', 'KAlSi3O8', 'Na(Na2)(Fe{2+}4Fe{3+})(Si8)O22(OH)2', 'K2(Mn{3+}2Mg2)(Si8)O20(OH)4', 'Na(NaCa)(Fe4Al)(Si7Al)O22(OH)2', 'Fe{2+}Cr{3+}2O4', 'Na(NaCa)(Fe5)(Si8)O22(OH)2', 'K2(Cr{3+}4)(Si6Al2)O20(OH)4', 'K2(Mg2Al2)(Si8)O20(OH)4', 'K2(Al3Mg)(Si7Al)O20(OH)4', 'Fe2SiO4', 'NaCrSi2O6', 'Mg3Al2(SiO4)3', 'K2(Mg4)(Si4Al6)O20(OH)4', 'LiAlSi2O6', 'Na(NaCa)(Mg4Al)(Si7Al)O22(OH)2', 'Mg2SiO4', 'NaAlSi2O6', 'CaMnSi2O6', 'Fe{2+}Fe{3+}2O4', 'Fe2Si2O6', 'K2(Fe{3+}2Fe{2+}2)(Si8)O20(OH)4', '(Ca2)(Mg3Al2)(Si6Al2)O22(OH)2', 'Ca2(Al4)(Si4Al4)O20(OH)4', 'Na(Ca2)(Fe4Ti)(Si6Al2)O22(OH)2', 'Na(Ca2)(Fe{2+}4Fe{3+})(Si6Al2)O22(OH)2', 'MgCr{3+}2O4', 'Ca2Al3(Si2O7)(SiO4)O(OH)', 'CaAlFe{3+}SiO6', 'K2(Al2Li2)(Si8)O20(OH)4', '(Na2)(Mg3Fe{3+}2)(Si8)O22(OH)2', 'K2(Fe{2+}6)(Si6Al2)O20(OH)4', 'Na(Ca2)(Mg4Fe{3+})(Si6Al2)O22(OH)2', 'K2(Fe{2+}4)(Si4Al6)O20(OH)4', '(NaCa)(Mg3Al2)(Si7Al)O22(OH)2', '(NaCa)(Mg4Al)(Si8)O22(OH)2', 'MgAl2O4', 'Ca3Cr2(SiO4)3', 'Ca3(TiFe{2+})(SiO4)3', 'Na(Ca2)(Mg4Ti)(Si6Al2)O22(OH)2', '(Mg2)(Mg5)(Si8)O22(OH)2', '(Na2)(Fe3Fe{3+}2)(Si8)O22(OH)2', 'K2(Al4)(Si6Al2)O20(OH)4', 'Ni1.5Mg0.5SiO4', 'CaMgSi2O6', '(Na2)(Mg3Al2)(Si8)O22(OH)2', 'K2(Fe{2+}2Al2)(Si8)O20(OH)4', 'CaCe{3+}Al2Fe{2+}(Si2O7)(SiO4)O(OH)', 'Fe{2+}3Al2(SiO4)3', 'Mg3(MgSi)(SiO4)3', 'K2(Mg6)(Si6Al2)O20(OH)4', '(Mg2)(Mg3Al2)(Si6Al2)O22(OH)2', 'Na(NaCa)(Mg3Al2)(Si6Al2)O22(OH)2'] - - - -You can also directly get the composition of specific minerals by name: - - - -.. code-block:: default - - get_mineral("forsterite") - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - name forsterite - group olivine - formula Mg2SiO4 - Mg 0.346 - Si 0.2 - O 0.455 - Fe 0 - Mn 0 - Ni 0 - Ca 0 - Al 0 - Fe{3+} 0 - Na 0 - Mn{3+} 0 - Cr 0 - Li 0 - Cr{3+} 0 - Fe{2+} 0 - K 0 - H 0 - Ti 0 - Ce{3+} 0 - dtype: object - - - -If you want to get compositions for all minerals within a specific group, you can -use :func:`~pyrolite.mineral.mindb.get_mineral_group`: - - -.. code-block:: default - - get_mineral_group("olivine") - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
nameformulaMgSiOFeMnNi
0forsteriteMg2SiO40.3460.2000.4550.0000.0000.000
1fayaliteFe2SiO40.0000.1380.3140.5480.0000.000
2tephroiteMn2SiO40.0000.1390.3170.0000.5440.000
3liebenbergiteNi1.5Mg0.5SiO40.0630.1460.3330.0000.0000.458
-
-
-
- - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 0.051 seconds) - - -.. _sphx_glr_download_examples_geochem_mineral_mindb.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/geochem/mineral_mindb.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: mineral_mindb.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: mineral_mindb.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/geochem/mineral_mindb_codeobj.pickle b/docs/source/examples/geochem/mineral_mindb_codeobj.pickle deleted file mode 100644 index 3709b0ca..00000000 Binary files a/docs/source/examples/geochem/mineral_mindb_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/geochem/normalization.ipynb b/docs/source/examples/geochem/normalization.ipynb deleted file mode 100644 index 288f3a09..00000000 --- a/docs/source/examples/geochem/normalization.ipynb +++ /dev/null @@ -1,108 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nNormalization\n==============\n\nA selection of reference compositions are included in pyrolite, and can be easily\naccessed with :func:`pyrolite.geochem.norm.get_reference_composition` (see the list\nat the bottom of the page for a complete list):\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pandas as pd\nimport matplotlib.pyplot as plt\nimport pyrolite.plot\nfrom pyrolite.geochem.ind import REE\nfrom pyrolite.geochem.norm import get_reference_composition, all_reference_compositions" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "chondrite = get_reference_composition(\"Chondrite_PON\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To use the compositions with a specific set of units, you can change them with\n:func:`~pyrolite.geochem.norm.Composition.set_units`:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "CI = chondrite.set_units(\"ppm\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The :func:`~pyrolite.geochem.pyrochem.normalize_to` method can be used to\nnormalise DataFrames to a given reference (e.g. for spiderplots):\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(1)\n\nfor name, ref in list(all_reference_compositions().items())[::2]:\n if name != \"Chondrite_PON\":\n ref.set_units(\"ppm\")\n df = ref.comp.pyrochem.REE.pyrochem.normalize_to(CI, units=\"ppm\")\n df.pyroplot.REE(unity_line=True, ax=ax, label=name)\n\nax.set_ylabel(\"X/X$_{Chondrite}$\")\nax.legend(frameon=False, facecolor=None, loc=\"upper left\", bbox_to_anchor=(1.0, 1.0))\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ".. seealso::\n\n Examples:\n `lambdas: Parameterising REE Profiles `__,\n `REE Radii Plot <../plotting/REE_radii_plot.html>`__\n\nCurrently available models include:\n\n|refcomps|\n\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/geochem/normalization.py b/docs/source/examples/geochem/normalization.py deleted file mode 100644 index 6f0579da..00000000 --- a/docs/source/examples/geochem/normalization.py +++ /dev/null @@ -1,46 +0,0 @@ -""" -Normalization -============== - -A selection of reference compositions are included in pyrolite, and can be easily -accessed with :func:`pyrolite.geochem.norm.get_reference_composition` (see the list -at the bottom of the page for a complete list): -""" -import pandas as pd -import matplotlib.pyplot as plt -import pyrolite.plot -from pyrolite.geochem.ind import REE -from pyrolite.geochem.norm import get_reference_composition, all_reference_compositions - -######################################################################################## -chondrite = get_reference_composition("Chondrite_PON") -######################################################################################## -# To use the compositions with a specific set of units, you can change them with -# :func:`~pyrolite.geochem.norm.Composition.set_units`: -# -CI = chondrite.set_units("ppm") -######################################################################################### -# The :func:`~pyrolite.geochem.pyrochem.normalize_to` method can be used to -# normalise DataFrames to a given reference (e.g. for spiderplots): -# -fig, ax = plt.subplots(1) - -for name, ref in list(all_reference_compositions().items())[::2]: - if name != "Chondrite_PON": - ref.set_units("ppm") - df = ref.comp.pyrochem.REE.pyrochem.normalize_to(CI, units="ppm") - df.pyroplot.REE(unity_line=True, ax=ax, label=name) - -ax.set_ylabel("X/X$_{Chondrite}$") -ax.legend(frameon=False, facecolor=None, loc="upper left", bbox_to_anchor=(1.0, 1.0)) -plt.show() -######################################################################################## -# .. seealso:: -# -# Examples: -# `lambdas: Parameterising REE Profiles `__, -# `REE Radii Plot <../plotting/REE_radii_plot.html>`__ -# -# Currently available models include: -# -# |refcomps| diff --git a/docs/source/examples/geochem/normalization.py.md5 b/docs/source/examples/geochem/normalization.py.md5 deleted file mode 100644 index a138f416..00000000 --- a/docs/source/examples/geochem/normalization.py.md5 +++ /dev/null @@ -1 +0,0 @@ -56a97f8c52ac11025ab16112f4fcdc69 \ No newline at end of file diff --git a/docs/source/examples/geochem/normalization.rst b/docs/source/examples/geochem/normalization.rst deleted file mode 100644 index d1f431ea..00000000 --- a/docs/source/examples/geochem/normalization.rst +++ /dev/null @@ -1,130 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_geochem_normalization.py: - - -Normalization -============== - -A selection of reference compositions are included in pyrolite, and can be easily -accessed with :func:`pyrolite.geochem.norm.get_reference_composition` (see the list -at the bottom of the page for a complete list): - - -.. code-block:: default - - import pandas as pd - import matplotlib.pyplot as plt - import pyrolite.plot - from pyrolite.geochem.ind import REE - from pyrolite.geochem.norm import get_reference_composition, all_reference_compositions - - - - - - - - - -.. code-block:: default - - chondrite = get_reference_composition("Chondrite_PON") - - - - - - - -To use the compositions with a specific set of units, you can change them with -:func:`~pyrolite.geochem.norm.Composition.set_units`: - - - -.. code-block:: default - - CI = chondrite.set_units("ppm") - - - - - - - -The :func:`~pyrolite.geochem.pyrochem.normalize_to` method can be used to -normalise DataFrames to a given reference (e.g. for spiderplots): - - - -.. code-block:: default - - fig, ax = plt.subplots(1) - - for name, ref in list(all_reference_compositions().items())[::2]: - if name != "Chondrite_PON": - ref.set_units("ppm") - df = ref.comp.pyrochem.REE.pyrochem.normalize_to(CI, units="ppm") - df.pyroplot.REE(unity_line=True, ax=ax, label=name) - - ax.set_ylabel("X/X$_{Chondrite}$") - ax.legend(frameon=False, facecolor=None, loc="upper left", bbox_to_anchor=(1.0, 1.0)) - plt.show() - - - -.. image:: /examples/geochem/images/sphx_glr_normalization_001.png - :class: sphx-glr-single-img - - - - - -.. seealso:: - - Examples: - `lambdas: Parameterising REE Profiles `__, - `REE Radii Plot <../plotting/REE_radii_plot.html>`__ - -Currently available models include: - -|refcomps| - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 3.141 seconds) - - -.. _sphx_glr_download_examples_geochem_normalization.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/geochem/normalization.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: normalization.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: normalization.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/geochem/normalization_codeobj.pickle b/docs/source/examples/geochem/normalization_codeobj.pickle deleted file mode 100644 index 5c74fb73..00000000 Binary files a/docs/source/examples/geochem/normalization_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/geochem/scaling.ipynb b/docs/source/examples/geochem/scaling.ipynb deleted file mode 100644 index ea1c6922..00000000 --- a/docs/source/examples/geochem/scaling.ipynb +++ /dev/null @@ -1,76 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nUnit Scaling\n=============\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.geochem\nimport pandas as pd\n\npd.set_option(\"precision\", 3) # smaller outputs" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.synthetic import test_df\n\ndf = test_df(cols=['CaO', 'MgO', 'SiO2', 'FeO', 'Ni', 'Ti', 'La', 'Lu', 'Mg/Fe'])" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "cols = [\"Ni\", \"NiO\", \"La\", \"La2O3\"]\ndf.head(2).pyrochem.convert_chemistry(to=cols)[cols] # these are in ppm!" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/geochem/scaling.py b/docs/source/examples/geochem/scaling.py deleted file mode 100644 index db6ba805..00000000 --- a/docs/source/examples/geochem/scaling.py +++ /dev/null @@ -1,15 +0,0 @@ -""" -Unit Scaling -============= -""" -import pyrolite.geochem -import pandas as pd - -pd.set_option("precision", 3) # smaller outputs -######################################################################################## -from pyrolite.util.synthetic import test_df - -df = test_df(cols=['CaO', 'MgO', 'SiO2', 'FeO', 'Ni', 'Ti', 'La', 'Lu', 'Mg/Fe']) -######################################################################################## -cols = ["Ni", "NiO", "La", "La2O3"] -df.head(2).pyrochem.convert_chemistry(to=cols)[cols] # these are in ppm! diff --git a/docs/source/examples/geochem/scaling.py.md5 b/docs/source/examples/geochem/scaling.py.md5 deleted file mode 100644 index 146f969c..00000000 --- a/docs/source/examples/geochem/scaling.py.md5 +++ /dev/null @@ -1 +0,0 @@ -3e8d731b5780be34894f3cfaeb7af158 \ No newline at end of file diff --git a/docs/source/examples/geochem/scaling.rst b/docs/source/examples/geochem/scaling.rst deleted file mode 100644 index 974eb957..00000000 --- a/docs/source/examples/geochem/scaling.rst +++ /dev/null @@ -1,132 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_geochem_scaling.py: - - -Unit Scaling -============= - - -.. code-block:: default - - import pyrolite.geochem - import pandas as pd - - pd.set_option("precision", 3) # smaller outputs - - - - - - - - -.. code-block:: default - - from pyrolite.util.synthetic import test_df - - df = test_df(cols=['CaO', 'MgO', 'SiO2', 'FeO', 'Ni', 'Ti', 'La', 'Lu', 'Mg/Fe']) - - - - - - - - -.. code-block:: default - - cols = ["Ni", "NiO", "La", "La2O3"] - df.head(2).pyrochem.convert_chemistry(to=cols)[cols] # these are in ppm! - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
NiNiOLaLa2O3
00.6440.8200.0040.005
10.6500.8270.0040.004
-
-
-
- - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 0.084 seconds) - - -.. _sphx_glr_download_examples_geochem_scaling.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/geochem/scaling.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: scaling.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: scaling.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/geochem/scaling_codeobj.pickle b/docs/source/examples/geochem/scaling_codeobj.pickle deleted file mode 100644 index 87e141cc..00000000 Binary files a/docs/source/examples/geochem/scaling_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/geochem/sg_execution_times.rst b/docs/source/examples/geochem/sg_execution_times.rst deleted file mode 100644 index cb551b35..00000000 --- a/docs/source/examples/geochem/sg_execution_times.rst +++ /dev/null @@ -1,28 +0,0 @@ - -:orphan: - -.. _sphx_glr_examples_geochem_sg_execution_times: - -Computation times -================= -**00:03.141** total execution time for **examples_geochem** files: - -+------------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_geochem_normalization.py` (``normalization.py``) | 00:03.141 | 0.0 MB | -+------------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_geochem_convert_chemistry.py` (``convert_chemistry.py``) | 00:00.000 | 0.0 MB | -+------------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_geochem_indexes_selectors.py` (``indexes_selectors.py``) | 00:00.000 | 0.0 MB | -+------------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_geochem_ionic_radii.py` (``ionic_radii.py``) | 00:00.000 | 0.0 MB | -+------------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_geochem_lambdas.py` (``lambdas.py``) | 00:00.000 | 0.0 MB | -+------------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_geochem_mineral_endmembers.py` (``mineral_endmembers.py``) | 00:00.000 | 0.0 MB | -+------------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_geochem_mineral_lattice.py` (``mineral_lattice.py``) | 00:00.000 | 0.0 MB | -+------------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_geochem_mineral_mindb.py` (``mineral_mindb.py``) | 00:00.000 | 0.0 MB | -+------------------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_geochem_scaling.py` (``scaling.py``) | 00:00.000 | 0.0 MB | -+------------------------------------------------------------------------------------+-----------+--------+ diff --git a/docs/source/examples/index.rst b/docs/source/examples/index.rst deleted file mode 100644 index 02a5d149..00000000 --- a/docs/source/examples/index.rst +++ /dev/null @@ -1,542 +0,0 @@ -:orphan: - - - -.. _sphx_glr_examples: - -Examples -================== - -This example gallery includes a variety of examples for using pyrolite -which you can copy, download and alter, or run on Binder. - - -.. raw:: html - -
- - - -.. _sphx_glr_examples_plotting: - -Plotting Examples -~~~~~~~~~~~~~~~~~~~~ - -pyrolite provides some functionality for basic plotting of geochemical data in the form -of spidergrams (pyrolite.plot.spider), ternary diagrams (pyrolite.plot.tern) and -density diagrams (i.e. 2D histograms, pyrolite.plot.density). - - - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/plotting/images/thumb/sphx_glr_templates_thumb.png - - :ref:`sphx_glr_examples_plotting_templates.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/plotting/templates - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/plotting/images/thumb/sphx_glr_stem_thumb.png - - :ref:`sphx_glr_examples_plotting_stem.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/plotting/stem - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/plotting/images/thumb/sphx_glr_ternary_thumb.png - - :ref:`sphx_glr_examples_plotting_ternary.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/plotting/ternary - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/plotting/images/thumb/sphx_glr_REE_v_radii_thumb.png - - :ref:`sphx_glr_examples_plotting_REE_v_radii.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/plotting/REE_v_radii - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/plotting/images/thumb/sphx_glr_manifold_vis_thumb.png - - :ref:`sphx_glr_examples_plotting_manifold_vis.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/plotting/manifold_vis - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/plotting/images/thumb/sphx_glr_parallel_thumb.png - - :ref:`sphx_glr_examples_plotting_parallel.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/plotting/parallel - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/plotting/images/thumb/sphx_glr_heatscatter_thumb.png - - :ref:`sphx_glr_examples_plotting_heatscatter.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/plotting/heatscatter - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/plotting/images/thumb/sphx_glr_spider_thumb.png - - :ref:`sphx_glr_examples_plotting_spider.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/plotting/spider - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/plotting/images/thumb/sphx_glr_density_thumb.png - - :ref:`sphx_glr_examples_plotting_density.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/plotting/density -.. raw:: html - -
- - - -.. _sphx_glr_examples_geochem: - -Geochemistry Examples -~~~~~~~~~~~~~~~~~~~~~ - - - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/geochem/images/thumb/sphx_glr_mineral_mindb_thumb.png - - :ref:`sphx_glr_examples_geochem_mineral_mindb.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/geochem/mineral_mindb - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/geochem/images/thumb/sphx_glr_scaling_thumb.png - - :ref:`sphx_glr_examples_geochem_scaling.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/geochem/scaling - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/geochem/images/thumb/sphx_glr_convert_chemistry_thumb.png - - :ref:`sphx_glr_examples_geochem_convert_chemistry.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/geochem/convert_chemistry - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/geochem/images/thumb/sphx_glr_indexes_selectors_thumb.png - - :ref:`sphx_glr_examples_geochem_indexes_selectors.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/geochem/indexes_selectors - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/geochem/images/thumb/sphx_glr_normalization_thumb.png - - :ref:`sphx_glr_examples_geochem_normalization.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/geochem/normalization - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/geochem/images/thumb/sphx_glr_lambdas_thumb.png - - :ref:`sphx_glr_examples_geochem_lambdas.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/geochem/lambdas - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/geochem/images/thumb/sphx_glr_mineral_endmembers_thumb.png - - :ref:`sphx_glr_examples_geochem_mineral_endmembers.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/geochem/mineral_endmembers - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/geochem/images/thumb/sphx_glr_ionic_radii_thumb.png - - :ref:`sphx_glr_examples_geochem_ionic_radii.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/geochem/ionic_radii - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/geochem/images/thumb/sphx_glr_mineral_lattice_thumb.png - - :ref:`sphx_glr_examples_geochem_mineral_lattice.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/geochem/mineral_lattice -.. raw:: html - -
- - - -.. _sphx_glr_examples_comp: - -Compositional Data Examples -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/comp/images/thumb/sphx_glr_logtransforms_thumb.png - - :ref:`sphx_glr_examples_comp_logtransforms.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/comp/logtransforms - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/comp/images/thumb/sphx_glr_logratiomeans_thumb.png - - :ref:`sphx_glr_examples_comp_logratiomeans.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/comp/logratiomeans - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/comp/images/thumb/sphx_glr_compositional_data_thumb.png - - :ref:`sphx_glr_examples_comp_compositional_data.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/comp/compositional_data -.. raw:: html - -
- - - -.. _sphx_glr_examples_util: - -Utility Examples -~~~~~~~~~~~~~~~~~~~~ - -pyrolite includes a range of utilities for everything from dealing with -the web to plotting, synthetic data and machine learning. While most of these -are used as part of the core functions of pyrolite, you may also find -other uses for them, and this section provides some simple examples for -some of these. - - - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/util/images/thumb/sphx_glr_TAS_thumb.png - - :ref:`sphx_glr_examples_util_TAS.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/util/TAS - -.. raw:: html - -
- -.. only:: html - - .. figure:: /examples/util/images/thumb/sphx_glr_timescale_thumb.png - - :ref:`sphx_glr_examples_util_timescale.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /examples/util/timescale -.. raw:: html - -
- - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/plotting/REE_v_radii.ipynb b/docs/source/examples/plotting/REE_v_radii.ipynb deleted file mode 100644 index cb4f04bd..00000000 --- a/docs/source/examples/plotting/REE_v_radii.ipynb +++ /dev/null @@ -1,151 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nREE Radii Plots\n============================\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyrolite.plot import pyroplot" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here we generate some example data, using the\n:func:`~pyrolite.util.synthetic.example_spider_data` function (based on EMORB,\nhere normalised to Primitive Mantle);\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.synthetic import example_spider_data\n\ndf = example_spider_data(noise_level=0.1, nobs=20)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Where data is specified, the default plot is a line-based spiderplot:\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = df.pyroplot.REE(color=\"0.5\", figsize=(8, 4))\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This behaviour can be modified (see spiderplot docs) to provide e.g. filled ranges:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df.pyroplot.REE(mode=\"fill\", color=\"0.5\", alpha=0.5, figsize=(8, 4))\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The plotting axis can be specified to use exisiting axes:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(1, 2, sharey=True, figsize=(12, 4))\n\ndf.pyroplot.REE(ax=ax[0])\n# we can also change the index of the second axes\nanother_df = example_spider_data(noise_level=0.2, nobs=20) # some 'nosier' data\nanother_df.pyroplot.REE(ax=ax[1], color=\"k\", index=\"radii\")\n\nplt.tight_layout()\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If you're just after a plotting template, you can use\n:func:`~pyrolite.plot.spider.REE_v_radii` to get a formatted axis which can be used\nfor subsequent plotting:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.plot.spider import REE_v_radii\n\nax = REE_v_radii(index=\"radii\") # radii mode will put ionic radii on the x axis\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ".. seealso::\n\n Examples:\n `Ionic Radii `__,\n `Spider Diagrams `__,\n `lambdas: Parameterising REE Profiles `__\n\n Functions:\n :func:`~pyrolite.geochem.ind.get_ionic_radii`,\n :func:`pyrolite.plot.pyroplot.REE`,\n :func:`pyrolite.plot.pyroplot.spider`,\n :func:`~pyrolite.geochem.pyrochem.lambda_lnREE`\n\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/plotting/REE_v_radii.py b/docs/source/examples/plotting/REE_v_radii.py deleted file mode 100644 index 3ccae3df..00000000 --- a/docs/source/examples/plotting/REE_v_radii.py +++ /dev/null @@ -1,63 +0,0 @@ -""" -REE Radii Plots -============================ -""" -import pandas as pd -import numpy as np -import matplotlib.pyplot as plt -from pyrolite.plot import pyroplot - -# sphinx_gallery_thumbnail_number = 3 - -######################################################################################## -# Here we generate some example data, using the -# :func:`~pyrolite.util.synthetic.example_spider_data` function (based on EMORB, -# here normalised to Primitive Mantle); -# -from pyrolite.util.synthetic import example_spider_data - -df = example_spider_data(noise_level=0.1, nobs=20) - -######################################################################################## -# Where data is specified, the default plot is a line-based spiderplot: -ax = df.pyroplot.REE(color="0.5", figsize=(8, 4)) -plt.show() -######################################################################################## -# This behaviour can be modified (see spiderplot docs) to provide e.g. filled ranges: -# -df.pyroplot.REE(mode="fill", color="0.5", alpha=0.5, figsize=(8, 4)) -plt.show() -######################################################################################## -# The plotting axis can be specified to use exisiting axes: -# -fig, ax = plt.subplots(1, 2, sharey=True, figsize=(12, 4)) - -df.pyroplot.REE(ax=ax[0]) -# we can also change the index of the second axes -another_df = example_spider_data(noise_level=0.2, nobs=20) # some 'nosier' data -another_df.pyroplot.REE(ax=ax[1], color="k", index="radii") - -plt.tight_layout() -plt.show() -######################################################################################## -# If you're just after a plotting template, you can use -# :func:`~pyrolite.plot.spider.REE_v_radii` to get a formatted axis which can be used -# for subsequent plotting: -# -from pyrolite.plot.spider import REE_v_radii - -ax = REE_v_radii(index="radii") # radii mode will put ionic radii on the x axis -plt.show() -######################################################################################## -# .. seealso:: -# -# Examples: -# `Ionic Radii `__, -# `Spider Diagrams `__, -# `lambdas: Parameterising REE Profiles `__ -# -# Functions: -# :func:`~pyrolite.geochem.ind.get_ionic_radii`, -# :func:`pyrolite.plot.pyroplot.REE`, -# :func:`pyrolite.plot.pyroplot.spider`, -# :func:`~pyrolite.geochem.pyrochem.lambda_lnREE` diff --git a/docs/source/examples/plotting/REE_v_radii.py.md5 b/docs/source/examples/plotting/REE_v_radii.py.md5 deleted file mode 100644 index 4324f456..00000000 --- a/docs/source/examples/plotting/REE_v_radii.py.md5 +++ /dev/null @@ -1 +0,0 @@ -45663c05afc2c9a019c90cf3ca975c74 \ No newline at end of file diff --git a/docs/source/examples/plotting/REE_v_radii.rst b/docs/source/examples/plotting/REE_v_radii.rst deleted file mode 100644 index 4e36b45e..00000000 --- a/docs/source/examples/plotting/REE_v_radii.rst +++ /dev/null @@ -1,176 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_plotting_REE_v_radii.py: - - -REE Radii Plots -============================ - - -.. code-block:: default - - import pandas as pd - import numpy as np - import matplotlib.pyplot as plt - from pyrolite.plot import pyroplot - - - - - - - - - -Here we generate some example data, using the -:func:`~pyrolite.util.synthetic.example_spider_data` function (based on EMORB, -here normalised to Primitive Mantle); - - - -.. code-block:: default - - from pyrolite.util.synthetic import example_spider_data - - df = example_spider_data(noise_level=0.1, nobs=20) - - - - - - - - -Where data is specified, the default plot is a line-based spiderplot: - - -.. code-block:: default - - ax = df.pyroplot.REE(color="0.5", figsize=(8, 4)) - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_REE_v_radii_001.png - :class: sphx-glr-single-img - - - - - -This behaviour can be modified (see spiderplot docs) to provide e.g. filled ranges: - - - -.. code-block:: default - - df.pyroplot.REE(mode="fill", color="0.5", alpha=0.5, figsize=(8, 4)) - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_REE_v_radii_002.png - :class: sphx-glr-single-img - - - - - -The plotting axis can be specified to use exisiting axes: - - - -.. code-block:: default - - fig, ax = plt.subplots(1, 2, sharey=True, figsize=(12, 4)) - - df.pyroplot.REE(ax=ax[0]) - # we can also change the index of the second axes - another_df = example_spider_data(noise_level=0.2, nobs=20) # some 'nosier' data - another_df.pyroplot.REE(ax=ax[1], color="k", index="radii") - - plt.tight_layout() - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_REE_v_radii_003.png - :class: sphx-glr-single-img - - - - - -If you're just after a plotting template, you can use -:func:`~pyrolite.plot.spider.REE_v_radii` to get a formatted axis which can be used -for subsequent plotting: - - - -.. code-block:: default - - from pyrolite.plot.spider import REE_v_radii - - ax = REE_v_radii(index="radii") # radii mode will put ionic radii on the x axis - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_REE_v_radii_004.png - :class: sphx-glr-single-img - - - - - -.. seealso:: - - Examples: - `Ionic Radii `__, - `Spider Diagrams `__, - `lambdas: Parameterising REE Profiles `__ - - Functions: - :func:`~pyrolite.geochem.ind.get_ionic_radii`, - :func:`pyrolite.plot.pyroplot.REE`, - :func:`pyrolite.plot.pyroplot.spider`, - :func:`~pyrolite.geochem.pyrochem.lambda_lnREE` - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 3.606 seconds) - - -.. _sphx_glr_download_examples_plotting_REE_v_radii.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/plotting/REE_v_radii.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: REE_v_radii.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: REE_v_radii.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/plotting/REE_v_radii_codeobj.pickle b/docs/source/examples/plotting/REE_v_radii_codeobj.pickle deleted file mode 100644 index 639f1f3e..00000000 Binary files a/docs/source/examples/plotting/REE_v_radii_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/plotting/density.ipynb b/docs/source/examples/plotting/density.ipynb deleted file mode 100644 index bdc40598..00000000 --- a/docs/source/examples/plotting/density.ipynb +++ /dev/null @@ -1,256 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nDensity and Contour Plots\n==================================\n\nWhile individual point data are useful, we commonly want to understand the\nthe distribution of our data within a particular subspace, and compare that\nto a reference or other dataset. Pyrolite includes a few functions for\nvisualising data density, most based on Gaussian kernel density estimation\nand evaluation over a grid. The below examples highlight some of the currently\nimplemented features.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyrolite.plot import pyroplot\nfrom pyrolite.plot.density import density\nfrom pyrolite.comp.codata import close\n\n\nnp.random.seed(82)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First we create some example data :\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "oxs = [\"SiO2\", \"CaO\", \"MgO\", \"Na2O\"]\nys = np.random.rand(1000, len(oxs))\nys[:, 1] += 0.7\nys[:, 2] += 1.0\ndf = pd.DataFrame(data=close(np.exp(ys)), columns=oxs)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "A minimal density plot can be constructed as follows:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = df.loc[:, [\"SiO2\", \"MgO\"]].pyroplot.density()\ndf.loc[:, [\"SiO2\", \"MgO\"]].pyroplot.scatter(ax=ax, s=10, alpha=0.3, c=\"k\", zorder=2)\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "A colorbar linked to the KDE estimate colormap can be added using the `colorbar`\nboolean switch:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = df.loc[:, [\"SiO2\", \"MgO\"]].pyroplot.density(colorbar=True)\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "`density` by default will create a new axis, but can also be plotted over an\nexisting axis for more control:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12, 5))\n\ndf.loc[:, [\"SiO2\", \"MgO\"]].pyroplot.density(ax=ax[0])\ndf.loc[:, [\"SiO2\", \"CaO\"]].pyroplot.density(ax=ax[1])\n\nplt.tight_layout()\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Contours are also easily created, which by default are percentile values:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = df.loc[:, [\"SiO2\", \"CaO\"]].pyroplot.scatter(s=10, alpha=0.3, c=\"k\", zorder=2)\ndf.loc[:, [\"SiO2\", \"CaO\"]].pyroplot.density(ax=ax, contours=[0.95, 0.66, 0.33])\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Geochemical data is commonly log-normally distributed and is best analysed\nand visualised after log-transformation. The density estimation can be conducted\nover logspaced grids (individually for x and y axes using `logx` and `logy` boolean\nswitches). Notably, this makes both the KDE image and contours behave more naturally:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# some assymetric data\nfrom scipy import stats\n\nxs = stats.norm.rvs(loc=6, scale=3, size=(200, 1))\nys = stats.norm.rvs(loc=20, scale=3, size=(200, 1)) + 5 * xs + 50\ndata = np.append(xs, ys, axis=1).T\nasym_df = pd.DataFrame(np.exp(np.append(xs, ys, axis=1) / 25.0))\nasym_df.columns = [\"A\", \"B\"]\ngrids = [\"linxy\", \"logxy\"] * 2 + [\"logx\", \"logy\"]\nscales = [\"linscale\"] * 2 + [\"logscale\"] * 2 + [\"semilogx\", \"semilogy\"]\nlabels = [\"{}-{}\".format(ls, ps) for (ls, ps) in zip(grids, scales)]\nparams = list(\n zip(\n [\n (False, False),\n (True, True),\n (False, False),\n (True, True),\n (True, False),\n (False, True),\n ],\n grids,\n scales,\n )\n)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(3, 2, figsize=(8, 8))\nax = ax.flat\n\nfor a, (ls, grid, scale) in zip(ax, params):\n lx, ly = ls\n asym_df.pyroplot.density(ax=a, logx=lx, logy=ly, bins=30, cmap=\"viridis_r\")\n asym_df.pyroplot.density(\n ax=a,\n logx=lx,\n logy=ly,\n contours=[0.95, 0.5],\n bins=30,\n cmap=\"viridis\",\n fontsize=10,\n )\n asym_df.pyroplot.scatter(ax=a, s=10, alpha=0.3, c=\"k\", zorder=2)\n\n a.set_title(\"{}-{}\".format(grid, scale), fontsize=10)\n if scale in [\"logscale\", \"semilogx\"]:\n a.set_xscale(\"log\")\n if scale in [\"logscale\", \"semilogy\"]:\n a.set_yscale(\"log\")\nplt.tight_layout()\nplt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "plt.close(\"all\") # let's save some memory.." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "There are two other implemented modes beyond the default `density`: `hist2d` and\n`hexbin`, which parallel their equivalents in matplotlib.\nContouring is not enabled for these histogram methods.\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(1, 3, sharex=True, sharey=True, figsize=(14, 5))\nfor a, mode in zip(ax, [\"density\", \"hexbin\", \"hist2d\"]):\n df.loc[:, [\"SiO2\", \"CaO\"]].pyroplot.density(ax=a, mode=mode)\n a.set_title(\"Mode: {}\".format(mode))\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For the ``density`` mode, a ``vmin`` parameter is used to choose the lower\nthreshold, and by default is the 99th percentile (``vmin=0.01``), but can be\nadjusted. This is useful where there are a number of outliers, or where you wish to\nreduce the overall complexity/colour intensity of a figure (also good for printing!).\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(1, 3, figsize=(14, 4))\nfor a, vmin in zip(ax, [0.01, 0.1, 0.4]):\n df.loc[:, [\"SiO2\", \"CaO\"]].pyroplot.density(ax=a, bins=30, vmin=vmin, colorbar=True)\nplt.tight_layout()\nplt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "plt.close(\"all\") # let's save some memory.." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Density plots can also be used for ternary diagrams, where more than two components\nare specified:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(\n 1,\n 3,\n sharex=True,\n sharey=True,\n figsize=(15, 5),\n subplot_kw=dict(projection=\"ternary\"),\n)\ndf.loc[:, [\"SiO2\", \"CaO\", \"MgO\"]].pyroplot.scatter(ax=ax[0], alpha=0.05, c=\"k\")\nfor a, mode in zip(ax[1:], [\"hist\", \"density\"]):\n df.loc[:, [\"SiO2\", \"CaO\", \"MgO\"]].pyroplot.density(ax=a, mode=mode)\n a.set_title(\"Mode: {}\".format(mode), y=1.2)\n\nplt.tight_layout()\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "

Note

Using alpha with the ``density`` mode induces a known and old matplotlib bug,\n where the edges of bins within a ``pcolormesh`` image (used for plotting the\n KDE estimate) are over-emphasized, giving a gridded look.

\n\n.. seealso:: `Heatscatter Plots `__,\n `Ternary Plots `__,\n `Spider Density Diagrams `__\n\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/plotting/density.py b/docs/source/examples/plotting/density.py deleted file mode 100644 index 0bfe2751..00000000 --- a/docs/source/examples/plotting/density.py +++ /dev/null @@ -1,167 +0,0 @@ -""" -Density and Contour Plots -================================== - -While individual point data are useful, we commonly want to understand the -the distribution of our data within a particular subspace, and compare that -to a reference or other dataset. Pyrolite includes a few functions for -visualising data density, most based on Gaussian kernel density estimation -and evaluation over a grid. The below examples highlight some of the currently -implemented features. -""" -import pandas as pd -import numpy as np -import matplotlib.pyplot as plt -from pyrolite.plot import pyroplot -from pyrolite.plot.density import density -from pyrolite.comp.codata import close - -# sphinx_gallery_thumbnail_number = 6 - -np.random.seed(82) -######################################################################################## -# First we create some example data : -# -oxs = ["SiO2", "CaO", "MgO", "Na2O"] -ys = np.random.rand(1000, len(oxs)) -ys[:, 1] += 0.7 -ys[:, 2] += 1.0 -df = pd.DataFrame(data=close(np.exp(ys)), columns=oxs) -######################################################################################## -# A minimal density plot can be constructed as follows: -# -ax = df.loc[:, ["SiO2", "MgO"]].pyroplot.density() -df.loc[:, ["SiO2", "MgO"]].pyroplot.scatter(ax=ax, s=10, alpha=0.3, c="k", zorder=2) -plt.show() -######################################################################################## -# A colorbar linked to the KDE estimate colormap can be added using the `colorbar` -# boolean switch: -# -ax = df.loc[:, ["SiO2", "MgO"]].pyroplot.density(colorbar=True) -plt.show() -######################################################################################## -# `density` by default will create a new axis, but can also be plotted over an -# existing axis for more control: -# -fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12, 5)) - -df.loc[:, ["SiO2", "MgO"]].pyroplot.density(ax=ax[0]) -df.loc[:, ["SiO2", "CaO"]].pyroplot.density(ax=ax[1]) - -plt.tight_layout() -plt.show() -######################################################################################## -# Contours are also easily created, which by default are percentile values: -# -ax = df.loc[:, ["SiO2", "CaO"]].pyroplot.scatter(s=10, alpha=0.3, c="k", zorder=2) -df.loc[:, ["SiO2", "CaO"]].pyroplot.density(ax=ax, contours=[0.95, 0.66, 0.33]) -plt.show() -######################################################################################## -# Geochemical data is commonly log-normally distributed and is best analysed -# and visualised after log-transformation. The density estimation can be conducted -# over logspaced grids (individually for x and y axes using `logx` and `logy` boolean -# switches). Notably, this makes both the KDE image and contours behave more naturally: -# - -# some assymetric data -from scipy import stats - -xs = stats.norm.rvs(loc=6, scale=3, size=(200, 1)) -ys = stats.norm.rvs(loc=20, scale=3, size=(200, 1)) + 5 * xs + 50 -data = np.append(xs, ys, axis=1).T -asym_df = pd.DataFrame(np.exp(np.append(xs, ys, axis=1) / 25.0)) -asym_df.columns = ["A", "B"] -grids = ["linxy", "logxy"] * 2 + ["logx", "logy"] -scales = ["linscale"] * 2 + ["logscale"] * 2 + ["semilogx", "semilogy"] -labels = ["{}-{}".format(ls, ps) for (ls, ps) in zip(grids, scales)] -params = list( - zip( - [ - (False, False), - (True, True), - (False, False), - (True, True), - (True, False), - (False, True), - ], - grids, - scales, - ) -) -######################################################################################## -fig, ax = plt.subplots(3, 2, figsize=(8, 8)) -ax = ax.flat - -for a, (ls, grid, scale) in zip(ax, params): - lx, ly = ls - asym_df.pyroplot.density(ax=a, logx=lx, logy=ly, bins=30, cmap="viridis_r") - asym_df.pyroplot.density( - ax=a, - logx=lx, - logy=ly, - contours=[0.95, 0.5], - bins=30, - cmap="viridis", - fontsize=10, - ) - asym_df.pyroplot.scatter(ax=a, s=10, alpha=0.3, c="k", zorder=2) - - a.set_title("{}-{}".format(grid, scale), fontsize=10) - if scale in ["logscale", "semilogx"]: - a.set_xscale("log") - if scale in ["logscale", "semilogy"]: - a.set_yscale("log") -plt.tight_layout() -plt.show() -####################################################################################### -plt.close("all") # let's save some memory.. -######################################################################################## -# There are two other implemented modes beyond the default `density`: `hist2d` and -# `hexbin`, which parallel their equivalents in matplotlib. -# Contouring is not enabled for these histogram methods. -# -fig, ax = plt.subplots(1, 3, sharex=True, sharey=True, figsize=(14, 5)) -for a, mode in zip(ax, ["density", "hexbin", "hist2d"]): - df.loc[:, ["SiO2", "CaO"]].pyroplot.density(ax=a, mode=mode) - a.set_title("Mode: {}".format(mode)) -plt.show() -######################################################################################## -# For the ``density`` mode, a ``vmin`` parameter is used to choose the lower -# threshold, and by default is the 99th percentile (``vmin=0.01``), but can be -# adjusted. This is useful where there are a number of outliers, or where you wish to -# reduce the overall complexity/colour intensity of a figure (also good for printing!). -# -fig, ax = plt.subplots(1, 3, figsize=(14, 4)) -for a, vmin in zip(ax, [0.01, 0.1, 0.4]): - df.loc[:, ["SiO2", "CaO"]].pyroplot.density(ax=a, bins=30, vmin=vmin, colorbar=True) -plt.tight_layout() -plt.show() -####################################################################################### -plt.close("all") # let's save some memory.. -######################################################################################## -# Density plots can also be used for ternary diagrams, where more than two components -# are specified: -# -fig, ax = plt.subplots( - 1, - 3, - sharex=True, - sharey=True, - figsize=(15, 5), - subplot_kw=dict(projection="ternary"), -) -df.loc[:, ["SiO2", "CaO", "MgO"]].pyroplot.scatter(ax=ax[0], alpha=0.05, c="k") -for a, mode in zip(ax[1:], ["hist", "density"]): - df.loc[:, ["SiO2", "CaO", "MgO"]].pyroplot.density(ax=a, mode=mode) - a.set_title("Mode: {}".format(mode), y=1.2) - -plt.tight_layout() -plt.show() -######################################################################################## -# .. note:: Using alpha with the ``density`` mode induces a known and old matplotlib bug, -# where the edges of bins within a ``pcolormesh`` image (used for plotting the -# KDE estimate) are over-emphasized, giving a gridded look. -# -# .. seealso:: `Heatscatter Plots `__, -# `Ternary Plots `__, -# `Spider Density Diagrams `__ diff --git a/docs/source/examples/plotting/density.py.md5 b/docs/source/examples/plotting/density.py.md5 deleted file mode 100644 index 73920690..00000000 --- a/docs/source/examples/plotting/density.py.md5 +++ /dev/null @@ -1 +0,0 @@ -ab27758fd6acf594fab05b5229c38b1f \ No newline at end of file diff --git a/docs/source/examples/plotting/density.rst b/docs/source/examples/plotting/density.rst deleted file mode 100644 index d8f533f4..00000000 --- a/docs/source/examples/plotting/density.rst +++ /dev/null @@ -1,359 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_plotting_density.py: - - -Density and Contour Plots -================================== - -While individual point data are useful, we commonly want to understand the -the distribution of our data within a particular subspace, and compare that -to a reference or other dataset. Pyrolite includes a few functions for -visualising data density, most based on Gaussian kernel density estimation -and evaluation over a grid. The below examples highlight some of the currently -implemented features. - - -.. code-block:: default - - import pandas as pd - import numpy as np - import matplotlib.pyplot as plt - from pyrolite.plot import pyroplot - from pyrolite.plot.density import density - from pyrolite.comp.codata import close - - - np.random.seed(82) - - - - - - - -First we create some example data : - - - -.. code-block:: default - - oxs = ["SiO2", "CaO", "MgO", "Na2O"] - ys = np.random.rand(1000, len(oxs)) - ys[:, 1] += 0.7 - ys[:, 2] += 1.0 - df = pd.DataFrame(data=close(np.exp(ys)), columns=oxs) - - - - - - - -A minimal density plot can be constructed as follows: - - - -.. code-block:: default - - ax = df.loc[:, ["SiO2", "MgO"]].pyroplot.density() - df.loc[:, ["SiO2", "MgO"]].pyroplot.scatter(ax=ax, s=10, alpha=0.3, c="k", zorder=2) - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_density_001.png - :class: sphx-glr-single-img - - - - - -A colorbar linked to the KDE estimate colormap can be added using the `colorbar` -boolean switch: - - - -.. code-block:: default - - ax = df.loc[:, ["SiO2", "MgO"]].pyroplot.density(colorbar=True) - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_density_002.png - :class: sphx-glr-single-img - - - - - -`density` by default will create a new axis, but can also be plotted over an -existing axis for more control: - - - -.. code-block:: default - - fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12, 5)) - - df.loc[:, ["SiO2", "MgO"]].pyroplot.density(ax=ax[0]) - df.loc[:, ["SiO2", "CaO"]].pyroplot.density(ax=ax[1]) - - plt.tight_layout() - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_density_003.png - :class: sphx-glr-single-img - - - - - -Contours are also easily created, which by default are percentile values: - - - -.. code-block:: default - - ax = df.loc[:, ["SiO2", "CaO"]].pyroplot.scatter(s=10, alpha=0.3, c="k", zorder=2) - df.loc[:, ["SiO2", "CaO"]].pyroplot.density(ax=ax, contours=[0.95, 0.66, 0.33]) - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_density_004.png - :class: sphx-glr-single-img - - - - - -Geochemical data is commonly log-normally distributed and is best analysed -and visualised after log-transformation. The density estimation can be conducted -over logspaced grids (individually for x and y axes using `logx` and `logy` boolean -switches). Notably, this makes both the KDE image and contours behave more naturally: - - - -.. code-block:: default - - - # some assymetric data - from scipy import stats - - xs = stats.norm.rvs(loc=6, scale=3, size=(200, 1)) - ys = stats.norm.rvs(loc=20, scale=3, size=(200, 1)) + 5 * xs + 50 - data = np.append(xs, ys, axis=1).T - asym_df = pd.DataFrame(np.exp(np.append(xs, ys, axis=1) / 25.0)) - asym_df.columns = ["A", "B"] - grids = ["linxy", "logxy"] * 2 + ["logx", "logy"] - scales = ["linscale"] * 2 + ["logscale"] * 2 + ["semilogx", "semilogy"] - labels = ["{}-{}".format(ls, ps) for (ls, ps) in zip(grids, scales)] - params = list( - zip( - [ - (False, False), - (True, True), - (False, False), - (True, True), - (True, False), - (False, True), - ], - grids, - scales, - ) - ) - - - - - - - - -.. code-block:: default - - fig, ax = plt.subplots(3, 2, figsize=(8, 8)) - ax = ax.flat - - for a, (ls, grid, scale) in zip(ax, params): - lx, ly = ls - asym_df.pyroplot.density(ax=a, logx=lx, logy=ly, bins=30, cmap="viridis_r") - asym_df.pyroplot.density( - ax=a, - logx=lx, - logy=ly, - contours=[0.95, 0.5], - bins=30, - cmap="viridis", - fontsize=10, - ) - asym_df.pyroplot.scatter(ax=a, s=10, alpha=0.3, c="k", zorder=2) - - a.set_title("{}-{}".format(grid, scale), fontsize=10) - if scale in ["logscale", "semilogx"]: - a.set_xscale("log") - if scale in ["logscale", "semilogy"]: - a.set_yscale("log") - plt.tight_layout() - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_density_005.png - :class: sphx-glr-single-img - - - - - - -.. code-block:: default - - plt.close("all") # let's save some memory.. - - - - - - - -There are two other implemented modes beyond the default `density`: `hist2d` and -`hexbin`, which parallel their equivalents in matplotlib. -Contouring is not enabled for these histogram methods. - - - -.. code-block:: default - - fig, ax = plt.subplots(1, 3, sharex=True, sharey=True, figsize=(14, 5)) - for a, mode in zip(ax, ["density", "hexbin", "hist2d"]): - df.loc[:, ["SiO2", "CaO"]].pyroplot.density(ax=a, mode=mode) - a.set_title("Mode: {}".format(mode)) - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_density_006.png - :class: sphx-glr-single-img - - - - - -For the ``density`` mode, a ``vmin`` parameter is used to choose the lower -threshold, and by default is the 99th percentile (``vmin=0.01``), but can be -adjusted. This is useful where there are a number of outliers, or where you wish to -reduce the overall complexity/colour intensity of a figure (also good for printing!). - - - -.. code-block:: default - - fig, ax = plt.subplots(1, 3, figsize=(14, 4)) - for a, vmin in zip(ax, [0.01, 0.1, 0.4]): - df.loc[:, ["SiO2", "CaO"]].pyroplot.density(ax=a, bins=30, vmin=vmin, colorbar=True) - plt.tight_layout() - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_density_007.png - :class: sphx-glr-single-img - - - - - - -.. code-block:: default - - plt.close("all") # let's save some memory.. - - - - - - - -Density plots can also be used for ternary diagrams, where more than two components -are specified: - - - -.. code-block:: default - - fig, ax = plt.subplots( - 1, - 3, - sharex=True, - sharey=True, - figsize=(15, 5), - subplot_kw=dict(projection="ternary"), - ) - df.loc[:, ["SiO2", "CaO", "MgO"]].pyroplot.scatter(ax=ax[0], alpha=0.05, c="k") - for a, mode in zip(ax[1:], ["hist", "density"]): - df.loc[:, ["SiO2", "CaO", "MgO"]].pyroplot.density(ax=a, mode=mode) - a.set_title("Mode: {}".format(mode), y=1.2) - - plt.tight_layout() - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_density_008.png - :class: sphx-glr-single-img - - - - - -.. note:: Using alpha with the ``density`` mode induces a known and old matplotlib bug, - where the edges of bins within a ``pcolormesh`` image (used for plotting the - KDE estimate) are over-emphasized, giving a gridded look. - -.. seealso:: `Heatscatter Plots `__, - `Ternary Plots `__, - `Spider Density Diagrams `__ - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 5.971 seconds) - - -.. _sphx_glr_download_examples_plotting_density.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/plotting/density.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: density.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: density.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/plotting/density_codeobj.pickle b/docs/source/examples/plotting/density_codeobj.pickle deleted file mode 100644 index 0d6b9706..00000000 Binary files a/docs/source/examples/plotting/density_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/plotting/heatscatter.ipynb b/docs/source/examples/plotting/heatscatter.ipynb deleted file mode 100644 index e63c7bd0..00000000 --- a/docs/source/examples/plotting/heatscatter.ipynb +++ /dev/null @@ -1,97 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nHeatscatter Plots\n==================================\n\nWhile :func:`~pyrolite.plot.pyroplot.density` plots are useful summary visualizations\nfor large datasets, scatterplots are more precise and retain all spatial information\n(although they can get crowded).\n\nA scatter plot where individual points are coloured by data density in some respects\nrepresents the best of both worlds. A version inspired by similar existing\nvisualisations is implemented with :func:`~pyrolite.plot.pyroplot.heatscatter`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyrolite.plot import pyroplot\n\nnp.random.seed(12)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First we'll create some example data\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.synthetic import test_df, random_cov_matrix\n\ndf = test_df(\n index_length=1000,\n cov=random_cov_matrix(sigmas=np.random.rand(4) * 2, dim=4, seed=12),\n seed=12,\n)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can compare a minimal :func:`~pyrolite.plot.pyroplot.heatscatter` plot to other\nvisualisations for the same data:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.plot.axes import share_axes\n\nfig, ax = plt.subplots(3, 4, figsize=(12, 9))\n\nax = ax.flat\nshare_axes(ax[:4], which=\"xy\")\nshare_axes(ax[4:8], which=\"xy\")\nshare_axes(ax[8:], which=\"xy\")\n\ncontours = [0.95, 0.66, 0.3]\nbivar = [\"SiO2\", \"MgO\"]\ntrivar = [\"SiO2\", \"MgO\", \"TiO2\"]\n# linear-scaled comparison\ndf.loc[:, bivar].pyroplot.scatter(ax=ax[0], c=\"k\", s=10, alpha=0.3)\ndf.loc[:, bivar].pyroplot.density(ax=ax[1])\ndf.loc[:, bivar].pyroplot.density(ax=ax[2], contours=contours)\ndf.loc[:, bivar].pyroplot.heatscatter(ax=ax[3], s=10, alpha=0.3)\n# log-log plots\ndf.loc[:, bivar].pyroplot.scatter(ax=ax[4], c=\"k\", s=10, alpha=0.3)\ndf.loc[:, bivar].pyroplot.density(ax=ax[5], logx=True, logy=True)\ndf.loc[:, bivar].pyroplot.density(ax=ax[6], contours=contours, logx=True, logy=True)\ndf.loc[:, bivar].pyroplot.heatscatter(ax=ax[7], s=10, alpha=0.3, logx=True, logy=True)\n# ternary plots\ndf.loc[:, trivar].pyroplot.scatter(ax=ax[8], c=\"k\", s=10, alpha=0.1)\ndf.loc[:, trivar].pyroplot.density(ax=ax[9], bins=100)\ndf.loc[:, trivar].pyroplot.density(ax=ax[10], contours=contours, bins=100)\ndf.loc[:, trivar].pyroplot.heatscatter(ax=ax[11], s=10, alpha=0.3, renorm=True)\nfig.subplots_adjust(hspace=0.4, wspace=0.4)\n\ntitles = [\"Scatter\", \"Density\", \"Contours\", \"Heatscatter\"]\nfor t, a in zip(titles + [i + \" (log-log)\" for i in titles], ax):\n a.set_title(t)\nplt.tight_layout()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ".. seealso:: `Ternary Plots `__,\n `Density Plots `__,\n `Spider Density Diagrams `__\n\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/plotting/heatscatter.py b/docs/source/examples/plotting/heatscatter.py deleted file mode 100644 index 42949355..00000000 --- a/docs/source/examples/plotting/heatscatter.py +++ /dev/null @@ -1,69 +0,0 @@ -""" -Heatscatter Plots -================================== - -While :func:`~pyrolite.plot.pyroplot.density` plots are useful summary visualizations -for large datasets, scatterplots are more precise and retain all spatial information -(although they can get crowded). - -A scatter plot where individual points are coloured by data density in some respects -represents the best of both worlds. A version inspired by similar existing -visualisations is implemented with :func:`~pyrolite.plot.pyroplot.heatscatter`. -""" -import pandas as pd -import numpy as np -import matplotlib.pyplot as plt -from pyrolite.plot import pyroplot - -np.random.seed(12) -######################################################################################## -# First we'll create some example data -from pyrolite.util.synthetic import test_df, random_cov_matrix - -df = test_df( - index_length=1000, - cov=random_cov_matrix(sigmas=np.random.rand(4) * 2, dim=4, seed=12), - seed=12, -) - -######################################################################################## -# We can compare a minimal :func:`~pyrolite.plot.pyroplot.heatscatter` plot to other -# visualisations for the same data: -# -from pyrolite.util.plot.axes import share_axes - -fig, ax = plt.subplots(3, 4, figsize=(12, 9)) - -ax = ax.flat -share_axes(ax[:4], which="xy") -share_axes(ax[4:8], which="xy") -share_axes(ax[8:], which="xy") - -contours = [0.95, 0.66, 0.3] -bivar = ["SiO2", "MgO"] -trivar = ["SiO2", "MgO", "TiO2"] -# linear-scaled comparison -df.loc[:, bivar].pyroplot.scatter(ax=ax[0], c="k", s=10, alpha=0.3) -df.loc[:, bivar].pyroplot.density(ax=ax[1]) -df.loc[:, bivar].pyroplot.density(ax=ax[2], contours=contours) -df.loc[:, bivar].pyroplot.heatscatter(ax=ax[3], s=10, alpha=0.3) -# log-log plots -df.loc[:, bivar].pyroplot.scatter(ax=ax[4], c="k", s=10, alpha=0.3) -df.loc[:, bivar].pyroplot.density(ax=ax[5], logx=True, logy=True) -df.loc[:, bivar].pyroplot.density(ax=ax[6], contours=contours, logx=True, logy=True) -df.loc[:, bivar].pyroplot.heatscatter(ax=ax[7], s=10, alpha=0.3, logx=True, logy=True) -# ternary plots -df.loc[:, trivar].pyroplot.scatter(ax=ax[8], c="k", s=10, alpha=0.1) -df.loc[:, trivar].pyroplot.density(ax=ax[9], bins=100) -df.loc[:, trivar].pyroplot.density(ax=ax[10], contours=contours, bins=100) -df.loc[:, trivar].pyroplot.heatscatter(ax=ax[11], s=10, alpha=0.3, renorm=True) -fig.subplots_adjust(hspace=0.4, wspace=0.4) - -titles = ["Scatter", "Density", "Contours", "Heatscatter"] -for t, a in zip(titles + [i + " (log-log)" for i in titles], ax): - a.set_title(t) -plt.tight_layout() -######################################################################################## -# .. seealso:: `Ternary Plots `__, -# `Density Plots `__, -# `Spider Density Diagrams `__ diff --git a/docs/source/examples/plotting/heatscatter.py.md5 b/docs/source/examples/plotting/heatscatter.py.md5 deleted file mode 100644 index b1857147..00000000 --- a/docs/source/examples/plotting/heatscatter.py.md5 +++ /dev/null @@ -1 +0,0 @@ -3f1c1064f56f8596673c62ebdf2f2b75 \ No newline at end of file diff --git a/docs/source/examples/plotting/heatscatter.rst b/docs/source/examples/plotting/heatscatter.rst deleted file mode 100644 index 17bfc0ca..00000000 --- a/docs/source/examples/plotting/heatscatter.rst +++ /dev/null @@ -1,144 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_plotting_heatscatter.py: - - -Heatscatter Plots -================================== - -While :func:`~pyrolite.plot.pyroplot.density` plots are useful summary visualizations -for large datasets, scatterplots are more precise and retain all spatial information -(although they can get crowded). - -A scatter plot where individual points are coloured by data density in some respects -represents the best of both worlds. A version inspired by similar existing -visualisations is implemented with :func:`~pyrolite.plot.pyroplot.heatscatter`. - - -.. code-block:: default - - import pandas as pd - import numpy as np - import matplotlib.pyplot as plt - from pyrolite.plot import pyroplot - - np.random.seed(12) - - - - - - - -First we'll create some example data - - -.. code-block:: default - - from pyrolite.util.synthetic import test_df, random_cov_matrix - - df = test_df( - index_length=1000, - cov=random_cov_matrix(sigmas=np.random.rand(4) * 2, dim=4, seed=12), - seed=12, - ) - - - - - - - - -We can compare a minimal :func:`~pyrolite.plot.pyroplot.heatscatter` plot to other -visualisations for the same data: - - - -.. code-block:: default - - from pyrolite.util.plot.axes import share_axes - - fig, ax = plt.subplots(3, 4, figsize=(12, 9)) - - ax = ax.flat - share_axes(ax[:4], which="xy") - share_axes(ax[4:8], which="xy") - share_axes(ax[8:], which="xy") - - contours = [0.95, 0.66, 0.3] - bivar = ["SiO2", "MgO"] - trivar = ["SiO2", "MgO", "TiO2"] - # linear-scaled comparison - df.loc[:, bivar].pyroplot.scatter(ax=ax[0], c="k", s=10, alpha=0.3) - df.loc[:, bivar].pyroplot.density(ax=ax[1]) - df.loc[:, bivar].pyroplot.density(ax=ax[2], contours=contours) - df.loc[:, bivar].pyroplot.heatscatter(ax=ax[3], s=10, alpha=0.3) - # log-log plots - df.loc[:, bivar].pyroplot.scatter(ax=ax[4], c="k", s=10, alpha=0.3) - df.loc[:, bivar].pyroplot.density(ax=ax[5], logx=True, logy=True) - df.loc[:, bivar].pyroplot.density(ax=ax[6], contours=contours, logx=True, logy=True) - df.loc[:, bivar].pyroplot.heatscatter(ax=ax[7], s=10, alpha=0.3, logx=True, logy=True) - # ternary plots - df.loc[:, trivar].pyroplot.scatter(ax=ax[8], c="k", s=10, alpha=0.1) - df.loc[:, trivar].pyroplot.density(ax=ax[9], bins=100) - df.loc[:, trivar].pyroplot.density(ax=ax[10], contours=contours, bins=100) - df.loc[:, trivar].pyroplot.heatscatter(ax=ax[11], s=10, alpha=0.3, renorm=True) - fig.subplots_adjust(hspace=0.4, wspace=0.4) - - titles = ["Scatter", "Density", "Contours", "Heatscatter"] - for t, a in zip(titles + [i + " (log-log)" for i in titles], ax): - a.set_title(t) - plt.tight_layout() - - - -.. image:: /examples/plotting/images/sphx_glr_heatscatter_001.png - :class: sphx-glr-single-img - - - - - -.. seealso:: `Ternary Plots `__, - `Density Plots `__, - `Spider Density Diagrams `__ - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 3.503 seconds) - - -.. _sphx_glr_download_examples_plotting_heatscatter.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/plotting/heatscatter.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: heatscatter.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: heatscatter.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/plotting/heatscatter_codeobj.pickle b/docs/source/examples/plotting/heatscatter_codeobj.pickle deleted file mode 100644 index c1b6aa67..00000000 Binary files a/docs/source/examples/plotting/heatscatter_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_001.png b/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_001.png deleted file mode 100644 index d7d4a078..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_001.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_002.png b/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_002.png deleted file mode 100644 index 960e5abb..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_002.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_003.png b/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_003.png deleted file mode 100644 index 5726c57f..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_003.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_004.png b/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_004.png deleted file mode 100644 index 17791e26..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_REE_v_radii_004.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_density_001.png b/docs/source/examples/plotting/images/sphx_glr_density_001.png deleted file mode 100644 index d1c7d976..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_density_001.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_density_002.png b/docs/source/examples/plotting/images/sphx_glr_density_002.png deleted file mode 100644 index 027c8ea3..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_density_002.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_density_003.png b/docs/source/examples/plotting/images/sphx_glr_density_003.png deleted file mode 100644 index 207ead3f..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_density_003.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_density_004.png b/docs/source/examples/plotting/images/sphx_glr_density_004.png deleted file mode 100644 index ce9e82c1..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_density_004.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_density_005.png b/docs/source/examples/plotting/images/sphx_glr_density_005.png deleted file mode 100644 index ae82e6d4..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_density_005.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_density_006.png b/docs/source/examples/plotting/images/sphx_glr_density_006.png deleted file mode 100644 index 1ccaefe3..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_density_006.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_density_007.png b/docs/source/examples/plotting/images/sphx_glr_density_007.png deleted file mode 100644 index acc3baf0..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_density_007.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_density_008.png b/docs/source/examples/plotting/images/sphx_glr_density_008.png deleted file mode 100644 index 91587105..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_density_008.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_heatscatter_001.png b/docs/source/examples/plotting/images/sphx_glr_heatscatter_001.png deleted file mode 100644 index 8d554cc9..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_heatscatter_001.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_manifold_vis_001.png b/docs/source/examples/plotting/images/sphx_glr_manifold_vis_001.png deleted file mode 100644 index 88682dc0..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_manifold_vis_001.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_parallel_001.png b/docs/source/examples/plotting/images/sphx_glr_parallel_001.png deleted file mode 100644 index 5a00358a..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_parallel_001.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_parallel_002.png b/docs/source/examples/plotting/images/sphx_glr_parallel_002.png deleted file mode 100644 index e49660ab..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_parallel_002.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_parallel_003.png b/docs/source/examples/plotting/images/sphx_glr_parallel_003.png deleted file mode 100644 index 38669c91..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_parallel_003.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_parallel_004.png b/docs/source/examples/plotting/images/sphx_glr_parallel_004.png deleted file mode 100644 index 8402c5ee..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_parallel_004.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_spider_001.png b/docs/source/examples/plotting/images/sphx_glr_spider_001.png deleted file mode 100644 index c08abe54..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_spider_001.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_spider_002.png b/docs/source/examples/plotting/images/sphx_glr_spider_002.png deleted file mode 100644 index 14bab1ce..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_spider_002.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_spider_003.png b/docs/source/examples/plotting/images/sphx_glr_spider_003.png deleted file mode 100644 index 6b1363a3..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_spider_003.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_spider_004.png b/docs/source/examples/plotting/images/sphx_glr_spider_004.png deleted file mode 100644 index a4608a24..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_spider_004.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_spider_005.png b/docs/source/examples/plotting/images/sphx_glr_spider_005.png deleted file mode 100644 index ab74a3e6..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_spider_005.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_stem_001.png b/docs/source/examples/plotting/images/sphx_glr_stem_001.png deleted file mode 100644 index 11b3de26..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_stem_001.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_stem_002.png b/docs/source/examples/plotting/images/sphx_glr_stem_002.png deleted file mode 100644 index 6b1e670a..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_stem_002.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_templates_001.png b/docs/source/examples/plotting/images/sphx_glr_templates_001.png deleted file mode 100644 index 16c04611..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_templates_001.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_templates_002.png b/docs/source/examples/plotting/images/sphx_glr_templates_002.png deleted file mode 100644 index 6ae2d8e7..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_templates_002.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_ternary_001.png b/docs/source/examples/plotting/images/sphx_glr_ternary_001.png deleted file mode 100644 index 79271313..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_ternary_001.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_ternary_002.png b/docs/source/examples/plotting/images/sphx_glr_ternary_002.png deleted file mode 100644 index 7cc843b7..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_ternary_002.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/sphx_glr_ternary_003.png b/docs/source/examples/plotting/images/sphx_glr_ternary_003.png deleted file mode 100644 index 74438c84..00000000 Binary files a/docs/source/examples/plotting/images/sphx_glr_ternary_003.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/thumb/sphx_glr_REE_v_radii_thumb.png b/docs/source/examples/plotting/images/thumb/sphx_glr_REE_v_radii_thumb.png deleted file mode 100644 index 9f57d59e..00000000 Binary files a/docs/source/examples/plotting/images/thumb/sphx_glr_REE_v_radii_thumb.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/thumb/sphx_glr_density_thumb.png b/docs/source/examples/plotting/images/thumb/sphx_glr_density_thumb.png deleted file mode 100644 index 1edfddfa..00000000 Binary files a/docs/source/examples/plotting/images/thumb/sphx_glr_density_thumb.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/thumb/sphx_glr_heatscatter_thumb.png b/docs/source/examples/plotting/images/thumb/sphx_glr_heatscatter_thumb.png deleted file mode 100644 index ab3c672a..00000000 Binary files a/docs/source/examples/plotting/images/thumb/sphx_glr_heatscatter_thumb.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/thumb/sphx_glr_manifold_vis_thumb.png b/docs/source/examples/plotting/images/thumb/sphx_glr_manifold_vis_thumb.png deleted file mode 100644 index f07500e5..00000000 Binary files a/docs/source/examples/plotting/images/thumb/sphx_glr_manifold_vis_thumb.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/thumb/sphx_glr_parallel_thumb.png b/docs/source/examples/plotting/images/thumb/sphx_glr_parallel_thumb.png deleted file mode 100644 index be3911a0..00000000 Binary files a/docs/source/examples/plotting/images/thumb/sphx_glr_parallel_thumb.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/thumb/sphx_glr_spider_thumb.png b/docs/source/examples/plotting/images/thumb/sphx_glr_spider_thumb.png deleted file mode 100644 index 681feb6a..00000000 Binary files a/docs/source/examples/plotting/images/thumb/sphx_glr_spider_thumb.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/thumb/sphx_glr_stem_thumb.png b/docs/source/examples/plotting/images/thumb/sphx_glr_stem_thumb.png deleted file mode 100644 index 6ebaf41d..00000000 Binary files a/docs/source/examples/plotting/images/thumb/sphx_glr_stem_thumb.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/thumb/sphx_glr_templates_thumb.png b/docs/source/examples/plotting/images/thumb/sphx_glr_templates_thumb.png deleted file mode 100644 index 2a7028c2..00000000 Binary files a/docs/source/examples/plotting/images/thumb/sphx_glr_templates_thumb.png and /dev/null differ diff --git a/docs/source/examples/plotting/images/thumb/sphx_glr_ternary_thumb.png b/docs/source/examples/plotting/images/thumb/sphx_glr_ternary_thumb.png deleted file mode 100644 index 2fb31cd5..00000000 Binary files a/docs/source/examples/plotting/images/thumb/sphx_glr_ternary_thumb.png and /dev/null differ diff --git a/docs/source/examples/plotting/manifold_vis.ipynb b/docs/source/examples/plotting/manifold_vis.ipynb deleted file mode 100644 index 200d83f9..00000000 --- a/docs/source/examples/plotting/manifold_vis.ipynb +++ /dev/null @@ -1,98 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nUsing Manifolds for Visualisation\n=================================\n\nVisualisation of data which has high dimensionality is challenging, and one solution\nis to provide visualisations in low-dimension representations of the space actually\nspanned by the data. Here we provide an example of visualisation of classification\npredictions and relative prediction certainty (using entropy across predicted\nprobability for each individual class) for a toy :mod:`sklearn` dataset.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\nimport sklearn.datasets\nimport matplotlib.pyplot as plt\nfrom pyrolite.util.skl.pipeline import SVC_pipeline\nfrom pyrolite.util.skl.vis import plot_mapping\nfrom pyrolite.util.plot import DEFAULT_DISC_COLORMAP\n\nnp.random.seed(82)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "wine = sklearn.datasets.load_wine()\ndata, target = wine[\"data\"], wine[\"target\"]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# data = data[:, np.random.random(data.shape[1]) > 0.4] # randomly remove fraction of dimensionality" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "svc = SVC_pipeline(probability=True)\ngs = svc.fit(data, target)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(1, 2, figsize=(8, 4))\n\na, tfm, mapped = plot_mapping(\n data, gs.best_estimator_, ax=ax[1], s=50, init=\"pca\"\n)\nax[0].scatter(*mapped.T, c=DEFAULT_DISC_COLORMAP(gs.predict(data)), s=50)\n\nax[0].set_title(\"Predicted Classes\")\nax[1].set_title(\"With Relative Certainty\")\n\nfor a in ax:\n a.set_xticks([])\n a.set_yticks([])" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/plotting/manifold_vis.py b/docs/source/examples/plotting/manifold_vis.py deleted file mode 100644 index bca7eb0f..00000000 --- a/docs/source/examples/plotting/manifold_vis.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -Using Manifolds for Visualisation -================================= - -Visualisation of data which has high dimensionality is challenging, and one solution -is to provide visualisations in low-dimension representations of the space actually -spanned by the data. Here we provide an example of visualisation of classification -predictions and relative prediction certainty (using entropy across predicted -probability for each individual class) for a toy :mod:`sklearn` dataset. -""" -import numpy as np -import sklearn.datasets -import matplotlib.pyplot as plt -from pyrolite.util.skl.pipeline import SVC_pipeline -from pyrolite.util.skl.vis import plot_mapping -from pyrolite.util.plot import DEFAULT_DISC_COLORMAP - -np.random.seed(82) -######################################################################################## -wine = sklearn.datasets.load_wine() -data, target = wine["data"], wine["target"] -######################################################################################## - -# data = data[:, np.random.random(data.shape[1]) > 0.4] # randomly remove fraction of dimensionality - -######################################################################################## - -svc = SVC_pipeline(probability=True) -gs = svc.fit(data, target) -# %% Plot -fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - -a, tfm, mapped = plot_mapping( - data, gs.best_estimator_, ax=ax[1], s=50, init="pca" -) -ax[0].scatter(*mapped.T, c=DEFAULT_DISC_COLORMAP(gs.predict(data)), s=50) - -ax[0].set_title("Predicted Classes") -ax[1].set_title("With Relative Certainty") - -for a in ax: - a.set_xticks([]) - a.set_yticks([]) diff --git a/docs/source/examples/plotting/manifold_vis.py.md5 b/docs/source/examples/plotting/manifold_vis.py.md5 deleted file mode 100644 index 98f712f6..00000000 --- a/docs/source/examples/plotting/manifold_vis.py.md5 +++ /dev/null @@ -1 +0,0 @@ -2d649d9b5754c3db136b5516cf44c90f \ No newline at end of file diff --git a/docs/source/examples/plotting/manifold_vis.rst b/docs/source/examples/plotting/manifold_vis.rst deleted file mode 100644 index 95b1e9d9..00000000 --- a/docs/source/examples/plotting/manifold_vis.rst +++ /dev/null @@ -1,146 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_plotting_manifold_vis.py: - - -Using Manifolds for Visualisation -================================= - -Visualisation of data which has high dimensionality is challenging, and one solution -is to provide visualisations in low-dimension representations of the space actually -spanned by the data. Here we provide an example of visualisation of classification -predictions and relative prediction certainty (using entropy across predicted -probability for each individual class) for a toy :mod:`sklearn` dataset. - - -.. code-block:: default - - import numpy as np - import sklearn.datasets - import matplotlib.pyplot as plt - from pyrolite.util.skl.pipeline import SVC_pipeline - from pyrolite.util.skl.vis import plot_mapping - from pyrolite.util.plot import DEFAULT_DISC_COLORMAP - - np.random.seed(82) - - - - - - - - -.. code-block:: default - - wine = sklearn.datasets.load_wine() - data, target = wine["data"], wine["target"] - - - - - - - - -.. code-block:: default - - - # data = data[:, np.random.random(data.shape[1]) > 0.4] # randomly remove fraction of dimensionality - - - - - - - - - -.. code-block:: default - - - svc = SVC_pipeline(probability=True) - gs = svc.fit(data, target) - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - Fitting 10 folds for each of 1 candidates, totalling 10 fits - [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. - [Parallel(n_jobs=4)]: Done 5 out of 10 | elapsed: 1.7s remaining: 1.7s - [Parallel(n_jobs=4)]: Done 7 out of 10 | elapsed: 1.7s remaining: 0.7s - [Parallel(n_jobs=4)]: Done 10 out of 10 | elapsed: 1.7s finished - - - - - -.. code-block:: default - - fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - - a, tfm, mapped = plot_mapping( - data, gs.best_estimator_, ax=ax[1], s=50, init="pca" - ) - ax[0].scatter(*mapped.T, c=DEFAULT_DISC_COLORMAP(gs.predict(data)), s=50) - - ax[0].set_title("Predicted Classes") - ax[1].set_title("With Relative Certainty") - - for a in ax: - a.set_xticks([]) - a.set_yticks([]) - - - -.. image:: /examples/plotting/images/sphx_glr_manifold_vis_001.png - :class: sphx-glr-single-img - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 2.508 seconds) - - -.. _sphx_glr_download_examples_plotting_manifold_vis.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/plotting/manifold_vis.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: manifold_vis.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: manifold_vis.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/plotting/manifold_vis_codeobj.pickle b/docs/source/examples/plotting/manifold_vis_codeobj.pickle deleted file mode 100644 index b2779117..00000000 Binary files a/docs/source/examples/plotting/manifold_vis_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/plotting/parallel.ipynb b/docs/source/examples/plotting/parallel.ipynb deleted file mode 100644 index 025a4de6..00000000 --- a/docs/source/examples/plotting/parallel.ipynb +++ /dev/null @@ -1,130 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nParallel Coordinate Plots\n============================\n\nParallel coordinate plots are one way to visualise data relationships and clusters in\nhigher dimensional data. pyrolite now includes an implementation of this which allows\na handy quick exploratory visualisation.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.axes\nimport pyrolite.plot\nimport pyrolite.data.Aitchison" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To start, let's load up an example dataset from Aitchison\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df = pyrolite.data.Aitchison.load_coxite()\ncomp = [\n i for i in df.columns if i not in [\"Depth\", \"Porosity\"]\n] # compositional data variables" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = df.pyroplot.parallel()\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By rescaling this using the mean and standard deviation, we can account for scale\ndifferences between variables:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = df.pyroplot.parallel(rescale=True)\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can also use a centred-log transform for compositional data to reduce the effects\nof spurious correlation:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.skl.transform import CLRTransform\n\ncmap = \"inferno\"\ncompdata = df.copy()\ncompdata[comp] = CLRTransform().transform(compdata[comp])\nax = compdata.loc[:, comp].pyroplot.parallel(color_by=compdata.Depth.values, cmap=cmap)\n\n# we can add a meaningful colorbar to indicate one variable also, here Depth\nsm = plt.cm.ScalarMappable(cmap=cmap)\nsm.set_array(df.Depth)\nplt.colorbar(sm)\nplt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = compdata.loc[:, comp].pyroplot.parallel(\n rescale=True, color_by=compdata.Depth.values, cmap=cmap\n)\nplt.colorbar(sm)\nplt.show()" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/plotting/parallel.py b/docs/source/examples/plotting/parallel.py deleted file mode 100644 index e3ad5129..00000000 --- a/docs/source/examples/plotting/parallel.py +++ /dev/null @@ -1,54 +0,0 @@ -""" -Parallel Coordinate Plots -============================ - -Parallel coordinate plots are one way to visualise data relationships and clusters in -higher dimensional data. pyrolite now includes an implementation of this which allows -a handy quick exploratory visualisation. -""" -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import matplotlib.axes -import pyrolite.plot -import pyrolite.data.Aitchison -# sphinx_gallery_thumbnail_number = 3 - -######################################################################################## -# To start, let's load up an example dataset from Aitchison -# -df = pyrolite.data.Aitchison.load_coxite() -comp = [ - i for i in df.columns if i not in ["Depth", "Porosity"] -] # compositional data variables -######################################################################################## -ax = df.pyroplot.parallel() -plt.show() -######################################################################################## -# By rescaling this using the mean and standard deviation, we can account for scale -# differences between variables: -# -ax = df.pyroplot.parallel(rescale=True) -plt.show() -######################################################################################## -# We can also use a centred-log transform for compositional data to reduce the effects -# of spurious correlation: -# -from pyrolite.util.skl.transform import CLRTransform - -cmap = "inferno" -compdata = df.copy() -compdata[comp] = CLRTransform().transform(compdata[comp]) -ax = compdata.loc[:, comp].pyroplot.parallel(color_by=compdata.Depth.values, cmap=cmap) - -# we can add a meaningful colorbar to indicate one variable also, here Depth -sm = plt.cm.ScalarMappable(cmap=cmap) -sm.set_array(df.Depth) -plt.colorbar(sm) -plt.show() -######################################################################################## -ax = compdata.loc[:, comp].pyroplot.parallel( - rescale=True, color_by=compdata.Depth.values, cmap=cmap -) -plt.colorbar(sm) -plt.show() diff --git a/docs/source/examples/plotting/parallel.py.md5 b/docs/source/examples/plotting/parallel.py.md5 deleted file mode 100644 index 04de1ddf..00000000 --- a/docs/source/examples/plotting/parallel.py.md5 +++ /dev/null @@ -1 +0,0 @@ -cfa03ffba1f8ca41c17698f5f470bbba \ No newline at end of file diff --git a/docs/source/examples/plotting/parallel.rst b/docs/source/examples/plotting/parallel.rst deleted file mode 100644 index 7e22acee..00000000 --- a/docs/source/examples/plotting/parallel.rst +++ /dev/null @@ -1,165 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_plotting_parallel.py: - - -Parallel Coordinate Plots -============================ - -Parallel coordinate plots are one way to visualise data relationships and clusters in -higher dimensional data. pyrolite now includes an implementation of this which allows -a handy quick exploratory visualisation. - - -.. code-block:: default - - import numpy as np - import pandas as pd - import matplotlib.pyplot as plt - import matplotlib.axes - import pyrolite.plot - import pyrolite.data.Aitchison - - - - - - - - -To start, let's load up an example dataset from Aitchison - - - -.. code-block:: default - - df = pyrolite.data.Aitchison.load_coxite() - comp = [ - i for i in df.columns if i not in ["Depth", "Porosity"] - ] # compositional data variables - - - - - - - - -.. code-block:: default - - ax = df.pyroplot.parallel() - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_parallel_001.png - :class: sphx-glr-single-img - - - - - -By rescaling this using the mean and standard deviation, we can account for scale -differences between variables: - - - -.. code-block:: default - - ax = df.pyroplot.parallel(rescale=True) - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_parallel_002.png - :class: sphx-glr-single-img - - - - - -We can also use a centred-log transform for compositional data to reduce the effects -of spurious correlation: - - - -.. code-block:: default - - from pyrolite.util.skl.transform import CLRTransform - - cmap = "inferno" - compdata = df.copy() - compdata[comp] = CLRTransform().transform(compdata[comp]) - ax = compdata.loc[:, comp].pyroplot.parallel(color_by=compdata.Depth.values, cmap=cmap) - - # we can add a meaningful colorbar to indicate one variable also, here Depth - sm = plt.cm.ScalarMappable(cmap=cmap) - sm.set_array(df.Depth) - plt.colorbar(sm) - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_parallel_003.png - :class: sphx-glr-single-img - - - - - - -.. code-block:: default - - ax = compdata.loc[:, comp].pyroplot.parallel( - rescale=True, color_by=compdata.Depth.values, cmap=cmap - ) - plt.colorbar(sm) - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_parallel_004.png - :class: sphx-glr-single-img - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 1.124 seconds) - - -.. _sphx_glr_download_examples_plotting_parallel.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/plotting/parallel.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: parallel.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: parallel.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/plotting/parallel_codeobj.pickle b/docs/source/examples/plotting/parallel_codeobj.pickle deleted file mode 100644 index 0232a6e3..00000000 Binary files a/docs/source/examples/plotting/parallel_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/plotting/sg_execution_times.rst b/docs/source/examples/plotting/sg_execution_times.rst deleted file mode 100644 index 45ffd03d..00000000 --- a/docs/source/examples/plotting/sg_execution_times.rst +++ /dev/null @@ -1,28 +0,0 @@ - -:orphan: - -.. _sphx_glr_examples_plotting_sg_execution_times: - -Computation times -================= -**00:05.572** total execution time for **examples_plotting** files: - -+-------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_plotting_REE_v_radii.py` (``REE_v_radii.py``) | 00:03.606 | 0.0 MB | -+-------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_plotting_templates.py` (``templates.py``) | 00:01.965 | 0.0 MB | -+-------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_plotting_density.py` (``density.py``) | 00:00.000 | 0.0 MB | -+-------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_plotting_heatscatter.py` (``heatscatter.py``) | 00:00.000 | 0.0 MB | -+-------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_plotting_manifold_vis.py` (``manifold_vis.py``) | 00:00.000 | 0.0 MB | -+-------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_plotting_parallel.py` (``parallel.py``) | 00:00.000 | 0.0 MB | -+-------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_plotting_spider.py` (``spider.py``) | 00:00.000 | 0.0 MB | -+-------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_plotting_stem.py` (``stem.py``) | 00:00.000 | 0.0 MB | -+-------------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_plotting_ternary.py` (``ternary.py``) | 00:00.000 | 0.0 MB | -+-------------------------------------------------------------------------+-----------+--------+ diff --git a/docs/source/examples/plotting/spider.ipynb b/docs/source/examples/plotting/spider.ipynb deleted file mode 100644 index 6aeebac4..00000000 --- a/docs/source/examples/plotting/spider.ipynb +++ /dev/null @@ -1,187 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nSpiderplots & Density Spiderplots\n==================================\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here we'll set up an example which uses EMORB as a starting point. Typically we'll\nnormalise trace element compositions to a reference composition\nto be able to link the diagram to 'relative enrichement' occuring during geological\nprocesses, so here we're normalising to a Primitive Mantle composition first.\nWe're here taking this normalised composition and adding some noise in log-space to\ngenerate multiple compositions about this mean (i.e. a compositional distribution).\nFor simplicility, this is handlded by\n:func:`~pyrolite.util.synthetic.example_spider_data`:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.synthetic import example_spider_data\n\nnormdf = example_spider_data(start=\"EMORB_SM89\", norm_to=\"PM_PON\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ".. seealso:: `Normalisation <../geochem/normalization.html>`__\n\n\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Basic spider plots are straightforward to produce:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.plot\n\nax = normdf.pyroplot.spider(color=\"0.5\", alpha=0.5, unity_line=True, figsize=(10, 4))\nax.set_ylabel(\"X / $X_{Primitive Mantle}$\")\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The default ordering here follows that of the dataframe columns, but we typically\nwant to reorder these based on some physical ordering. A :code:`index_order` keyword\nargument can be used to supply a function which will reorder the elements before\nplotting. Here we order the elements by relative incompatiblity using\n:func:`pyrolite.geochem.ind.order_incompatibility`:\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.geochem.ind import by_incompatibility\n\nax = normdf.pyroplot.spider(\n color=\"k\",\n alpha=0.1,\n unity_line=True,\n index_order=by_incompatibility,\n figsize=(10, 4),\n)\nax.set_ylabel(\"X / $X_{Primitive Mantle}$\")\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The spiderplot can be extended to provide visualisations of ranges and density via the\nvarious modes. We could now plot the range of compositions as a filled range:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = normdf.pyroplot.spider(\n mode=\"fill\",\n color=\"green\",\n alpha=0.5,\n unity_line=True,\n index_order=by_incompatibility,\n figsize=(10, 4),\n)\nax.set_ylabel(\"X / $X_{Primitive Mantle}$\")\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Alternatively, we can plot a conditional density spider plot:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(10, 6))\nnormdf.pyroplot.spider(\n ax=ax[0], color=\"k\", alpha=0.05, unity_line=True, index_order=by_incompatibility\n)\nnormdf.pyroplot.spider(\n ax=ax[1],\n mode=\"binkde\",\n vmin=0.05, # 95th percentile,\n resolution=10,\n unity_line=True,\n index_order=by_incompatibility,\n)\n[a.set_ylabel(\"X / $X_{Primitive Mantle}$\") for a in ax]\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can now assemble a more complete comparison of some of the conditional density\nmodes for spider plots:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "modes = [\n (\"plot\", \"plot\", [], dict(color=\"k\", alpha=0.01)),\n (\"fill\", \"fill\", [], dict(color=\"k\", alpha=0.5)),\n (\"binkde\", \"binkde\", [], dict(resolution=5)),\n (\n \"binkde\",\n \"binkde contours specified\",\n [],\n dict(contours=[0.95], resolution=5), # 95th percentile contour\n ),\n (\"histogram\", \"histogram\", [], dict(resolution=5, ybins=30)),\n]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "down, across = len(modes), 1\nfig, ax = plt.subplots(\n down, across, sharey=True, sharex=True, figsize=(across * 8, 2 * down)\n)\n[a.set_ylabel(\"X / $X_{Primitive Mantle}$\") for a in ax]\nfor a, (m, name, args, kwargs) in zip(ax, modes):\n a.annotate( # label the axes rows\n \"Mode: {}\".format(name),\n xy=(0.1, 1.05),\n xycoords=a.transAxes,\n fontsize=8,\n ha=\"left\",\n va=\"bottom\",\n )\nax = ax.flat\nfor mix, (m, name, args, kwargs) in enumerate(modes):\n normdf.pyroplot.spider(\n mode=m,\n ax=ax[mix],\n vmin=0.05, # minimum percentile\n fontsize=8,\n unity_line=True,\n index_order=by_incompatibility,\n *args,\n **kwargs\n )\n\nplt.tight_layout()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ".. seealso:: `Heatscatter Plots `__,\n `Density Diagrams `__\n\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/plotting/spider.py b/docs/source/examples/plotting/spider.py deleted file mode 100644 index c9af501e..00000000 --- a/docs/source/examples/plotting/spider.py +++ /dev/null @@ -1,132 +0,0 @@ -""" -Spiderplots & Density Spiderplots -================================== -""" -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt - -# sphinx_gallery_thumbnail_number = 4 - -######################################################################################## -# Here we'll set up an example which uses EMORB as a starting point. Typically we'll -# normalise trace element compositions to a reference composition -# to be able to link the diagram to 'relative enrichement' occuring during geological -# processes, so here we're normalising to a Primitive Mantle composition first. -# We're here taking this normalised composition and adding some noise in log-space to -# generate multiple compositions about this mean (i.e. a compositional distribution). -# For simplicility, this is handlded by -# :func:`~pyrolite.util.synthetic.example_spider_data`: -# -from pyrolite.util.synthetic import example_spider_data - -normdf = example_spider_data(start="EMORB_SM89", norm_to="PM_PON") - -######################################################################################## -# .. seealso:: `Normalisation <../geochem/normalization.html>`__ -# - -######################################################################################## -# Basic spider plots are straightforward to produce: -# -import pyrolite.plot - -ax = normdf.pyroplot.spider(color="0.5", alpha=0.5, unity_line=True, figsize=(10, 4)) -ax.set_ylabel("X / $X_{Primitive Mantle}$") -plt.show() -######################################################################################## -# The default ordering here follows that of the dataframe columns, but we typically -# want to reorder these based on some physical ordering. A :code:`index_order` keyword -# argument can be used to supply a function which will reorder the elements before -# plotting. Here we order the elements by relative incompatiblity using -# :func:`pyrolite.geochem.ind.order_incompatibility`: -from pyrolite.geochem.ind import by_incompatibility - -ax = normdf.pyroplot.spider( - color="k", - alpha=0.1, - unity_line=True, - index_order=by_incompatibility, - figsize=(10, 4), -) -ax.set_ylabel("X / $X_{Primitive Mantle}$") -plt.show() -######################################################################################## -# The spiderplot can be extended to provide visualisations of ranges and density via the -# various modes. We could now plot the range of compositions as a filled range: -# -ax = normdf.pyroplot.spider( - mode="fill", - color="green", - alpha=0.5, - unity_line=True, - index_order=by_incompatibility, - figsize=(10, 4), -) -ax.set_ylabel("X / $X_{Primitive Mantle}$") -plt.show() -######################################################################################## -# Alternatively, we can plot a conditional density spider plot: -# -fig, ax = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(10, 6)) -normdf.pyroplot.spider( - ax=ax[0], color="k", alpha=0.05, unity_line=True, index_order=by_incompatibility -) -normdf.pyroplot.spider( - ax=ax[1], - mode="binkde", - vmin=0.05, # 95th percentile, - resolution=10, - unity_line=True, - index_order=by_incompatibility, -) -[a.set_ylabel("X / $X_{Primitive Mantle}$") for a in ax] -plt.show() -######################################################################################## -# We can now assemble a more complete comparison of some of the conditional density -# modes for spider plots: -# -modes = [ - ("plot", "plot", [], dict(color="k", alpha=0.01)), - ("fill", "fill", [], dict(color="k", alpha=0.5)), - ("binkde", "binkde", [], dict(resolution=5)), - ( - "binkde", - "binkde contours specified", - [], - dict(contours=[0.95], resolution=5), # 95th percentile contour - ), - ("histogram", "histogram", [], dict(resolution=5, ybins=30)), -] -######################################################################################## -down, across = len(modes), 1 -fig, ax = plt.subplots( - down, across, sharey=True, sharex=True, figsize=(across * 8, 2 * down) -) -[a.set_ylabel("X / $X_{Primitive Mantle}$") for a in ax] -for a, (m, name, args, kwargs) in zip(ax, modes): - a.annotate( # label the axes rows - "Mode: {}".format(name), - xy=(0.1, 1.05), - xycoords=a.transAxes, - fontsize=8, - ha="left", - va="bottom", - ) -ax = ax.flat -for mix, (m, name, args, kwargs) in enumerate(modes): - normdf.pyroplot.spider( - mode=m, - ax=ax[mix], - vmin=0.05, # minimum percentile - fontsize=8, - unity_line=True, - index_order=by_incompatibility, - *args, - **kwargs - ) - -plt.tight_layout() -######################################################################################## -# .. seealso:: `Heatscatter Plots `__, -# `Density Diagrams `__ diff --git a/docs/source/examples/plotting/spider.py.md5 b/docs/source/examples/plotting/spider.py.md5 deleted file mode 100644 index 33c4d4c7..00000000 --- a/docs/source/examples/plotting/spider.py.md5 +++ /dev/null @@ -1 +0,0 @@ -cabb6f5db8c734b183b6d0d21a9d652d \ No newline at end of file diff --git a/docs/source/examples/plotting/spider.rst b/docs/source/examples/plotting/spider.rst deleted file mode 100644 index 327ee30e..00000000 --- a/docs/source/examples/plotting/spider.rst +++ /dev/null @@ -1,266 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_plotting_spider.py: - - -Spiderplots & Density Spiderplots -================================== - - -.. code-block:: default - - import numpy as np - import pandas as pd - import matplotlib.pyplot as plt - - - - - - - - - -Here we'll set up an example which uses EMORB as a starting point. Typically we'll -normalise trace element compositions to a reference composition -to be able to link the diagram to 'relative enrichement' occuring during geological -processes, so here we're normalising to a Primitive Mantle composition first. -We're here taking this normalised composition and adding some noise in log-space to -generate multiple compositions about this mean (i.e. a compositional distribution). -For simplicility, this is handlded by -:func:`~pyrolite.util.synthetic.example_spider_data`: - - - -.. code-block:: default - - from pyrolite.util.synthetic import example_spider_data - - normdf = example_spider_data(start="EMORB_SM89", norm_to="PM_PON") - - - - - - - - -.. seealso:: `Normalisation <../geochem/normalization.html>`__ - - -Basic spider plots are straightforward to produce: - - - -.. code-block:: default - - import pyrolite.plot - - ax = normdf.pyroplot.spider(color="0.5", alpha=0.5, unity_line=True, figsize=(10, 4)) - ax.set_ylabel("X / $X_{Primitive Mantle}$") - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_spider_001.png - :class: sphx-glr-single-img - - - - - -The default ordering here follows that of the dataframe columns, but we typically -want to reorder these based on some physical ordering. A :code:`index_order` keyword -argument can be used to supply a function which will reorder the elements before -plotting. Here we order the elements by relative incompatiblity using -:func:`pyrolite.geochem.ind.order_incompatibility`: - - -.. code-block:: default - - from pyrolite.geochem.ind import by_incompatibility - - ax = normdf.pyroplot.spider( - color="k", - alpha=0.1, - unity_line=True, - index_order=by_incompatibility, - figsize=(10, 4), - ) - ax.set_ylabel("X / $X_{Primitive Mantle}$") - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_spider_002.png - :class: sphx-glr-single-img - - - - - -The spiderplot can be extended to provide visualisations of ranges and density via the -various modes. We could now plot the range of compositions as a filled range: - - - -.. code-block:: default - - ax = normdf.pyroplot.spider( - mode="fill", - color="green", - alpha=0.5, - unity_line=True, - index_order=by_incompatibility, - figsize=(10, 4), - ) - ax.set_ylabel("X / $X_{Primitive Mantle}$") - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_spider_003.png - :class: sphx-glr-single-img - - - - - -Alternatively, we can plot a conditional density spider plot: - - - -.. code-block:: default - - fig, ax = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(10, 6)) - normdf.pyroplot.spider( - ax=ax[0], color="k", alpha=0.05, unity_line=True, index_order=by_incompatibility - ) - normdf.pyroplot.spider( - ax=ax[1], - mode="binkde", - vmin=0.05, # 95th percentile, - resolution=10, - unity_line=True, - index_order=by_incompatibility, - ) - [a.set_ylabel("X / $X_{Primitive Mantle}$") for a in ax] - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_spider_004.png - :class: sphx-glr-single-img - - - - - -We can now assemble a more complete comparison of some of the conditional density -modes for spider plots: - - - -.. code-block:: default - - modes = [ - ("plot", "plot", [], dict(color="k", alpha=0.01)), - ("fill", "fill", [], dict(color="k", alpha=0.5)), - ("binkde", "binkde", [], dict(resolution=5)), - ( - "binkde", - "binkde contours specified", - [], - dict(contours=[0.95], resolution=5), # 95th percentile contour - ), - ("histogram", "histogram", [], dict(resolution=5, ybins=30)), - ] - - - - - - - - -.. code-block:: default - - down, across = len(modes), 1 - fig, ax = plt.subplots( - down, across, sharey=True, sharex=True, figsize=(across * 8, 2 * down) - ) - [a.set_ylabel("X / $X_{Primitive Mantle}$") for a in ax] - for a, (m, name, args, kwargs) in zip(ax, modes): - a.annotate( # label the axes rows - "Mode: {}".format(name), - xy=(0.1, 1.05), - xycoords=a.transAxes, - fontsize=8, - ha="left", - va="bottom", - ) - ax = ax.flat - for mix, (m, name, args, kwargs) in enumerate(modes): - normdf.pyroplot.spider( - mode=m, - ax=ax[mix], - vmin=0.05, # minimum percentile - fontsize=8, - unity_line=True, - index_order=by_incompatibility, - *args, - **kwargs - ) - - plt.tight_layout() - - - -.. image:: /examples/plotting/images/sphx_glr_spider_005.png - :class: sphx-glr-single-img - - - - - -.. seealso:: `Heatscatter Plots `__, - `Density Diagrams `__ - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 7.640 seconds) - - -.. _sphx_glr_download_examples_plotting_spider.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/plotting/spider.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: spider.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: spider.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/plotting/spider_codeobj.pickle b/docs/source/examples/plotting/spider_codeobj.pickle deleted file mode 100644 index 37245e75..00000000 Binary files a/docs/source/examples/plotting/spider_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/plotting/stem.ipynb b/docs/source/examples/plotting/stem.ipynb deleted file mode 100644 index 1f8f3319..00000000 --- a/docs/source/examples/plotting/stem.ipynb +++ /dev/null @@ -1,108 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nStem Plots\n============\n\nStem plots are commonly used to visualise discrete distributions of data,\nand are useful to highlight discrete observations where the precision of values along\none axis is high (e.g. an independent spatial measure like depth) and the other is less\nso (such that the sampling frequency along this axis is important, which is not\nemphasised by a scatter plot).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyrolite.plot import pyroplot\nfrom pyrolite.plot.stem import stem\n\n\nnp.random.seed(82)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First let's create some example data:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "x = np.linspace(0, 10, 10) + np.random.randn(10) / 2.0\ny = np.random.rand(10)\ndf = pd.DataFrame(np.vstack([x, y]).T, columns=[\"Depth\", \"Fe3O4\"])" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "A minimal stem plot can be constructed as follows:\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = df.pyroplot.stem(color=\"k\", figsize=(5, 3))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Stem plots can also be used in a vertical orientation, such as for visualising\ndiscrete observations down a drill hole:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = df.pyroplot.stem(\n orientation=\"vertical\",\n s=12,\n linestyle=\"--\",\n linewidth=0.5,\n color=\"k\",\n figsize=(3, 5),\n)\n# the yaxes can then be inverted using:\nax.invert_yaxis()\n# and if you'd like the xaxis to be labeled at the top:\nax.xaxis.set_ticks_position(\"top\")\nax.xaxis.set_label_position(\"top\")" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/plotting/stem.py b/docs/source/examples/plotting/stem.py deleted file mode 100644 index 9d1afd3e..00000000 --- a/docs/source/examples/plotting/stem.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -Stem Plots -============ - -Stem plots are commonly used to visualise discrete distributions of data, -and are useful to highlight discrete observations where the precision of values along -one axis is high (e.g. an independent spatial measure like depth) and the other is less -so (such that the sampling frequency along this axis is important, which is not -emphasised by a scatter plot). -""" -import pandas as pd -import numpy as np -import matplotlib.pyplot as plt -from pyrolite.plot import pyroplot -from pyrolite.plot.stem import stem - -# sphinx_gallery_thumbnail_number = 2 - -np.random.seed(82) -######################################################################################## -# First let's create some example data: -# -x = np.linspace(0, 10, 10) + np.random.randn(10) / 2.0 -y = np.random.rand(10) -df = pd.DataFrame(np.vstack([x, y]).T, columns=["Depth", "Fe3O4"]) -######################################################################################## -# A minimal stem plot can be constructed as follows: -ax = df.pyroplot.stem(color="k", figsize=(5, 3)) -######################################################################################## -# Stem plots can also be used in a vertical orientation, such as for visualising -# discrete observations down a drill hole: -# -ax = df.pyroplot.stem( - orientation="vertical", - s=12, - linestyle="--", - linewidth=0.5, - color="k", - figsize=(3, 5), -) -# the yaxes can then be inverted using: -ax.invert_yaxis() -# and if you'd like the xaxis to be labeled at the top: -ax.xaxis.set_ticks_position("top") -ax.xaxis.set_label_position("top") diff --git a/docs/source/examples/plotting/stem.py.md5 b/docs/source/examples/plotting/stem.py.md5 deleted file mode 100644 index bf9a434c..00000000 --- a/docs/source/examples/plotting/stem.py.md5 +++ /dev/null @@ -1 +0,0 @@ -92808137b17c70b57ee740353448bf67 \ No newline at end of file diff --git a/docs/source/examples/plotting/stem.rst b/docs/source/examples/plotting/stem.rst deleted file mode 100644 index 6adb9c09..00000000 --- a/docs/source/examples/plotting/stem.rst +++ /dev/null @@ -1,132 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_plotting_stem.py: - - -Stem Plots -============ - -Stem plots are commonly used to visualise discrete distributions of data, -and are useful to highlight discrete observations where the precision of values along -one axis is high (e.g. an independent spatial measure like depth) and the other is less -so (such that the sampling frequency along this axis is important, which is not -emphasised by a scatter plot). - - -.. code-block:: default - - import pandas as pd - import numpy as np - import matplotlib.pyplot as plt - from pyrolite.plot import pyroplot - from pyrolite.plot.stem import stem - - - np.random.seed(82) - - - - - - - -First let's create some example data: - - - -.. code-block:: default - - x = np.linspace(0, 10, 10) + np.random.randn(10) / 2.0 - y = np.random.rand(10) - df = pd.DataFrame(np.vstack([x, y]).T, columns=["Depth", "Fe3O4"]) - - - - - - - -A minimal stem plot can be constructed as follows: - - -.. code-block:: default - - ax = df.pyroplot.stem(color="k", figsize=(5, 3)) - - - -.. image:: /examples/plotting/images/sphx_glr_stem_001.png - :class: sphx-glr-single-img - - - - - -Stem plots can also be used in a vertical orientation, such as for visualising -discrete observations down a drill hole: - - - -.. code-block:: default - - ax = df.pyroplot.stem( - orientation="vertical", - s=12, - linestyle="--", - linewidth=0.5, - color="k", - figsize=(3, 5), - ) - # the yaxes can then be inverted using: - ax.invert_yaxis() - # and if you'd like the xaxis to be labeled at the top: - ax.xaxis.set_ticks_position("top") - ax.xaxis.set_label_position("top") - - - -.. image:: /examples/plotting/images/sphx_glr_stem_002.png - :class: sphx-glr-single-img - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 0.454 seconds) - - -.. _sphx_glr_download_examples_plotting_stem.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/plotting/stem.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: stem.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: stem.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/plotting/stem_codeobj.pickle b/docs/source/examples/plotting/stem_codeobj.pickle deleted file mode 100644 index 11873cd6..00000000 Binary files a/docs/source/examples/plotting/stem_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/plotting/templates.ipynb b/docs/source/examples/plotting/templates.ipynb deleted file mode 100644 index d2ad8dfb..00000000 --- a/docs/source/examples/plotting/templates.ipynb +++ /dev/null @@ -1,108 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nPlot Templates\n============================\n\n:mod:`pyrolite` includes some ready-made templates for well-known plots. These can\nbe used to create new plots, or add a template to an existing\n:class:`matplotlib.axes.Axes`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\nfrom pyrolite.util.plot.axes import share_axes" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First let's build a simple total-alkali vs silica (\n:func:`~pyrolite.plot.templates.TAS`) diagram:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.plot.templates import TAS\n\nax = TAS(linewidth=0.5, labels='ID')\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The other templates currently included in :mod:`pyrolite` are the\n:func:`~pyrolite.plot.templates.pearceThNbYb` and\n:func:`~pyrolite.plot.templates.pearceTiNbYb` diagrams.\nWe can create some axes and add these templates to them:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.plot.templates import pearceThNbYb, pearceTiNbYb\n\nfig, ax = plt.subplots(1, 2, figsize=(10, 4))\nshare_axes(ax, which=\"x\") # these diagrams have the same x axis\n\npearceThNbYb(ax=ax[0])\npearceTiNbYb(ax=ax[1])\n\nplt.tight_layout() # nicer spacing for axis labels" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "References and other notes for diagram templates can be found within the docstrings\nand within the pyrolite documentation:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "help(TAS)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/plotting/templates.py b/docs/source/examples/plotting/templates.py deleted file mode 100644 index df8bdaaf..00000000 --- a/docs/source/examples/plotting/templates.py +++ /dev/null @@ -1,42 +0,0 @@ -""" -Plot Templates -============================ - -:mod:`pyrolite` includes some ready-made templates for well-known plots. These can -be used to create new plots, or add a template to an existing -:class:`matplotlib.axes.Axes`. -""" -import matplotlib.pyplot as plt -from pyrolite.util.plot.axes import share_axes - -# sphinx_gallery_thumbnail_number = 2 - -######################################################################################## -# First let's build a simple total-alkali vs silica ( -# :func:`~pyrolite.plot.templates.TAS`) diagram: -# -from pyrolite.plot.templates import TAS - -ax = TAS(linewidth=0.5, labels='ID') -plt.show() -######################################################################################## -# The other templates currently included in :mod:`pyrolite` are the -# :func:`~pyrolite.plot.templates.pearceThNbYb` and -# :func:`~pyrolite.plot.templates.pearceTiNbYb` diagrams. -# We can create some axes and add these templates to them: -# -from pyrolite.plot.templates import pearceThNbYb, pearceTiNbYb - -fig, ax = plt.subplots(1, 2, figsize=(10, 4)) -share_axes(ax, which="x") # these diagrams have the same x axis - -pearceThNbYb(ax=ax[0]) -pearceTiNbYb(ax=ax[1]) - -plt.tight_layout() # nicer spacing for axis labels - -######################################################################################## -# References and other notes for diagram templates can be found within the docstrings -# and within the pyrolite documentation: -# -help(TAS) diff --git a/docs/source/examples/plotting/templates.py.md5 b/docs/source/examples/plotting/templates.py.md5 deleted file mode 100644 index dfd509bc..00000000 --- a/docs/source/examples/plotting/templates.py.md5 +++ /dev/null @@ -1 +0,0 @@ -3e600a370d3f87dfdd277594be64bb1d \ No newline at end of file diff --git a/docs/source/examples/plotting/templates.rst b/docs/source/examples/plotting/templates.rst deleted file mode 100644 index 96c3dd0d..00000000 --- a/docs/source/examples/plotting/templates.rst +++ /dev/null @@ -1,162 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_plotting_templates.py: - - -Plot Templates -============================ - -:mod:`pyrolite` includes some ready-made templates for well-known plots. These can -be used to create new plots, or add a template to an existing -:class:`matplotlib.axes.Axes`. - - -.. code-block:: default - - import matplotlib.pyplot as plt - from pyrolite.util.plot.axes import share_axes - - - - - - - - - -First let's build a simple total-alkali vs silica ( -:func:`~pyrolite.plot.templates.TAS`) diagram: - - - -.. code-block:: default - - from pyrolite.plot.templates import TAS - - ax = TAS(linewidth=0.5, labels='ID') - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_templates_001.png - :class: sphx-glr-single-img - - - - - -The other templates currently included in :mod:`pyrolite` are the -:func:`~pyrolite.plot.templates.pearceThNbYb` and -:func:`~pyrolite.plot.templates.pearceTiNbYb` diagrams. -We can create some axes and add these templates to them: - - - -.. code-block:: default - - from pyrolite.plot.templates import pearceThNbYb, pearceTiNbYb - - fig, ax = plt.subplots(1, 2, figsize=(10, 4)) - share_axes(ax, which="x") # these diagrams have the same x axis - - pearceThNbYb(ax=ax[0]) - pearceTiNbYb(ax=ax[1]) - - plt.tight_layout() # nicer spacing for axis labels - - - - -.. image:: /examples/plotting/images/sphx_glr_templates_002.png - :class: sphx-glr-single-img - - - - - -References and other notes for diagram templates can be found within the docstrings -and within the pyrolite documentation: - - - -.. code-block:: default - - help(TAS) - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - Help on function TAS in module pyrolite.plot.templates.TAS: - - TAS(ax=None, relim=True, color='k', **kwargs) - Adds the TAS diagram from Le Bas (1992) [#pyrolite.plot.templates.TAS.TAS_1]_ to an axes. - - Parameters - ---------- - ax : :class:`matplotlib.axes.Axes` - Axes to add the template on to. - relim : :class:`bool` - Whether to relimit axes to fit the built in ranges for this diagram. - color : :class:`str` - Line color for the diagram. - - Returns - ------- - ax : :class:`matplotlib.axes.Axes` - - References - ----------- - .. [#pyrolite.plot.templates.TAS.TAS_1] Le Bas, M.J., Le Maitre, R.W., Woolley, A.R., 1992. - The construction of the Total Alkali-Silica chemical - classification of volcanic rocks. - Mineralogy and Petrology 46, 1–22. - doi: `10.1007/BF01160698 `__ - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 1.965 seconds) - - -.. _sphx_glr_download_examples_plotting_templates.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/plotting/templates.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: templates.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: templates.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/plotting/templates_codeobj.pickle b/docs/source/examples/plotting/templates_codeobj.pickle deleted file mode 100644 index af791b7d..00000000 Binary files a/docs/source/examples/plotting/templates_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/plotting/ternary.ipynb b/docs/source/examples/plotting/ternary.ipynb deleted file mode 100644 index b9b84229..00000000 --- a/docs/source/examples/plotting/ternary.ipynb +++ /dev/null @@ -1,133 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nTernary Plots\n=============\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyrolite.plot import pyroplot\n\nnp.random.seed(82)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let's first create some example data:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df = pd.DataFrame(data=np.exp(np.random.rand(100, 3)), columns=[\"SiO2\", \"MgO\", \"CaO\"])\ndf.loc[:, [\"SiO2\", \"MgO\", \"CaO\"]].head()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now we can create a simple scatter plot:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = df.loc[:, [\"SiO2\", \"MgO\", \"CaO\"]].pyroplot.scatter(c=\"k\")\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If the data represent some continuting, you could also simply plot them as lines:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax = df.loc[:, [\"SiO2\", \"MgO\", \"CaO\"]].pyroplot.plot(color=\"k\", alpha=0.5)\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The plotting axis can be specified to use exisiting axes:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12, 5))\n\ndf.loc[:, [\"SiO2\", \"MgO\", \"CaO\"]].sample(20).pyroplot.scatter(ax=ax[0], c=\"k\")\ndf.loc[:, [\"SiO2\", \"MgO\", \"CaO\"]].sample(20).pyroplot.scatter(ax=ax[1], c=\"g\")\n\nax = fig.orderedaxes # creating scatter plots reorders axes, this is the correct order\nplt.tight_layout()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - ".. seealso:: `Heatscatter Plots `__,\n `Density Plots `__,\n `Spider Density Diagrams `__\n\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/plotting/ternary.py b/docs/source/examples/plotting/ternary.py deleted file mode 100644 index ef17fcb3..00000000 --- a/docs/source/examples/plotting/ternary.py +++ /dev/null @@ -1,39 +0,0 @@ -""" -Ternary Plots -============= -""" -import pandas as pd -import numpy as np -import matplotlib.pyplot as plt -from pyrolite.plot import pyroplot - -np.random.seed(82) -######################################################################################## -# Let's first create some example data: -# -df = pd.DataFrame(data=np.exp(np.random.rand(100, 3)), columns=["SiO2", "MgO", "CaO"]) -df.loc[:, ["SiO2", "MgO", "CaO"]].head() -######################################################################################## -# Now we can create a simple scatter plot: -# -ax = df.loc[:, ["SiO2", "MgO", "CaO"]].pyroplot.scatter(c="k") -plt.show() -######################################################################################## -# If the data represent some continuting, you could also simply plot them as lines: -# -ax = df.loc[:, ["SiO2", "MgO", "CaO"]].pyroplot.plot(color="k", alpha=0.5) -plt.show() -######################################################################################## -# The plotting axis can be specified to use exisiting axes: -# -fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12, 5)) - -df.loc[:, ["SiO2", "MgO", "CaO"]].sample(20).pyroplot.scatter(ax=ax[0], c="k") -df.loc[:, ["SiO2", "MgO", "CaO"]].sample(20).pyroplot.scatter(ax=ax[1], c="g") - -ax = fig.orderedaxes # creating scatter plots reorders axes, this is the correct order -plt.tight_layout() -######################################################################################## -# .. seealso:: `Heatscatter Plots `__, -# `Density Plots `__, -# `Spider Density Diagrams `__ diff --git a/docs/source/examples/plotting/ternary.py.md5 b/docs/source/examples/plotting/ternary.py.md5 deleted file mode 100644 index 7c4afd2f..00000000 --- a/docs/source/examples/plotting/ternary.py.md5 +++ /dev/null @@ -1 +0,0 @@ -7cfd3ee7de15583a81bc58c0ccebc451 \ No newline at end of file diff --git a/docs/source/examples/plotting/ternary.rst b/docs/source/examples/plotting/ternary.rst deleted file mode 100644 index 3f7b7d32..00000000 --- a/docs/source/examples/plotting/ternary.rst +++ /dev/null @@ -1,202 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_plotting_ternary.py: - - -Ternary Plots -============= - - -.. code-block:: default - - import pandas as pd - import numpy as np - import matplotlib.pyplot as plt - from pyrolite.plot import pyroplot - - np.random.seed(82) - - - - - - - -Let's first create some example data: - - - -.. code-block:: default - - df = pd.DataFrame(data=np.exp(np.random.rand(100, 3)), columns=["SiO2", "MgO", "CaO"]) - df.loc[:, ["SiO2", "MgO", "CaO"]].head() - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SiO2MgOCaO
01.3168281.8950231.866191
12.1772061.6130292.609435
22.7113162.2990901.226108
31.1434501.8496841.809385
41.9055692.6877931.398168
-
-
-
- -Now we can create a simple scatter plot: - - - -.. code-block:: default - - ax = df.loc[:, ["SiO2", "MgO", "CaO"]].pyroplot.scatter(c="k") - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_ternary_001.png - :class: sphx-glr-single-img - - - - - -If the data represent some continuting, you could also simply plot them as lines: - - - -.. code-block:: default - - ax = df.loc[:, ["SiO2", "MgO", "CaO"]].pyroplot.plot(color="k", alpha=0.5) - plt.show() - - - -.. image:: /examples/plotting/images/sphx_glr_ternary_002.png - :class: sphx-glr-single-img - - - - - -The plotting axis can be specified to use exisiting axes: - - - -.. code-block:: default - - fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12, 5)) - - df.loc[:, ["SiO2", "MgO", "CaO"]].sample(20).pyroplot.scatter(ax=ax[0], c="k") - df.loc[:, ["SiO2", "MgO", "CaO"]].sample(20).pyroplot.scatter(ax=ax[1], c="g") - - ax = fig.orderedaxes # creating scatter plots reorders axes, this is the correct order - plt.tight_layout() - - - -.. image:: /examples/plotting/images/sphx_glr_ternary_003.png - :class: sphx-glr-single-img - - - - - -.. seealso:: `Heatscatter Plots `__, - `Density Plots `__, - `Spider Density Diagrams `__ - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 2.353 seconds) - - -.. _sphx_glr_download_examples_plotting_ternary.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/plotting/ternary.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: ternary.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: ternary.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/plotting/ternary_codeobj.pickle b/docs/source/examples/plotting/ternary_codeobj.pickle deleted file mode 100644 index eaabeadf..00000000 Binary files a/docs/source/examples/plotting/ternary_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/searchindex.bak b/docs/source/examples/searchindex.bak deleted file mode 100644 index ce911e83..00000000 --- a/docs/source/examples/searchindex.bak +++ /dev/null @@ -1,3 +0,0 @@ -'C:\\GitHub\\pyrolite\\docs\\build\\html\\index.html', (0, 11239) -'C:\\GitHub\\pyrolite\\docs\\build\\html\\_static\\documentation_options.js', (11264, 325) -'C:\\GitHub\\pyrolite\\docs\\build\\html\\searchindex.js', (11776, 81850) diff --git a/docs/source/examples/searchindex.dat b/docs/source/examples/searchindex.dat deleted file mode 100644 index fa8991bd..00000000 Binary files a/docs/source/examples/searchindex.dat and /dev/null differ diff --git a/docs/source/examples/searchindex.dir b/docs/source/examples/searchindex.dir deleted file mode 100644 index ce911e83..00000000 --- a/docs/source/examples/searchindex.dir +++ /dev/null @@ -1,3 +0,0 @@ -'C:\\GitHub\\pyrolite\\docs\\build\\html\\index.html', (0, 11239) -'C:\\GitHub\\pyrolite\\docs\\build\\html\\_static\\documentation_options.js', (11264, 325) -'C:\\GitHub\\pyrolite\\docs\\build\\html\\searchindex.js', (11776, 81850) diff --git a/docs/source/examples/util/TAS.ipynb b/docs/source/examples/util/TAS.ipynb deleted file mode 100644 index 2d55a98b..00000000 --- a/docs/source/examples/util/TAS.ipynb +++ /dev/null @@ -1,126 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nTAS Classifier\n==============\n\nSome simple discrimination methods are implemented,\nincluding the Total Alkali-Silica (TAS) classification.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pyrolite.util.classification import TAS\nfrom pyrolite.util.synthetic import test_df, random_cov_matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We'll first generate some synthetic data to play with:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df = (\n test_df(\n cols=[\"SiO2\", \"Na2O\", \"K2O\", \"Al2O3\"],\n mean=[0.5, 0.04, 0.05, 0.4],\n index_length=100,\n seed=49,\n )\n * 100\n)\n\ndf.head(3)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can visualise how this chemistry corresponds to the TAS diagram:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.plot\n\ndf[\"Na2O + K2O\"] = df[\"Na2O\"] + df[\"K2O\"]\ncm = TAS()\n\nfig, ax = plt.subplots(1)\ncm.add_to_axes(\n ax, alpha=0.5, linewidth=0.5, zorder=-1, labels=\"ID\",\n)\ndf[[\"SiO2\", \"Na2O + K2O\"]].pyroplot.scatter(ax=ax, c=\"k\", alpha=0.2)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can now classify this data according to the fields of the TAS diagram, and\nadd this as a column to the dataframe. Similarly, we can extract which rock names\nthe TAS fields correspond to:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "df[\"TAS\"] = cm.predict(df)\ndf[\"Rocknames\"] = df.TAS.apply(lambda x: cm.fields.get(x, {\"name\": None})[\"name\"])\ndf[\"Rocknames\"].sample(10) # randomly check 10 sample rocknames" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We could now take the TAS classes and use them to colorize our points for plotting\non the TAS diagram, or more likely, on another plot. Here the relationship to the\nTAS diagram is illustrated:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(1)\n\ncm.add_to_axes(ax, alpha=0.5, linewidth=0.5, zorder=-1, labels=\"ID\")\ndf[[\"SiO2\", \"Na2O + K2O\"]].pyroplot.scatter(ax=ax, c=df['TAS'], alpha=0.7)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/util/TAS.py b/docs/source/examples/util/TAS.py deleted file mode 100644 index 194fd62f..00000000 --- a/docs/source/examples/util/TAS.py +++ /dev/null @@ -1,61 +0,0 @@ -""" -TAS Classifier -============== - -Some simple discrimination methods are implemented, -including the Total Alkali-Silica (TAS) classification. -""" -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from pyrolite.util.classification import TAS -from pyrolite.util.synthetic import test_df, random_cov_matrix - -# sphinx_gallery_thumbnail_number = 2 -######################################################################################## -# We'll first generate some synthetic data to play with: -# -df = ( - test_df( - cols=["SiO2", "Na2O", "K2O", "Al2O3"], - mean=[0.5, 0.04, 0.05, 0.4], - index_length=100, - seed=49, - ) - * 100 -) - -df.head(3) -######################################################################################## -# We can visualise how this chemistry corresponds to the TAS diagram: -# -import pyrolite.plot - -df["Na2O + K2O"] = df["Na2O"] + df["K2O"] -cm = TAS() - -fig, ax = plt.subplots(1) -cm.add_to_axes( - ax, alpha=0.5, linewidth=0.5, zorder=-1, labels="ID", -) -df[["SiO2", "Na2O + K2O"]].pyroplot.scatter(ax=ax, c="k", alpha=0.2) - - -######################################################################################## -# We can now classify this data according to the fields of the TAS diagram, and -# add this as a column to the dataframe. Similarly, we can extract which rock names -# the TAS fields correspond to: -# -df["TAS"] = cm.predict(df) -df["Rocknames"] = df.TAS.apply(lambda x: cm.fields.get(x, {"name": None})["name"]) -df["Rocknames"].sample(10) # randomly check 10 sample rocknames -######################################################################################## -# We could now take the TAS classes and use them to colorize our points for plotting -# on the TAS diagram, or more likely, on another plot. Here the relationship to the -# TAS diagram is illustrated: -# - -fig, ax = plt.subplots(1) - -cm.add_to_axes(ax, alpha=0.5, linewidth=0.5, zorder=-1, labels="ID") -df[["SiO2", "Na2O + K2O"]].pyroplot.scatter(ax=ax, c=df['TAS'], alpha=0.7) diff --git a/docs/source/examples/util/TAS.py.md5 b/docs/source/examples/util/TAS.py.md5 deleted file mode 100644 index febdf750..00000000 --- a/docs/source/examples/util/TAS.py.md5 +++ /dev/null @@ -1 +0,0 @@ -100a276932f0f6efcd9c9760511b26ff \ No newline at end of file diff --git a/docs/source/examples/util/TAS.rst b/docs/source/examples/util/TAS.rst deleted file mode 100644 index 8d48f610..00000000 --- a/docs/source/examples/util/TAS.rst +++ /dev/null @@ -1,246 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_util_TAS.py: - - -TAS Classifier -============== - -Some simple discrimination methods are implemented, -including the Total Alkali-Silica (TAS) classification. - - -.. code-block:: default - - import numpy as np - import pandas as pd - import matplotlib.pyplot as plt - from pyrolite.util.classification import TAS - from pyrolite.util.synthetic import test_df, random_cov_matrix - - - - - - - - -We'll first generate some synthetic data to play with: - - - -.. code-block:: default - - df = ( - test_df( - cols=["SiO2", "Na2O", "K2O", "Al2O3"], - mean=[0.5, 0.04, 0.05, 0.4], - index_length=100, - seed=49, - ) - * 100 - ) - - df.head(3) - - - - - -.. only:: builder_html - - .. raw:: html - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SiO2Na2OK2OAl2O3
048.5977853.8337754.69536642.873074
150.0963003.9603785.19613040.747192
251.3815664.1264365.18105139.310947
-
-
-
- -We can visualise how this chemistry corresponds to the TAS diagram: - - - -.. code-block:: default - - import pyrolite.plot - - df["Na2O + K2O"] = df["Na2O"] + df["K2O"] - cm = TAS() - - fig, ax = plt.subplots(1) - cm.add_to_axes( - ax, alpha=0.5, linewidth=0.5, zorder=-1, labels="ID", - ) - df[["SiO2", "Na2O + K2O"]].pyroplot.scatter(ax=ax, c="k", alpha=0.2) - - - - - -.. image:: /examples/util/images/sphx_glr_TAS_001.png - :class: sphx-glr-single-img - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - - - - -We can now classify this data according to the fields of the TAS diagram, and -add this as a column to the dataframe. Similarly, we can extract which rock names -the TAS fields correspond to: - - - -.. code-block:: default - - df["TAS"] = cm.predict(df) - df["Rocknames"] = df.TAS.apply(lambda x: cm.fields.get(x, {"name": None})["name"]) - df["Rocknames"].sample(10) # randomly check 10 sample rocknames - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - 78 [Phonotephrite, Foid Monzodiorite] - 2 [Phonotephrite, Foid Monzodiorite] - 56 [Phonotephrite, Foid Monzodiorite] - 41 [Phonotephrite, Foid Monzodiorite] - 93 [Phonotephrite, Foid Monzodiorite] - 60 [Phonotephrite, Foid Monzodiorite] - 61 [Phonotephrite, Foid Monzodiorite] - 47 [Phonotephrite, Foid Monzodiorite] - 4 [Trachyandesite, Foidolite] - 12 [Trachyandesite, Foidolite] - Name: Rocknames, dtype: object - - - -We could now take the TAS classes and use them to colorize our points for plotting -on the TAS diagram, or more likely, on another plot. Here the relationship to the -TAS diagram is illustrated: - - - -.. code-block:: default - - - fig, ax = plt.subplots(1) - - cm.add_to_axes(ax, alpha=0.5, linewidth=0.5, zorder=-1, labels="ID") - df[["SiO2", "Na2O + K2O"]].pyroplot.scatter(ax=ax, c=df['TAS'], alpha=0.7) - - - -.. image:: /examples/util/images/sphx_glr_TAS_002.png - :class: sphx-glr-single-img - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 0.488 seconds) - - -.. _sphx_glr_download_examples_util_TAS.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/util/TAS.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: TAS.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: TAS.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/util/TAS_codeobj.pickle b/docs/source/examples/util/TAS_codeobj.pickle deleted file mode 100644 index 12da70ee..00000000 Binary files a/docs/source/examples/util/TAS_codeobj.pickle and /dev/null differ diff --git a/docs/source/examples/util/images/sphx_glr_TAS_001.png b/docs/source/examples/util/images/sphx_glr_TAS_001.png deleted file mode 100644 index a604e95c..00000000 Binary files a/docs/source/examples/util/images/sphx_glr_TAS_001.png and /dev/null differ diff --git a/docs/source/examples/util/images/sphx_glr_TAS_002.png b/docs/source/examples/util/images/sphx_glr_TAS_002.png deleted file mode 100644 index e05ed1da..00000000 Binary files a/docs/source/examples/util/images/sphx_glr_TAS_002.png and /dev/null differ diff --git a/docs/source/examples/util/images/sphx_glr_timescale_001.png b/docs/source/examples/util/images/sphx_glr_timescale_001.png deleted file mode 100644 index 94abe150..00000000 Binary files a/docs/source/examples/util/images/sphx_glr_timescale_001.png and /dev/null differ diff --git a/docs/source/examples/util/images/sphx_glr_timescale_002.png b/docs/source/examples/util/images/sphx_glr_timescale_002.png deleted file mode 100644 index 17b56d7a..00000000 Binary files a/docs/source/examples/util/images/sphx_glr_timescale_002.png and /dev/null differ diff --git a/docs/source/examples/util/images/thumb/sphx_glr_TAS_thumb.png b/docs/source/examples/util/images/thumb/sphx_glr_TAS_thumb.png deleted file mode 100644 index 09fbd937..00000000 Binary files a/docs/source/examples/util/images/thumb/sphx_glr_TAS_thumb.png and /dev/null differ diff --git a/docs/source/examples/util/images/thumb/sphx_glr_timescale_thumb.png b/docs/source/examples/util/images/thumb/sphx_glr_timescale_thumb.png deleted file mode 100644 index ad2c33a0..00000000 Binary files a/docs/source/examples/util/images/thumb/sphx_glr_timescale_thumb.png and /dev/null differ diff --git a/docs/source/examples/util/sg_execution_times.rst b/docs/source/examples/util/sg_execution_times.rst deleted file mode 100644 index 76282d9e..00000000 --- a/docs/source/examples/util/sg_execution_times.rst +++ /dev/null @@ -1,14 +0,0 @@ - -:orphan: - -.. _sphx_glr_examples_util_sg_execution_times: - -Computation times -================= -**00:00.488** total execution time for **examples_util** files: - -+---------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_util_TAS.py` (``TAS.py``) | 00:00.488 | 0.0 MB | -+---------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_examples_util_timescale.py` (``timescale.py``) | 00:00.000 | 0.0 MB | -+---------------------------------------------------------------+-----------+--------+ diff --git a/docs/source/examples/util/timescale.ipynb b/docs/source/examples/util/timescale.ipynb deleted file mode 100644 index 802b464d..00000000 --- a/docs/source/examples/util/timescale.ipynb +++ /dev/null @@ -1,169 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nGeological Timescale\n======================\n\npyrolite includes a simple geological timescale, based on a recent verion\nof the International Chronostratigraphic Chart [#ICS]_. The\n:class:`~pyrolite.util.time.Timescale` class can be used to look up names for\nspecific geological ages, to look up times for known geological age names\nand to access a reference table for all of these.\n\n.. [#ICS] Cohen, K.M., Finney, S.C., Gibbard, P.L., Fan, J.-X., 2013.\n `The ICS International Chronostratigraphic Chart `__.\n Episodes 36, 199\u2013204.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First we'll create a timescale:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.time import Timescale\nts = Timescale()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "From this we can look up the names of ages (in million years, or Ma):\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ts.named_age(1212.1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As geological age names are hierarchical, the name you give an age depends on what\nlevel you're looking at. By default, the timescale will return the most specific\nnon-null level. The levels accessible within the timescale are listed\nas an attribute:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ts.levels" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These can be used to refine the output names to your desired level of specificity\n(noting that for some ages, the levels which are accessible can differ; see the chart):\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ts.named_age(1212.1, level=\"Epoch\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The timescale can also do the inverse for you, and return the timing information for a\ngiven named age:\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ts.text2age(\"Holocene\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can use this to create a simple template to visualise the geological timescale:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pandas as pd\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1, figsize=(5, 10))\n\nfor ix, level in enumerate(ts.levels):\n ldf = ts.data.loc[ts.data.Level == level, :]\n for pix, period in ldf.iterrows():\n ax.bar(\n ix,\n period.Start - period.End,\n facecolor=period.Color,\n bottom=period.End,\n width=1,\n edgecolor=\"k\",\n )\n\nax.set_xticks(range(len(ts.levels)))\nax.set_xticklabels(ts.levels, rotation=60)\nax.xaxis.set_ticks_position(\"top\")\nax.set_ylabel(\"Age (Ma)\")\nax.invert_yaxis()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This doesn't quite look like the geological timescale you may be used to. We can improve\non the output somewhat with a bit of customisation for the positioning. Notably, this is\nless readable, but produces something closer to what we're after. Some of this may soon\nbe integrated as a :class:`~pyrolite.util.time.Timescale` method, if there's interest.\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\nfrom matplotlib.patches import Rectangle\n\n# first let's set up some x-limits for the different timescale levels\nxlims = {\n \"Eon\": (0, 1),\n \"Era\": (1, 2),\n \"Period\": (2, 3),\n \"Superepoch\": (3, 4),\n \"Epoch\": (3, 5),\n \"Age\": (5, 7),\n}\n\n\nfig, ax = plt.subplots(1, figsize=(4, 10))\n\nfor ix, level in enumerate(ts.levels[::-1]):\n ldf = ts.data.loc[ts.data.Level == level, :]\n for pix, period in ldf.iterrows():\n left, right = xlims[level]\n if ix != len(ts.levels) - 1:\n time = np.mean(ts.text2age(period.Name))\n general = None\n _ix = ix\n while general is None:\n try:\n general = ts.named_age(time, level=ts.levels[::-1][_ix + 1])\n except:\n pass\n _ix += 1\n _l, _r = xlims[ts.levels[::-1][_ix]]\n if _r > left:\n left = _r\n\n rect = Rectangle(\n (left, period.End),\n right - left,\n period.Start - period.End,\n facecolor=period.Color,\n edgecolor=\"k\",\n )\n ax.add_artist(rect)\n\nax.set_xticks([np.mean(xlims[lvl]) for lvl in ts.levels])\nax.set_xticklabels(ts.levels, rotation=60)\nax.xaxis.set_ticks_position(\"top\")\nax.set_xlim(0, 7)\nax.set_ylabel(\"Age (Ma)\")\nax.set_ylim(500, 0)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/examples/util/timescale.py b/docs/source/examples/util/timescale.py deleted file mode 100644 index 5965c3d3..00000000 --- a/docs/source/examples/util/timescale.py +++ /dev/null @@ -1,122 +0,0 @@ -""" -Geological Timescale -====================== - -pyrolite includes a simple geological timescale, based on a recent verion -of the International Chronostratigraphic Chart [#ICS]_. The -:class:`~pyrolite.util.time.Timescale` class can be used to look up names for -specific geological ages, to look up times for known geological age names -and to access a reference table for all of these. - -.. [#ICS] Cohen, K.M., Finney, S.C., Gibbard, P.L., Fan, J.-X., 2013. - `The ICS International Chronostratigraphic Chart `__. - Episodes 36, 199–204. -""" -######################################################################################## -# First we'll create a timescale: -# -from pyrolite.util.time import Timescale -# sphinx_gallery_thumbnail_number = 2 -ts = Timescale() - -######################################################################################## -# From this we can look up the names of ages (in million years, or Ma): -# -ts.named_age(1212.1) -######################################################################################## -# As geological age names are hierarchical, the name you give an age depends on what -# level you're looking at. By default, the timescale will return the most specific -# non-null level. The levels accessible within the timescale are listed -# as an attribute: -# -ts.levels -######################################################################################## -# These can be used to refine the output names to your desired level of specificity -# (noting that for some ages, the levels which are accessible can differ; see the chart): -# -ts.named_age(1212.1, level="Epoch") -######################################################################################## -# The timescale can also do the inverse for you, and return the timing information for a -# given named age: -ts.text2age("Holocene") -######################################################################################### -# We can use this to create a simple template to visualise the geological timescale: -# -import pandas as pd -import matplotlib.pyplot as plt - -fig, ax = plt.subplots(1, figsize=(5, 10)) - -for ix, level in enumerate(ts.levels): - ldf = ts.data.loc[ts.data.Level == level, :] - for pix, period in ldf.iterrows(): - ax.bar( - ix, - period.Start - period.End, - facecolor=period.Color, - bottom=period.End, - width=1, - edgecolor="k", - ) - -ax.set_xticks(range(len(ts.levels))) -ax.set_xticklabels(ts.levels, rotation=60) -ax.xaxis.set_ticks_position("top") -ax.set_ylabel("Age (Ma)") -ax.invert_yaxis() - -######################################################################################### -# This doesn't quite look like the geological timescale you may be used to. We can improve -# on the output somewhat with a bit of customisation for the positioning. Notably, this is -# less readable, but produces something closer to what we're after. Some of this may soon -# be integrated as a :class:`~pyrolite.util.time.Timescale` method, if there's interest. -# -import numpy as np -from matplotlib.patches import Rectangle - -# first let's set up some x-limits for the different timescale levels -xlims = { - "Eon": (0, 1), - "Era": (1, 2), - "Period": (2, 3), - "Superepoch": (3, 4), - "Epoch": (3, 5), - "Age": (5, 7), -} - - -fig, ax = plt.subplots(1, figsize=(4, 10)) - -for ix, level in enumerate(ts.levels[::-1]): - ldf = ts.data.loc[ts.data.Level == level, :] - for pix, period in ldf.iterrows(): - left, right = xlims[level] - if ix != len(ts.levels) - 1: - time = np.mean(ts.text2age(period.Name)) - general = None - _ix = ix - while general is None: - try: - general = ts.named_age(time, level=ts.levels[::-1][_ix + 1]) - except: - pass - _ix += 1 - _l, _r = xlims[ts.levels[::-1][_ix]] - if _r > left: - left = _r - - rect = Rectangle( - (left, period.End), - right - left, - period.Start - period.End, - facecolor=period.Color, - edgecolor="k", - ) - ax.add_artist(rect) - -ax.set_xticks([np.mean(xlims[lvl]) for lvl in ts.levels]) -ax.set_xticklabels(ts.levels, rotation=60) -ax.xaxis.set_ticks_position("top") -ax.set_xlim(0, 7) -ax.set_ylabel("Age (Ma)") -ax.set_ylim(500, 0) diff --git a/docs/source/examples/util/timescale.py.md5 b/docs/source/examples/util/timescale.py.md5 deleted file mode 100644 index c40b3813..00000000 --- a/docs/source/examples/util/timescale.py.md5 +++ /dev/null @@ -1 +0,0 @@ -1da0cebf1eafee131e06b5a19e93fc23 \ No newline at end of file diff --git a/docs/source/examples/util/timescale.rst b/docs/source/examples/util/timescale.rst deleted file mode 100644 index 13c32340..00000000 --- a/docs/source/examples/util/timescale.rst +++ /dev/null @@ -1,279 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_examples_util_timescale.py: - - -Geological Timescale -====================== - -pyrolite includes a simple geological timescale, based on a recent verion -of the International Chronostratigraphic Chart [#ICS]_. The -:class:`~pyrolite.util.time.Timescale` class can be used to look up names for -specific geological ages, to look up times for known geological age names -and to access a reference table for all of these. - -.. [#ICS] Cohen, K.M., Finney, S.C., Gibbard, P.L., Fan, J.-X., 2013. - `The ICS International Chronostratigraphic Chart `__. - Episodes 36, 199–204. - -First we'll create a timescale: - - - -.. code-block:: default - - from pyrolite.util.time import Timescale - ts = Timescale() - - - - - - - - -From this we can look up the names of ages (in million years, or Ma): - - - -.. code-block:: default - - ts.named_age(1212.1) - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - 'Precambrian' - - - -As geological age names are hierarchical, the name you give an age depends on what -level you're looking at. By default, the timescale will return the most specific -non-null level. The levels accessible within the timescale are listed -as an attribute: - - - -.. code-block:: default - - ts.levels - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - ['Eon', 'Era', 'Period', 'Superepoch', 'Epoch', 'Age'] - - - -These can be used to refine the output names to your desired level of specificity -(noting that for some ages, the levels which are accessible can differ; see the chart): - - - -.. code-block:: default - - ts.named_age(1212.1, level="Epoch") - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - 'Ectasian' - - - -The timescale can also do the inverse for you, and return the timing information for a -given named age: - - -.. code-block:: default - - ts.text2age("Holocene") - - - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - (0.0117, 0.0) - - - -We can use this to create a simple template to visualise the geological timescale: - - - -.. code-block:: default - - import pandas as pd - import matplotlib.pyplot as plt - - fig, ax = plt.subplots(1, figsize=(5, 10)) - - for ix, level in enumerate(ts.levels): - ldf = ts.data.loc[ts.data.Level == level, :] - for pix, period in ldf.iterrows(): - ax.bar( - ix, - period.Start - period.End, - facecolor=period.Color, - bottom=period.End, - width=1, - edgecolor="k", - ) - - ax.set_xticks(range(len(ts.levels))) - ax.set_xticklabels(ts.levels, rotation=60) - ax.xaxis.set_ticks_position("top") - ax.set_ylabel("Age (Ma)") - ax.invert_yaxis() - - - - -.. image:: /examples/util/images/sphx_glr_timescale_001.png - :class: sphx-glr-single-img - - - - - -This doesn't quite look like the geological timescale you may be used to. We can improve -on the output somewhat with a bit of customisation for the positioning. Notably, this is -less readable, but produces something closer to what we're after. Some of this may soon -be integrated as a :class:`~pyrolite.util.time.Timescale` method, if there's interest. - - - -.. code-block:: default - - import numpy as np - from matplotlib.patches import Rectangle - - # first let's set up some x-limits for the different timescale levels - xlims = { - "Eon": (0, 1), - "Era": (1, 2), - "Period": (2, 3), - "Superepoch": (3, 4), - "Epoch": (3, 5), - "Age": (5, 7), - } - - - fig, ax = plt.subplots(1, figsize=(4, 10)) - - for ix, level in enumerate(ts.levels[::-1]): - ldf = ts.data.loc[ts.data.Level == level, :] - for pix, period in ldf.iterrows(): - left, right = xlims[level] - if ix != len(ts.levels) - 1: - time = np.mean(ts.text2age(period.Name)) - general = None - _ix = ix - while general is None: - try: - general = ts.named_age(time, level=ts.levels[::-1][_ix + 1]) - except: - pass - _ix += 1 - _l, _r = xlims[ts.levels[::-1][_ix]] - if _r > left: - left = _r - - rect = Rectangle( - (left, period.End), - right - left, - period.Start - period.End, - facecolor=period.Color, - edgecolor="k", - ) - ax.add_artist(rect) - - ax.set_xticks([np.mean(xlims[lvl]) for lvl in ts.levels]) - ax.set_xticklabels(ts.levels, rotation=60) - ax.xaxis.set_ticks_position("top") - ax.set_xlim(0, 7) - ax.set_ylabel("Age (Ma)") - ax.set_ylim(500, 0) - - - -.. image:: /examples/util/images/sphx_glr_timescale_002.png - :class: sphx-glr-single-img - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - - (500, 0) - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 2.824 seconds) - - -.. _sphx_glr_download_examples_util_timescale.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/examples/util/timescale.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: timescale.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: timescale.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/examples/util/timescale_codeobj.pickle b/docs/source/examples/util/timescale_codeobj.pickle deleted file mode 100644 index c1c4ed42..00000000 Binary files a/docs/source/examples/util/timescale_codeobj.pickle and /dev/null differ diff --git a/docs/source/gallery/examples/geochem/CIPW.py b/docs/source/gallery/examples/geochem/CIPW.py index 90831578..ae91d3fc 100644 --- a/docs/source/gallery/examples/geochem/CIPW.py +++ b/docs/source/gallery/examples/geochem/CIPW.py @@ -21,17 +21,12 @@ :mod:`pyrolite` (:func:`~pyrolite.mineral.normative.CIPW_norm`), and an overview of the implementation and the currently available options is given below. -.. warning:: The current implementation of CIPW in pyrolite produces results - which are inconsistent with SINCLAS/IgRoCS; we're working on addressing this. - There's a warning implemented in the function so that you should be notified - of this. - For the purposes of testing, pyrolite includes a file containing the outputs from Verma's SINCLAS/IgRoCS program. Here we can use this file to demonstrate the use of the CIPW Norm and verify that the results should generally be comparable between Verma's original implementation and the :mod:`pyrolite` implementation. -Here we import this file and do a little cleaning and registration of -geochemical components so we can work with it in the sections to follow: +We import this file and do a little cleaning and registration of geochemical +components so we can work with it in the sections to follow: """ import matplotlib.pyplot as plt import numpy as np diff --git a/docs/source/gallery/examples/geochem/scaling.py b/docs/source/gallery/examples/geochem/scaling.py index 5c7daffd..d8b5f11b 100644 --- a/docs/source/gallery/examples/geochem/scaling.py +++ b/docs/source/gallery/examples/geochem/scaling.py @@ -2,17 +2,97 @@ Unit Scaling ============= """ +import numpy as np import pandas as pd import pyrolite.geochem pd.set_option("display.precision", 3) # smaller outputs ######################################################################################## +# Here we create an example dataframe to work from, containing some synthetic data +# in the form of oxides and elements, each with different units (wt% and ppm, respectively). +# from pyrolite.util.synthetic import normal_frame df = normal_frame( - columns=["CaO", "MgO", "SiO2", "FeO", "Ni", "Ti", "La", "Lu", "Mg/Fe"] + columns=["CaO", "MgO", "SiO2", "FeO", "Ni", "Ti", "La", "Lu"], seed=22 ) +df.pyrochem.oxides *= 100 # oxides in wt% +df.pyrochem.elements *= 10000 # elements in ppm ######################################################################################## -cols = ["Ni", "NiO", "La", "La2O3"] -df.head(2).pyrochem.convert_chemistry(to=cols)[cols] # these are in ppm! +# In this case, we might want to transform the Ni and Ti into their standard oxide +# equivalents NiO and TiO2: +# +df.pyrochem.convert_chemistry(to=["NiO", "TiO2"]).head(2) +######################################################################################## +# But here because Ni and Ti have units of ppm, the results are a little non-sensical, +# especially when it's combined with the other oxides: +# +df.pyrochem.convert_chemistry(to=df.pyrochem.list_oxides + ["NiO", "TiO2"]).head(2) +######################################################################################## +# There are multiple ways we could convert the units, but here we're going to first +# convert the elemental ppm data to wt%, then perform our oxide-element conversion. +# To do this, we'll use the built-in function :func:`~pyrolite.util.units.scale`: +# +from pyrolite.util.units import scale + +df.pyrochem.elements *= scale("ppm", "wt%") +######################################################################################## +# We can see that this then gives us numbers which are a bit more sensible: +# +df.pyrochem.convert_chemistry(to=df.pyrochem.list_oxides + ["NiO", "TiO2"]).head(2) +######################################################################################## +# Dealing with Units in Column Names +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# Often our dataframes will start containing column names which pyrolite doesn't recognize +# natively by default (work in progress, this is an item on the roadmap). Here we can +# create an example of that, and go through some key steps for using this data in +# :mod:`pyrolite`: +# +df = normal_frame( + columns=["CaO", "MgO", "SiO2", "FeO", "Ni", "Ti", "La", "Lu"], seed=22 +) +df.pyrochem.oxides *= 100 # oxides in wt% +df.pyrochem.elements *= 10000 # elements in ppm +df = df.rename( + columns={ + **{c: c + "_wt%" for c in df.pyrochem.oxides}, + **{c: c + "_ppm" for c in df.pyrochem.elements}, + } +) +df.head(2) +######################################################################################## +# If you just wanted to rescale some columns, you can get away without renaming your +# columns, e.g. converting all of the ppm columns to wt%: +# +df.loc[:, [c for c in df.columns if "_ppm" in c]] *= scale("ppm", "wt%") +df.head(2) +######################################################################################## +# However, to access the full native capability of pyrolite, we'd need to rename +# these columns to use things like :func:`~pyrolite.geochem.pyrochem.convert_chemistry`: +# +units = { # keep a copy of the units, we can use these to map back later + c: c[c.find("_") + 1 :] if "_" in c else None for c in df.columns +} +df = df.rename( + columns={c: c.replace("_wt%", "").replace("_ppm", "") for c in df.columns} +) +df.head(2) +######################################################################################## +# We could then perform our chemistry conversion, rename our columns to include +# units, and optionally export to e.g. CSV: +# +converted_wt_pct = df.pyrochem.convert_chemistry( + to=df.pyrochem.list_oxides + ["NiO", "TiO2"] +) +converted_wt_pct.head(2) +######################################################################################## +# Here we rename the columns before we export them, just so we know explicitly +# what the units are: +converted_wt_pct = converted_wt_pct.rename( + columns={c: c + "_wt%" for c in converted_wt_pct.pyrochem.list_oxides} +) +converted_wt_pct.head(2) +######################################################################################## +converted_wt_pct.to_csv("converted_wt_pct.csv") diff --git a/docs/source/tutorials/images/sphx_glr_logo_001.png b/docs/source/tutorials/images/sphx_glr_logo_001.png deleted file mode 100644 index 37205f8e..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_logo_001.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_logo_002.png b/docs/source/tutorials/images/sphx_glr_logo_002.png deleted file mode 100644 index c76a322c..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_logo_002.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_logo_003.png b/docs/source/tutorials/images/sphx_glr_logo_003.png deleted file mode 100644 index ee0ec937..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_logo_003.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_logo_004.png b/docs/source/tutorials/images/sphx_glr_logo_004.png deleted file mode 100644 index a1fde6ae..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_logo_004.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_logo_005.png b/docs/source/tutorials/images/sphx_glr_logo_005.png deleted file mode 100644 index b3e03bb2..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_logo_005.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_logo_006.png b/docs/source/tutorials/images/sphx_glr_logo_006.png deleted file mode 100644 index b3e03bb2..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_logo_006.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_001.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_001.png deleted file mode 100644 index c3709d23..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_001.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_002.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_002.png deleted file mode 100644 index 16661699..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_002.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_003.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_003.png deleted file mode 100644 index 44839558..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_003.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_004.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_004.png deleted file mode 100644 index da150153..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_004.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_005.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_005.png deleted file mode 100644 index d5570f5e..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_005.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_006.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_006.png deleted file mode 100644 index 4260a693..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_006.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_007.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_007.png deleted file mode 100644 index a2b8914a..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_007.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_008.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_008.png deleted file mode 100644 index 0f4fe35a..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_008.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_009.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_009.png deleted file mode 100644 index 3717b36a..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_009.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_010.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_010.png deleted file mode 100644 index fdf953a2..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_010.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_plot_formatting_011.png b/docs/source/tutorials/images/sphx_glr_plot_formatting_011.png deleted file mode 100644 index 296a93a7..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_plot_formatting_011.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_ternary_density_001.png b/docs/source/tutorials/images/sphx_glr_ternary_density_001.png deleted file mode 100644 index b2b03ccc..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_ternary_density_001.png and /dev/null differ diff --git a/docs/source/tutorials/images/sphx_glr_ternary_density_002.png b/docs/source/tutorials/images/sphx_glr_ternary_density_002.png deleted file mode 100644 index 61995598..00000000 Binary files a/docs/source/tutorials/images/sphx_glr_ternary_density_002.png and /dev/null differ diff --git a/docs/source/tutorials/images/thumb/sphx_glr_logo_thumb.png b/docs/source/tutorials/images/thumb/sphx_glr_logo_thumb.png deleted file mode 100644 index e7c30132..00000000 Binary files a/docs/source/tutorials/images/thumb/sphx_glr_logo_thumb.png and /dev/null differ diff --git a/docs/source/tutorials/images/thumb/sphx_glr_plot_formatting_thumb.png b/docs/source/tutorials/images/thumb/sphx_glr_plot_formatting_thumb.png deleted file mode 100644 index 072b699c..00000000 Binary files a/docs/source/tutorials/images/thumb/sphx_glr_plot_formatting_thumb.png and /dev/null differ diff --git a/docs/source/tutorials/images/thumb/sphx_glr_ternary_density_thumb.png b/docs/source/tutorials/images/thumb/sphx_glr_ternary_density_thumb.png deleted file mode 100644 index b0c67e11..00000000 Binary files a/docs/source/tutorials/images/thumb/sphx_glr_ternary_density_thumb.png and /dev/null differ diff --git a/docs/source/tutorials/index.rst b/docs/source/tutorials/index.rst deleted file mode 100644 index 3262d8a0..00000000 --- a/docs/source/tutorials/index.rst +++ /dev/null @@ -1,87 +0,0 @@ -:orphan: - - - -.. _sphx_glr_tutorials: - -Tutorials -================ - -This page is home to longer examples which incorporate multiple components of -:mod:`pyrolite` or provide examples of how to integrate these into your own workflows. - -.. note:: This page is a work in progress. Feel free to request tutorials or examples - with a feature request. - - - -.. raw:: html - -
- -.. only:: html - - .. figure:: /tutorials/images/thumb/sphx_glr_plot_formatting_thumb.png - - :ref:`sphx_glr_tutorials_plot_formatting.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /tutorials/plot_formatting - -.. raw:: html - -
- -.. only:: html - - .. figure:: /tutorials/images/thumb/sphx_glr_logo_thumb.png - - :ref:`sphx_glr_tutorials_logo.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /tutorials/logo - -.. raw:: html - -
- -.. only:: html - - .. figure:: /tutorials/images/thumb/sphx_glr_ternary_density_thumb.png - - :ref:`sphx_glr_tutorials_ternary_density.py` - -.. raw:: html - -
- - -.. toctree:: - :hidden: - - /tutorials/ternary_density -.. raw:: html - -
- - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/tutorials/logo.ipynb b/docs/source/tutorials/logo.ipynb deleted file mode 100644 index ded6dd74..00000000 --- a/docs/source/tutorials/logo.ipynb +++ /dev/null @@ -1,184 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nMaking the Logo\n==================================\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Having some funky ellipses in a simplex inspired some interest when I put the logo\ntogether for pyrolite, so I put together a cleaned-up example of how you can create\nthese kinds of plots for your own data. These examples illustrate different methods to\nshow distribution of (homogeneous, or near so) compositional data for exploratory\nanalysis.\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.colors\nimport matplotlib.cm\nfrom pyrolite.comp.codata import *\nfrom pyrolite.util.skl.transform import ILRTransform, ALRTransform\nfrom pyrolite.util.synthetic import random_composition\n\nimport pyrolite.plot\nfrom pyrolite.util.plot.helpers import plot_pca_vectors, plot_stdev_ellipses\n\nnp.random.seed(82)\n\n# ignore sphinx_gallery warnings\nimport warnings\n\nwarnings.filterwarnings(\"ignore\", \"Matplotlib is currently using agg\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First we choose some colors, create some log-distributed synthetic data. Here I've\ngenerated a synthetic dataset with four samples having means equidistant from the\nlog-space centre and with varying covariance. This should illustrate the spatial\nwarping of the simplex nicely. Additionally, I chose a log-transform here to go\nfrom and to compositional space (:class:`~pyrolite.util.skl.ILRTransform`, which uses\nthe isometric log-ratio function :func:`~pyrolite.comp.codata.ilr`). Choosing\nanother transform will change the distortion observed in the simplex slightly.\nThis synthetic dataset is added into a :class:`~pandas.DataFrame` for convenient access\nto plotting functions via the pandas API defined in :class:`pyrolite.plot.pyroplot`.\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "t10b3 = [ # tableau 10 colorblind safe colors, a selection of 4\n (0, 107, 164),\n (171, 171, 171),\n (89, 89, 89),\n (95, 158, 209),\n]\nt10b3 = [(r / 255.0, g / 255.0, b / 255.0) for r, g, b in t10b3]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "d = 1.0 # distance from centre\nsig = 0.1 # scale for variance\n# means for logspace (D=2)\nmeans = np.array(np.meshgrid([-1, 1], [-1, 1])).T.reshape(-1, 2) * d\n# means = np.array([(-d, -d), (d, -d), (-d, d), (d, d)])\ncovs = ( # covariance for logspace (D=2)\n np.array(\n [\n [[1, 0], [0, 1]],\n [[0.5, 0.15], [0.15, 0.5]],\n [[1.5, -1], [-1, 1.5]],\n [[1.2, -0.6], [-0.6, 1.2]],\n ]\n )\n * sig\n)\n\nmeans = ILRTransform().inverse_transform(means) # compositional means (D=3)\nsize = 2000 # logo @ 10000\npts = [random_composition(mean=M, cov=C, size=size) for M, C in zip(means, covs)]\n\nT = ILRTransform()\nto_log = T.transform\nfrom_log = T.inverse_transform\n\ndf = pd.DataFrame(np.vstack(pts))\ndf.columns = [\"SiO2\", \"MgO\", \"FeO\"]\ndf[\"Sample\"] = np.repeat(np.arange(df.columns.size + 1), size).flatten()\nchem = [\"MgO\", \"SiO2\", \"FeO\"]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(\n 2, 2, figsize=(10, 10 * np.sqrt(3) / 2), subplot_kw=dict(projection=\"ternary\")\n)\nax = ax.flat\n_ = [[x.set_ticks([]) for x in [a.taxis, a.laxis, a.raxis]] for a in ax]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First, let's look at the synthetic data itself in the ternary space:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "kwargs = dict(marker=\"D\", alpha=0.2, s=3, no_ticks=True, axlabels=False)\nfor ix, sample in enumerate(df.Sample.unique()):\n comp = df.query(\"Sample == {}\".format(sample))\n comp.loc[:, chem].pyroplot.scatter(ax=ax[0], c=t10b3[ix], **kwargs)\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can take the mean and covariance in log-space to create covariance ellipses and\nvectors using principal component analysis:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "kwargs = dict(ax=ax[1], transform=from_log, nstds=3)\nax[1].set_title(\"Covariance Ellipses and PCA Vectors\")\nfor ix, sample in enumerate(df.Sample.unique()):\n comp = df.query(\"Sample == {}\".format(sample))\n tcomp = to_log(comp.loc[:, chem])\n plot_stdev_ellipses(tcomp.values, color=t10b3[ix], resolution=1000, **kwargs)\n plot_pca_vectors(tcomp.values, ls=\"-\", lw=0.5, color=\"k\", **kwargs)\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can also look at data density (here using kernel density estimation)\nin logratio-space:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "kwargs = dict(ax=ax[-2], bins=100, axlabels=False)\nax[-2].set_title(\"Individual Density, with Contours\")\n\nfor ix, sample in enumerate(df.Sample.unique()):\n comp = df.query(\"Sample == {}\".format(sample))\n comp.loc[:, chem].pyroplot.density(cmap=\"Blues\", vmin=0.05, **kwargs)\n comp.loc[:, chem].pyroplot.density(\n contours=[0.68, 0.95],\n cmap=\"Blues_r\",\n contour_labels={0.68: \"\u03c3\", 0.95: \"2\u03c3\"},\n **kwargs,\n )\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can also do this for individual samples, and estimate percentile contours:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "kwargs = dict(ax=ax[-1], axlabels=False)\nax[-1].set_title(\"Overall Density\")\ndf.loc[:, chem].pyroplot.density(bins=100, cmap=\"Greys\", **kwargs)\nplt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "for a in ax:\n a.set_aspect(\"equal\")\n a.patch.set_visible(False)\nplt.show()" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/tutorials/logo.py b/docs/source/tutorials/logo.py deleted file mode 100644 index f0b1b5a8..00000000 --- a/docs/source/tutorials/logo.py +++ /dev/null @@ -1,136 +0,0 @@ -""" -Making the Logo -================================== -""" -####################################################################################### -# Having some funky ellipses in a simplex inspired some interest when I put the logo -# together for pyrolite, so I put together a cleaned-up example of how you can create -# these kinds of plots for your own data. These examples illustrate different methods to -# show distribution of (homogeneous, or near so) compositional data for exploratory -# analysis. -# -import matplotlib -import matplotlib.cm -import matplotlib.colors -import matplotlib.pyplot as plt -import numpy as np -import pandas as pd - -import pyrolite.plot -from pyrolite.comp.codata import * -from pyrolite.util.plot.helpers import plot_pca_vectors, plot_stdev_ellipses -from pyrolite.util.skl.transform import ALRTransform, ILRTransform -from pyrolite.util.synthetic import random_composition - -# sphinx_gallery_thumbnail_number = 6 -np.random.seed(82) - -# ignore sphinx_gallery warnings -import warnings - -warnings.filterwarnings("ignore", "Matplotlib is currently using agg") -####################################################################################### -# First we choose some colors, create some log-distributed synthetic data. Here I've -# generated a synthetic dataset with four samples having means equidistant from the -# log-space centre and with varying covariance. This should illustrate the spatial -# warping of the simplex nicely. Additionally, I chose a log-transform here to go -# from and to compositional space (:class:`~pyrolite.util.skl.ILRTransform`, which uses -# the isometric log-ratio function :func:`~pyrolite.comp.codata.ilr`). Choosing -# another transform will change the distortion observed in the simplex slightly. -# This synthetic dataset is added into a :class:`~pandas.DataFrame` for convenient access -# to plotting functions via the pandas API defined in :class:`pyrolite.plot.pyroplot`. -# -t10b3 = [ # tableau 10 colorblind safe colors, a selection of 4 - (0, 107, 164), - (171, 171, 171), - (89, 89, 89), - (95, 158, 209), -] -t10b3 = [(r / 255.0, g / 255.0, b / 255.0) for r, g, b in t10b3] -####################################################################################### -# -d = 1.0 # distance from centre -sig = 0.1 # scale for variance -# means for logspace (D=2) -means = np.array(np.meshgrid([-1, 1], [-1, 1])).T.reshape(-1, 2) * d -# means = np.array([(-d, -d), (d, -d), (-d, d), (d, d)]) -covs = ( # covariance for logspace (D=2) - np.array( - [ - [[1, 0], [0, 1]], - [[0.5, 0.15], [0.15, 0.5]], - [[1.5, -1], [-1, 1.5]], - [[1.2, -0.6], [-0.6, 1.2]], - ] - ) - * sig -) - -means = ILRTransform().inverse_transform(means) # compositional means (D=3) -size = 2000 # logo @ 10000 -pts = [random_composition(mean=M, cov=C, size=size) for M, C in zip(means, covs)] - -T = ILRTransform() -to_log = T.transform -from_log = T.inverse_transform - -df = pd.DataFrame(np.vstack(pts)) -df.columns = ["SiO2", "MgO", "FeO"] -df["Sample"] = np.repeat(np.arange(df.columns.size + 1), size).flatten() -chem = ["MgO", "SiO2", "FeO"] -####################################################################################### -# -fig, ax = plt.subplots( - 2, 2, figsize=(10, 10 * np.sqrt(3) / 2), subplot_kw=dict(projection="ternary") -) -ax = ax.flat -_ = [[x.set_ticks([]) for x in [a.taxis, a.laxis, a.raxis]] for a in ax] -####################################################################################### -# First, let's look at the synthetic data itself in the ternary space: -# -kwargs = dict(marker="D", alpha=0.2, s=3, no_ticks=True, axlabels=False) -for ix, sample in enumerate(df.Sample.unique()): - comp = df.query("Sample == {}".format(sample)) - comp.loc[:, chem].pyroplot.scatter(ax=ax[0], c=t10b3[ix], **kwargs) -plt.show() -####################################################################################### -# We can take the mean and covariance in log-space to create covariance ellipses and -# vectors using principal component analysis: -# -kwargs = dict(ax=ax[1], transform=from_log, nstds=3) -ax[1].set_title("Covariance Ellipses and PCA Vectors") -for ix, sample in enumerate(df.Sample.unique()): - comp = df.query("Sample == {}".format(sample)) - tcomp = to_log(comp.loc[:, chem]) - plot_stdev_ellipses(tcomp.values, color=t10b3[ix], resolution=1000, **kwargs) - plot_pca_vectors(tcomp.values, ls="-", lw=0.5, color="k", **kwargs) -plt.show() -####################################################################################### -# We can also look at data density (here using kernel density estimation) -# in logratio-space: -# -kwargs = dict(ax=ax[-2], bins=100, axlabels=False) -ax[-2].set_title("Individual Density, with Contours") - -for ix, sample in enumerate(df.Sample.unique()): - comp = df.query("Sample == {}".format(sample)) - comp.loc[:, chem].pyroplot.density(cmap="Blues", vmin=0.05, **kwargs) - comp.loc[:, chem].pyroplot.density( - contours=[0.68, 0.95], - cmap="Blues_r", - contour_labels={0.68: "σ", 0.95: "2σ"}, - **kwargs, - ) -plt.show() -####################################################################################### -# We can also do this for individual samples, and estimate percentile contours: -# -kwargs = dict(ax=ax[-1], axlabels=False) -ax[-1].set_title("Overall Density") -df.loc[:, chem].pyroplot.density(bins=100, cmap="Greys", **kwargs) -plt.show() -####################################################################################### -for a in ax: - a.set_aspect("equal") - a.patch.set_visible(False) -plt.show() diff --git a/docs/source/tutorials/logo.py.md5 b/docs/source/tutorials/logo.py.md5 deleted file mode 100644 index 931cc07e..00000000 --- a/docs/source/tutorials/logo.py.md5 +++ /dev/null @@ -1 +0,0 @@ -c2baff56af83ffe5ace41b9199138317 \ No newline at end of file diff --git a/docs/source/tutorials/logo.rst b/docs/source/tutorials/logo.rst deleted file mode 100644 index 8959f2d7..00000000 --- a/docs/source/tutorials/logo.rst +++ /dev/null @@ -1,289 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_tutorials_logo.py: - - -Making the Logo -================================== - -Having some funky ellipses in a simplex inspired some interest when I put the logo -together for pyrolite, so I put together a cleaned-up example of how you can create -these kinds of plots for your own data. These examples illustrate different methods to -show distribution of (homogeneous, or near so) compositional data for exploratory -analysis. - - - -.. code-block:: default - - import matplotlib - import numpy as np - import pandas as pd - import matplotlib.pyplot as plt - import matplotlib.colors - import matplotlib.cm - from pyrolite.comp.codata import * - from pyrolite.util.skl.transform import ILRTransform, ALRTransform - from pyrolite.util.synthetic import random_composition - - import pyrolite.plot - from pyrolite.util.plot.helpers import plot_pca_vectors, plot_stdev_ellipses - - np.random.seed(82) - - # ignore sphinx_gallery warnings - import warnings - - warnings.filterwarnings("ignore", "Matplotlib is currently using agg") - - - - - - - -First we choose some colors, create some log-distributed synthetic data. Here I've -generated a synthetic dataset with four samples having means equidistant from the -log-space centre and with varying covariance. This should illustrate the spatial -warping of the simplex nicely. Additionally, I chose a log-transform here to go -from and to compositional space (:class:`~pyrolite.util.skl.ILRTransform`, which uses -the isometric log-ratio function :func:`~pyrolite.comp.codata.ilr`). Choosing -another transform will change the distortion observed in the simplex slightly. -This synthetic dataset is added into a :class:`~pandas.DataFrame` for convenient access -to plotting functions via the pandas API defined in :class:`pyrolite.plot.pyroplot`. - - - -.. code-block:: default - - t10b3 = [ # tableau 10 colorblind safe colors, a selection of 4 - (0, 107, 164), - (171, 171, 171), - (89, 89, 89), - (95, 158, 209), - ] - t10b3 = [(r / 255.0, g / 255.0, b / 255.0) for r, g, b in t10b3] - - - - - - - - -.. code-block:: default - - d = 1.0 # distance from centre - sig = 0.1 # scale for variance - # means for logspace (D=2) - means = np.array(np.meshgrid([-1, 1], [-1, 1])).T.reshape(-1, 2) * d - # means = np.array([(-d, -d), (d, -d), (-d, d), (d, d)]) - covs = ( # covariance for logspace (D=2) - np.array( - [ - [[1, 0], [0, 1]], - [[0.5, 0.15], [0.15, 0.5]], - [[1.5, -1], [-1, 1.5]], - [[1.2, -0.6], [-0.6, 1.2]], - ] - ) - * sig - ) - - means = ILRTransform().inverse_transform(means) # compositional means (D=3) - size = 2000 # logo @ 10000 - pts = [random_composition(mean=M, cov=C, size=size) for M, C in zip(means, covs)] - - T = ILRTransform() - to_log = T.transform - from_log = T.inverse_transform - - df = pd.DataFrame(np.vstack(pts)) - df.columns = ["SiO2", "MgO", "FeO"] - df["Sample"] = np.repeat(np.arange(df.columns.size + 1), size).flatten() - chem = ["MgO", "SiO2", "FeO"] - - - - - - - - -.. code-block:: default - - fig, ax = plt.subplots( - 2, 2, figsize=(10, 10 * np.sqrt(3) / 2), subplot_kw=dict(projection="ternary") - ) - ax = ax.flat - _ = [[x.set_ticks([]) for x in [a.taxis, a.laxis, a.raxis]] for a in ax] - - - -.. image:: /tutorials/images/sphx_glr_logo_001.png - :class: sphx-glr-single-img - - - - - -First, let's look at the synthetic data itself in the ternary space: - - - -.. code-block:: default - - kwargs = dict(marker="D", alpha=0.2, s=3, no_ticks=True, axlabels=False) - for ix, sample in enumerate(df.Sample.unique()): - comp = df.query("Sample == {}".format(sample)) - comp.loc[:, chem].pyroplot.scatter(ax=ax[0], c=t10b3[ix], **kwargs) - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_logo_002.png - :class: sphx-glr-single-img - - - - - -We can take the mean and covariance in log-space to create covariance ellipses and -vectors using principal component analysis: - - - -.. code-block:: default - - kwargs = dict(ax=ax[1], transform=from_log, nstds=3) - ax[1].set_title("Covariance Ellipses and PCA Vectors") - for ix, sample in enumerate(df.Sample.unique()): - comp = df.query("Sample == {}".format(sample)) - tcomp = to_log(comp.loc[:, chem]) - plot_stdev_ellipses(tcomp.values, color=t10b3[ix], resolution=1000, **kwargs) - plot_pca_vectors(tcomp.values, ls="-", lw=0.5, color="k", **kwargs) - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_logo_003.png - :class: sphx-glr-single-img - - - - - -We can also look at data density (here using kernel density estimation) -in logratio-space: - - - -.. code-block:: default - - kwargs = dict(ax=ax[-2], bins=100, axlabels=False) - ax[-2].set_title("Individual Density, with Contours") - - for ix, sample in enumerate(df.Sample.unique()): - comp = df.query("Sample == {}".format(sample)) - comp.loc[:, chem].pyroplot.density(cmap="Blues", vmin=0.05, **kwargs) - comp.loc[:, chem].pyroplot.density( - contours=[0.68, 0.95], - cmap="Blues_r", - contour_labels={0.68: "σ", 0.95: "2σ"}, - **kwargs, - ) - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_logo_004.png - :class: sphx-glr-single-img - - -.. rst-class:: sphx-glr-script-out - - Out: - - .. code-block:: none - - C:\GitHub\pyrolite\pyrolite\comp\codata.py:171: RuntimeWarning: invalid value encountered in log - Y = np.log(X) # Log operation - - - - -We can also do this for individual samples, and estimate percentile contours: - - - -.. code-block:: default - - kwargs = dict(ax=ax[-1], axlabels=False) - ax[-1].set_title("Overall Density") - df.loc[:, chem].pyroplot.density(bins=100, cmap="Greys", **kwargs) - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_logo_005.png - :class: sphx-glr-single-img - - - - - - -.. code-block:: default - - for a in ax: - a.set_aspect("equal") - a.patch.set_visible(False) - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_logo_006.png - :class: sphx-glr-single-img - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 8.428 seconds) - - -.. _sphx_glr_download_tutorials_logo.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/tutorials/logo.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: logo.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: logo.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/tutorials/logo_codeobj.pickle b/docs/source/tutorials/logo_codeobj.pickle deleted file mode 100644 index 1e8796a2..00000000 Binary files a/docs/source/tutorials/logo_codeobj.pickle and /dev/null differ diff --git a/docs/source/tutorials/plot_formatting.ipynb b/docs/source/tutorials/plot_formatting.ipynb deleted file mode 100644 index e638832e..00000000 --- a/docs/source/tutorials/plot_formatting.ipynb +++ /dev/null @@ -1,259 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nFormatting and Cleaning Up Plots\n==================================\n\n

Note

This tutorial is a work in progress and will be gradually updated.

\n\nIn this tutorial we will illustrate some straightfoward formatting for your plots which\nwill allow for greater customisation as needed. As :mod:`pyrolite` heavily uses\nand exposes the API of :mod:`matplotlib` for the visualisation components\n(and also :mod:`mpltern` for ternary diagrams), you should also check out their\ndocumentation pages for more in-depth guides, examples and API documentation.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First let's pull in a simple dataset to use throughout these examples:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.util.synthetic import test_df\n\ndf = test_df(cols=[\"SiO2\", \"CaO\", \"MgO\", \"Al2O3\", \"TiO2\", \"27Al\", \"d11B\"])" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Basic Figure and Axes Settings\n------------------------------\n\n:mod:`matplotlib` makes it relatively straightfoward to customise most settings for\nyour figures and axes. These settings can be defined at creation (e.g. in a call to\n:func:`~matplotlib.pyplot.subplots`), or they can be defined after you've created an\naxis (with the methods :code:`ax.set_()`). For example:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1)\n\nax.set_xlabel(\"My X Axis Label\")\nax.set_title(\"My Axis Title\", fontsize=12)\nax.set_yscale(\"log\")\nax.set_xlim((0.5, 10))\n\nfig.suptitle(\"My Figure Title\", fontsize=15)\n\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You can use a single method to set most of these things:\n:func:`~matplotlib.axes.Axes.set`. For example:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1)\nax.set(yscale=\"log\", xlim=(0, 1), ylabel=\"YAxis\", xlabel=\"XAxis\")\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Labels and Text\n----------------\n\n:mod:`matplotlib` enables you to use $\\TeX$ within all text elements, including\nlabels and annotations. This can be leveraged for more complex formatting,\nincorporating math and symbols into your plots. Check out the mod:`matplotlib`\n`tutorial `__, and\nfor more on working with text generally in :mod:`matplotlib`, check out the\n`relevant tutorials gallery `__.\n\nThe ability to use TeX syntax in :mod:`matplotlib` text objects can also be used\nfor typsetting, like for subscripts and superscripts. This is particularly relevant\nfor geochemical oxides labels (e.g. Al2O3, which would ideally be rendered as\n$Al_2O_3$) and isotopes (e.g. d11B, which should be $\\delta^{11}B$).\nAt the moment, pyrolite won't do this for you, so you may want to adjust the labelling\nafter you've made them. For example:\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.plot\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(2, 1)\ndf[[\"Al2O3\", \"TiO2\"]].pyroplot.scatter(ax=ax[0])\nax[0].set_xlabel(\"Al$_2$O$_3$\")\nax[0].set_ylabel(\"TiO$_2$\")\n\ndf[[\"27Al\", \"d11B\"]].pyroplot.scatter(ax=ax[1])\nax[1].set_xlabel(\"$^{27}$Al\")\nax[1].set_ylabel(\"$\\delta^{11}$B\")\n\nplt.tight_layout() # rearrange the plots to fit nicely together\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Sharing Axes\n------------\n\nIf you're building figures which have variables which are re-used, you'll typically\nwant to 'share' them between your axes. The :mod:`matplotlib.pyplot` API makes\nthis easy for when you want to share among *all* the axes as your create them:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(2, 2, sharex=True, sharey=True)\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "However, if you want to share axes in a way which is less standard, it can be\ndifficult to set up using this function. :mod:`pyrolite` has a utility function\nwhich can be used to share axes after they're created in slightly more arbitrary\nways. For example, imagine we wanted to share the first and third x-axes, and the\nfirst three y-axes, you could use:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\nfrom pyrolite.util.plot.axes import share_axes\n\nfig, ax = plt.subplots(2, 2)\nax = ax.flat # turn the (2,2) array of axes into one flat axes with shape (4,)\nshare_axes([ax[0], ax[2]], which=\"x\") # share x-axes for 0, 2\nshare_axes(ax[0:3], which=\"y\") # share y-axes for 0, 1, 2\n\nax[0].set_xlim((0, 10))\nax[1].set_ylim((-5, 5))\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Legends\n-------\n\nWhile it's simple to set up basic legends in :mod:`maplotlib` (see the docs for\n:func:`matplotlib.axes.Axes.legend`), often you'll want to customise\nyour legends to fit nicely within your figures. Here we'll create a few\nsynthetic datasets, add them to a figure and create the default legend:\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.plot\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1)\nfor i in range(3):\n sample_data = test_df(cols=[\"CaO\", \"MgO\", \"FeO\"]) # a new random sample\n sample_data[[\"CaO\", \"MgO\"]].pyroplot.scatter(ax=ax, label=\"Sample {:d}\".format(i))\nax.legend()\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "On many of the :mod:`pyrolite` examples, you'll find legends formatted along the\nlines of the following to clean them up a little:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "ax.legend(\n facecolor=None, # have a transparent legend background\n frameon=False, # remove the legend frame\n bbox_to_anchor=(1, 1), # anchor legend's corner to the axes' top-right\n loc='upper left' # use the upper left corner for the anchor\n)\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Check out the :mod:`matplotlib`\n`legend guide `__\nfor more.\n\nTernary Plots\n-------------\n\nThe ternary plots in :mod:`pyrolite` are generated using :mod:`mpltern`, and while\nthe syntax is very similar to the :mod:`matplotlib` API, as we have three axes\nto deal with sometimes things are little different. Here we demonstrate how to\ncomplete some common tasks, but you should check out the :mod:`mpltern` documentation\nif you want to dig deeper into customising your ternary diagrams (e.g. see the\n`example gallery `__),\nwhich these examples were developed from.\n\nOne of the key things to note in :mod:`mpltern` is that you have `top`, `left` and\n`right` axes.\n\nTernary Plot Axes Labels\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nLabelling ternary axes is done similarly to in :mod:`matplotlib`, but using the\naxes prefixes `t`, `l` and `r` for top, left and right axes, respectively:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.plot\nimport matplotlib.pyplot as plt\n\nax = df[[\"CaO\", \"MgO\", \"Al2O3\"]].pyroplot.scatter()\nax.set_tlabel(\"Top\")\nax.set_llabel(\"Left\")\nax.set_rlabel(\"Right\")\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Ternary Plot Grids\n~~~~~~~~~~~~~~~~~~\n\nTo add a simple grid to your ternary plot, you can use\n:func:`~mpltern.TernaryAxis.grid`:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.plot\nimport matplotlib.pyplot as plt\n\nax = df[[\"CaO\", \"MgO\", \"Al2O3\"]].pyroplot.scatter()\nax.grid()\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With this method, you can also specify an `axis`, `which` tickmarks you want to use\nfor the grid ('major', 'minor' or 'both') and a `linestyle`:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.plot\nimport matplotlib.pyplot as plt\n\nax = df[[\"CaO\", \"MgO\", \"Al2O3\"]].pyroplot.scatter()\nax.grid(axis=\"r\", which=\"both\", linestyle=\"--\")\nplt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Ternary Plot Limits\n~~~~~~~~~~~~~~~~~~~\n\nTo focus on a specific area, you can reset the limits of your ternary axes with\n:func:`~mpltern.TernaryAxis.set_ternary_lim`.\n\nAlso check out the :mod:`mpltern`\n`inset axes example `__\nif you're after ways to focus on specific regions.\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pyrolite.plot\nimport matplotlib.pyplot as plt\n\nax = df[[\"CaO\", \"MgO\", \"Al2O3\"]].pyroplot.scatter()\nax.set_ternary_lim(\n 0.1, # tmin\n 0.5, # tmax\n 0.2, # lmin\n 0.6, # lmax\n 0.3, # rmin\n 0.7 # rmax\n)\nplt.show()" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/tutorials/plot_formatting.py b/docs/source/tutorials/plot_formatting.py deleted file mode 100644 index 1d4d7a3b..00000000 --- a/docs/source/tutorials/plot_formatting.py +++ /dev/null @@ -1,218 +0,0 @@ -""" -Formatting and Cleaning Up Plots -================================== - -.. note:: This tutorial is a work in progress and will be gradually updated. - -In this tutorial we will illustrate some straightfoward formatting for your plots which -will allow for greater customisation as needed. As :mod:`pyrolite` heavily uses -and exposes the API of :mod:`matplotlib` for the visualisation components -(and also :mod:`mpltern` for ternary diagrams), you should also check out their -documentation pages for more in-depth guides, examples and API documentation. -""" -####################################################################################### -# First let's pull in a simple dataset to use throughout these examples: -# -from pyrolite.util.synthetic import test_df -# sphinx_gallery_thumbnail_number = 7 - -df = test_df(cols=["SiO2", "CaO", "MgO", "Al2O3", "TiO2", "27Al", "d11B"]) -####################################################################################### -# Basic Figure and Axes Settings -# ------------------------------ -# -# :mod:`matplotlib` makes it relatively straightfoward to customise most settings for -# your figures and axes. These settings can be defined at creation (e.g. in a call to -# :func:`~matplotlib.pyplot.subplots`), or they can be defined after you've created an -# axis (with the methods :code:`ax.set_()`). For example: -# -import matplotlib.pyplot as plt - -fig, ax = plt.subplots(1) - -ax.set_xlabel("My X Axis Label") -ax.set_title("My Axis Title", fontsize=12) -ax.set_yscale("log") -ax.set_xlim((0.5, 10)) - -fig.suptitle("My Figure Title", fontsize=15) - -plt.show() -####################################################################################### -# You can use a single method to set most of these things: -# :func:`~matplotlib.axes.Axes.set`. For example: -# -import matplotlib.pyplot as plt - -fig, ax = plt.subplots(1) -ax.set(yscale="log", xlim=(0, 1), ylabel="YAxis", xlabel="XAxis") -plt.show() -####################################################################################### -# Labels and Text -# ---------------- -# -# :mod:`matplotlib` enables you to use :math:`\TeX` within all text elements, including -# labels and annotations. This can be leveraged for more complex formatting, -# incorporating math and symbols into your plots. Check out the mod:`matplotlib` -# `tutorial `__, and -# for more on working with text generally in :mod:`matplotlib`, check out the -# `relevant tutorials gallery `__. -# -# The ability to use TeX syntax in :mod:`matplotlib` text objects can also be used -# for typsetting, like for subscripts and superscripts. This is particularly relevant -# for geochemical oxides labels (e.g. Al2O3, which would ideally be rendered as -# :math:`Al_2O_3`) and isotopes (e.g. d11B, which should be :math:`\delta^{11}B`). -# At the moment, pyrolite won't do this for you, so you may want to adjust the labelling -# after you've made them. For example: -import pyrolite.plot -import matplotlib.pyplot as plt - -fig, ax = plt.subplots(2, 1) -df[["Al2O3", "TiO2"]].pyroplot.scatter(ax=ax[0]) -ax[0].set_xlabel("Al$_2$O$_3$") -ax[0].set_ylabel("TiO$_2$") - -df[["27Al", "d11B"]].pyroplot.scatter(ax=ax[1]) -ax[1].set_xlabel("$^{27}$Al") -ax[1].set_ylabel("$\delta^{11}$B") - -plt.tight_layout() # rearrange the plots to fit nicely together -plt.show() -####################################################################################### -# Sharing Axes -# ------------ -# -# If you're building figures which have variables which are re-used, you'll typically -# want to 'share' them between your axes. The :mod:`matplotlib.pyplot` API makes -# this easy for when you want to share among *all* the axes as your create them: -# -import matplotlib.pyplot as plt - -fig, ax = plt.subplots(2, 2, sharex=True, sharey=True) -plt.show() -####################################################################################### -# However, if you want to share axes in a way which is less standard, it can be -# difficult to set up using this function. :mod:`pyrolite` has a utility function -# which can be used to share axes after they're created in slightly more arbitrary -# ways. For example, imagine we wanted to share the first and third x-axes, and the -# first three y-axes, you could use: -# -import matplotlib.pyplot as plt -from pyrolite.util.plot.axes import share_axes - -fig, ax = plt.subplots(2, 2) -ax = ax.flat # turn the (2,2) array of axes into one flat axes with shape (4,) -share_axes([ax[0], ax[2]], which="x") # share x-axes for 0, 2 -share_axes(ax[0:3], which="y") # share y-axes for 0, 1, 2 - -ax[0].set_xlim((0, 10)) -ax[1].set_ylim((-5, 5)) -plt.show() -####################################################################################### -# Legends -# ------- -# -# While it's simple to set up basic legends in :mod:`maplotlib` (see the docs for -# :func:`matplotlib.axes.Axes.legend`), often you'll want to customise -# your legends to fit nicely within your figures. Here we'll create a few -# synthetic datasets, add them to a figure and create the default legend: -import pyrolite.plot -import matplotlib.pyplot as plt - -fig, ax = plt.subplots(1) -for i in range(3): - sample_data = test_df(cols=["CaO", "MgO", "FeO"]) # a new random sample - sample_data[["CaO", "MgO"]].pyroplot.scatter(ax=ax, label="Sample {:d}".format(i)) -ax.legend() -plt.show() -####################################################################################### -# On many of the :mod:`pyrolite` examples, you'll find legends formatted along the -# lines of the following to clean them up a little: -# -ax.legend( - facecolor=None, # have a transparent legend background - frameon=False, # remove the legend frame - bbox_to_anchor=(1, 1), # anchor legend's corner to the axes' top-right - loc='upper left' # use the upper left corner for the anchor -) -plt.show() -####################################################################################### -# Check out the :mod:`matplotlib` -# `legend guide `__ -# for more. -# -# Ternary Plots -# ------------- -# -# The ternary plots in :mod:`pyrolite` are generated using :mod:`mpltern`, and while -# the syntax is very similar to the :mod:`matplotlib` API, as we have three axes -# to deal with sometimes things are little different. Here we demonstrate how to -# complete some common tasks, but you should check out the :mod:`mpltern` documentation -# if you want to dig deeper into customising your ternary diagrams (e.g. see the -# `example gallery `__), -# which these examples were developed from. -# -# One of the key things to note in :mod:`mpltern` is that you have `top`, `left` and -# `right` axes. -# -# Ternary Plot Axes Labels -# ~~~~~~~~~~~~~~~~~~~~~~~~ -# -# Labelling ternary axes is done similarly to in :mod:`matplotlib`, but using the -# axes prefixes `t`, `l` and `r` for top, left and right axes, respectively: -# -import pyrolite.plot -import matplotlib.pyplot as plt - -ax = df[["CaO", "MgO", "Al2O3"]].pyroplot.scatter() -ax.set_tlabel("Top") -ax.set_llabel("Left") -ax.set_rlabel("Right") -plt.show() -######################################################################################## -# Ternary Plot Grids -# ~~~~~~~~~~~~~~~~~~ -# -# To add a simple grid to your ternary plot, you can use -# :func:`~mpltern.TernaryAxis.grid`: -# -import pyrolite.plot -import matplotlib.pyplot as plt - -ax = df[["CaO", "MgO", "Al2O3"]].pyroplot.scatter() -ax.grid() -plt.show() -######################################################################################## -# With this method, you can also specify an `axis`, `which` tickmarks you want to use -# for the grid ('major', 'minor' or 'both') and a `linestyle`: -# -import pyrolite.plot -import matplotlib.pyplot as plt - -ax = df[["CaO", "MgO", "Al2O3"]].pyroplot.scatter() -ax.grid(axis="r", which="both", linestyle="--") -plt.show() -######################################################################################## -# Ternary Plot Limits -# ~~~~~~~~~~~~~~~~~~~ -# -# To focus on a specific area, you can reset the limits of your ternary axes with -# :func:`~mpltern.TernaryAxis.set_ternary_lim`. -# -# Also check out the :mod:`mpltern` -# `inset axes example `__ -# if you're after ways to focus on specific regions. -# -import pyrolite.plot -import matplotlib.pyplot as plt - -ax = df[["CaO", "MgO", "Al2O3"]].pyroplot.scatter() -ax.set_ternary_lim( - 0.1, # tmin - 0.5, # tmax - 0.2, # lmin - 0.6, # lmax - 0.3, # rmin - 0.7 # rmax -) -plt.show() diff --git a/docs/source/tutorials/plot_formatting.py.md5 b/docs/source/tutorials/plot_formatting.py.md5 deleted file mode 100644 index e4b31ecd..00000000 --- a/docs/source/tutorials/plot_formatting.py.md5 +++ /dev/null @@ -1 +0,0 @@ -1d68e1d176501172babd90a19ad50af7 \ No newline at end of file diff --git a/docs/source/tutorials/plot_formatting.rst b/docs/source/tutorials/plot_formatting.rst deleted file mode 100644 index 5e04313a..00000000 --- a/docs/source/tutorials/plot_formatting.rst +++ /dev/null @@ -1,412 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_tutorials_plot_formatting.py: - - -Formatting and Cleaning Up Plots -================================== - -.. note:: This tutorial is a work in progress and will be gradually updated. - -In this tutorial we will illustrate some straightfoward formatting for your plots which -will allow for greater customisation as needed. As :mod:`pyrolite` heavily uses -and exposes the API of :mod:`matplotlib` for the visualisation components -(and also :mod:`mpltern` for ternary diagrams), you should also check out their -documentation pages for more in-depth guides, examples and API documentation. - -First let's pull in a simple dataset to use throughout these examples: - - - -.. code-block:: default - - from pyrolite.util.synthetic import test_df - - df = test_df(cols=["SiO2", "CaO", "MgO", "Al2O3", "TiO2", "27Al", "d11B"]) - - - - - - - -Basic Figure and Axes Settings ------------------------------- - -:mod:`matplotlib` makes it relatively straightfoward to customise most settings for -your figures and axes. These settings can be defined at creation (e.g. in a call to -:func:`~matplotlib.pyplot.subplots`), or they can be defined after you've created an -axis (with the methods :code:`ax.set_()`). For example: - - - -.. code-block:: default - - import matplotlib.pyplot as plt - - fig, ax = plt.subplots(1) - - ax.set_xlabel("My X Axis Label") - ax.set_title("My Axis Title", fontsize=12) - ax.set_yscale("log") - ax.set_xlim((0.5, 10)) - - fig.suptitle("My Figure Title", fontsize=15) - - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_001.png - :class: sphx-glr-single-img - - - - - -You can use a single method to set most of these things: -:func:`~matplotlib.axes.Axes.set`. For example: - - - -.. code-block:: default - - import matplotlib.pyplot as plt - - fig, ax = plt.subplots(1) - ax.set(yscale="log", xlim=(0, 1), ylabel="YAxis", xlabel="XAxis") - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_002.png - :class: sphx-glr-single-img - - - - - -Labels and Text ----------------- - -:mod:`matplotlib` enables you to use :math:`\TeX` within all text elements, including -labels and annotations. This can be leveraged for more complex formatting, -incorporating math and symbols into your plots. Check out the mod:`matplotlib` -`tutorial `__, and -for more on working with text generally in :mod:`matplotlib`, check out the -`relevant tutorials gallery `__. - -The ability to use TeX syntax in :mod:`matplotlib` text objects can also be used -for typsetting, like for subscripts and superscripts. This is particularly relevant -for geochemical oxides labels (e.g. Al2O3, which would ideally be rendered as -:math:`Al_2O_3`) and isotopes (e.g. d11B, which should be :math:`\delta^{11}B`). -At the moment, pyrolite won't do this for you, so you may want to adjust the labelling -after you've made them. For example: - - -.. code-block:: default - - import pyrolite.plot - import matplotlib.pyplot as plt - - fig, ax = plt.subplots(2, 1) - df[["Al2O3", "TiO2"]].pyroplot.scatter(ax=ax[0]) - ax[0].set_xlabel("Al$_2$O$_3$") - ax[0].set_ylabel("TiO$_2$") - - df[["27Al", "d11B"]].pyroplot.scatter(ax=ax[1]) - ax[1].set_xlabel("$^{27}$Al") - ax[1].set_ylabel("$\delta^{11}$B") - - plt.tight_layout() # rearrange the plots to fit nicely together - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_003.png - :class: sphx-glr-single-img - - - - - -Sharing Axes ------------- - -If you're building figures which have variables which are re-used, you'll typically -want to 'share' them between your axes. The :mod:`matplotlib.pyplot` API makes -this easy for when you want to share among *all* the axes as your create them: - - - -.. code-block:: default - - import matplotlib.pyplot as plt - - fig, ax = plt.subplots(2, 2, sharex=True, sharey=True) - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_004.png - :class: sphx-glr-single-img - - - - - -However, if you want to share axes in a way which is less standard, it can be -difficult to set up using this function. :mod:`pyrolite` has a utility function -which can be used to share axes after they're created in slightly more arbitrary -ways. For example, imagine we wanted to share the first and third x-axes, and the -first three y-axes, you could use: - - - -.. code-block:: default - - import matplotlib.pyplot as plt - from pyrolite.util.plot.axes import share_axes - - fig, ax = plt.subplots(2, 2) - ax = ax.flat # turn the (2,2) array of axes into one flat axes with shape (4,) - share_axes([ax[0], ax[2]], which="x") # share x-axes for 0, 2 - share_axes(ax[0:3], which="y") # share y-axes for 0, 1, 2 - - ax[0].set_xlim((0, 10)) - ax[1].set_ylim((-5, 5)) - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_005.png - :class: sphx-glr-single-img - - - - - -Legends -------- - -While it's simple to set up basic legends in :mod:`maplotlib` (see the docs for -:func:`matplotlib.axes.Axes.legend`), often you'll want to customise -your legends to fit nicely within your figures. Here we'll create a few -synthetic datasets, add them to a figure and create the default legend: - - -.. code-block:: default - - import pyrolite.plot - import matplotlib.pyplot as plt - - fig, ax = plt.subplots(1) - for i in range(3): - sample_data = test_df(cols=["CaO", "MgO", "FeO"]) # a new random sample - sample_data[["CaO", "MgO"]].pyroplot.scatter(ax=ax, label="Sample {:d}".format(i)) - ax.legend() - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_006.png - :class: sphx-glr-single-img - - - - - -On many of the :mod:`pyrolite` examples, you'll find legends formatted along the -lines of the following to clean them up a little: - - - -.. code-block:: default - - ax.legend( - facecolor=None, # have a transparent legend background - frameon=False, # remove the legend frame - bbox_to_anchor=(1, 1), # anchor legend's corner to the axes' top-right - loc='upper left' # use the upper left corner for the anchor - ) - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_007.png - :class: sphx-glr-single-img - - - - - -Check out the :mod:`matplotlib` -`legend guide `__ -for more. - -Ternary Plots -------------- - -The ternary plots in :mod:`pyrolite` are generated using :mod:`mpltern`, and while -the syntax is very similar to the :mod:`matplotlib` API, as we have three axes -to deal with sometimes things are little different. Here we demonstrate how to -complete some common tasks, but you should check out the :mod:`mpltern` documentation -if you want to dig deeper into customising your ternary diagrams (e.g. see the -`example gallery `__), -which these examples were developed from. - -One of the key things to note in :mod:`mpltern` is that you have `top`, `left` and -`right` axes. - -Ternary Plot Axes Labels -~~~~~~~~~~~~~~~~~~~~~~~~ - -Labelling ternary axes is done similarly to in :mod:`matplotlib`, but using the -axes prefixes `t`, `l` and `r` for top, left and right axes, respectively: - - - -.. code-block:: default - - import pyrolite.plot - import matplotlib.pyplot as plt - - ax = df[["CaO", "MgO", "Al2O3"]].pyroplot.scatter() - ax.set_tlabel("Top") - ax.set_llabel("Left") - ax.set_rlabel("Right") - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_008.png - :class: sphx-glr-single-img - - - - - -Ternary Plot Grids -~~~~~~~~~~~~~~~~~~ - -To add a simple grid to your ternary plot, you can use -:func:`~mpltern.TernaryAxis.grid`: - - - -.. code-block:: default - - import pyrolite.plot - import matplotlib.pyplot as plt - - ax = df[["CaO", "MgO", "Al2O3"]].pyroplot.scatter() - ax.grid() - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_009.png - :class: sphx-glr-single-img - - - - - -With this method, you can also specify an `axis`, `which` tickmarks you want to use -for the grid ('major', 'minor' or 'both') and a `linestyle`: - - - -.. code-block:: default - - import pyrolite.plot - import matplotlib.pyplot as plt - - ax = df[["CaO", "MgO", "Al2O3"]].pyroplot.scatter() - ax.grid(axis="r", which="both", linestyle="--") - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_010.png - :class: sphx-glr-single-img - - - - - -Ternary Plot Limits -~~~~~~~~~~~~~~~~~~~ - -To focus on a specific area, you can reset the limits of your ternary axes with -:func:`~mpltern.TernaryAxis.set_ternary_lim`. - -Also check out the :mod:`mpltern` -`inset axes example `__ -if you're after ways to focus on specific regions. - - - -.. code-block:: default - - import pyrolite.plot - import matplotlib.pyplot as plt - - ax = df[["CaO", "MgO", "Al2O3"]].pyroplot.scatter() - ax.set_ternary_lim( - 0.1, # tmin - 0.5, # tmax - 0.2, # lmin - 0.6, # lmax - 0.3, # rmin - 0.7 # rmax - ) - plt.show() - - - -.. image:: /tutorials/images/sphx_glr_plot_formatting_011.png - :class: sphx-glr-single-img - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 4.250 seconds) - - -.. _sphx_glr_download_tutorials_plot_formatting.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/tutorials/plot_formatting.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: plot_formatting.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: plot_formatting.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/tutorials/plot_formatting_codeobj.pickle b/docs/source/tutorials/plot_formatting_codeobj.pickle deleted file mode 100644 index 724114ad..00000000 Binary files a/docs/source/tutorials/plot_formatting_codeobj.pickle and /dev/null differ diff --git a/docs/source/tutorials/searchindex.bak b/docs/source/tutorials/searchindex.bak deleted file mode 100644 index 309ca9a8..00000000 --- a/docs/source/tutorials/searchindex.bak +++ /dev/null @@ -1,3 +0,0 @@ -'C:\\GitHub\\pyrolite\\docs\\build\\html\\index.html', (0, 11243) -'C:\\GitHub\\pyrolite\\docs\\build\\html\\_static\\documentation_options.js', (11264, 327) -'C:\\GitHub\\pyrolite\\docs\\build\\html\\searchindex.js', (11776, 81186) diff --git a/docs/source/tutorials/searchindex.dat b/docs/source/tutorials/searchindex.dat deleted file mode 100644 index 55c78862..00000000 Binary files a/docs/source/tutorials/searchindex.dat and /dev/null differ diff --git a/docs/source/tutorials/searchindex.dir b/docs/source/tutorials/searchindex.dir deleted file mode 100644 index 309ca9a8..00000000 --- a/docs/source/tutorials/searchindex.dir +++ /dev/null @@ -1,3 +0,0 @@ -'C:\\GitHub\\pyrolite\\docs\\build\\html\\index.html', (0, 11243) -'C:\\GitHub\\pyrolite\\docs\\build\\html\\_static\\documentation_options.js', (11264, 327) -'C:\\GitHub\\pyrolite\\docs\\build\\html\\searchindex.js', (11776, 81186) diff --git a/docs/source/tutorials/sg_execution_times.rst b/docs/source/tutorials/sg_execution_times.rst deleted file mode 100644 index 3fb6a441..00000000 --- a/docs/source/tutorials/sg_execution_times.rst +++ /dev/null @@ -1,16 +0,0 @@ - -:orphan: - -.. _sphx_glr_tutorials_sg_execution_times: - -Computation times -================= -**00:08.428** total execution time for **tutorials** files: - -+-----------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_tutorials_logo.py` (``logo.py``) | 00:08.428 | 0.0 MB | -+-----------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_tutorials_plot_formatting.py` (``plot_formatting.py``) | 00:00.000 | 0.0 MB | -+-----------------------------------------------------------------------+-----------+--------+ -| :ref:`sphx_glr_tutorials_ternary_density.py` (``ternary_density.py``) | 00:00.000 | 0.0 MB | -+-----------------------------------------------------------------------+-----------+--------+ diff --git a/docs/source/tutorials/ternary_density.ipynb b/docs/source/tutorials/ternary_density.ipynb deleted file mode 100644 index 6da9d7b4..00000000 --- a/docs/source/tutorials/ternary_density.ipynb +++ /dev/null @@ -1,137 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\nOne Way to Do Ternary Heatmaps\n==================================\n\nThere are multiple ways you can acheive ternary heatmaps, but those based on\nthe cartesian axes (e.g. a regularly spaced rectangular grid, or even a regularly\nspaced triangular grid) can result in difficulties and data misrepresentation.\n\nHere we illustrate how the ternary heatmaps for pyrolite are constructed using an\nirregualr triangulated grid and log transforms, and how this avoids some of the\npotential issues of the methods mentioned above.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let's first get some data to deal with. :mod:`mpltern` has a conventient dataset\nwhich we can use here:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\nimport pandas as pd\nfrom mpltern.ternary.datasets import get_scatter_points\n\nnp.random.seed(43)\ndf = pd.DataFrame(np.array([*get_scatter_points(n=80)]).T, columns=[\"A\", \"B\", \"C\"])\ndf = df.loc[(df > 0.1).all(axis=1), :]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "From this dataset we'll generate a\n:func:`~pyrolite.plot.density.ternary.ternary_heatmap`, which is the basis\nfor ternary density diagrams via :func:`~pyrolite.plot.pyrochem.density`:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from pyrolite.comp.codata import ilr, inverse_ilr\nfrom pyrolite.plot.density.ternary import ternary_heatmap\n\ncoords, H, data = ternary_heatmap(\n df.values,\n bins=10,\n mode=\"density\",\n remove_background=True,\n transform=ilr,\n inverse_transform=inverse_ilr,\n grid_border_frac=0.2,\n)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This function returns more than just the coordinates and histogram/density estimate,\nwhich will come in handy for exploring how it came together. The data variable here\nis a dictonary with contains the grids and coordiantes used to construct the\nhistogram/density diagram. We can use these to show how the ternary log-grid is\nconstructed, and then transformed back to ternary space before being triangulated\nand interpoalted for the ternary heatmap:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\nimport pyrolite.plot\nfrom pyrolite.util.math import flattengrid\nfrom pyrolite.util.plot.axes import axes_to_ternary, share_axes\n\nfig, ax = plt.subplots(3, 2, figsize=(6, 9))\nax = ax.flat\n\nshare_axes([ax[1], ax[2], ax[3]])\nax = axes_to_ternary([ax[0], ax[4], ax[5]])\n\nax[0].set_title(\"data\", y=1.2)\ndf.pyroplot.scatter(ax=ax[0], c=\"k\", alpha=0.1)\nax[0].scatter(*data[\"tern_bound_points\"].T, c=\"k\")\n\nax[1].set_title(\"transformed data\", y=1.2)\nax[1].scatter(*data[\"tfm_tern_bound_points\"].T, c=\"k\")\nax[1].scatter(*data[\"grid_transform\"](df.values).T, c=\"k\", alpha=0.1)\n\nax[2].set_title(\"log grid\", y=1.2)\nax[2].scatter(*flattengrid(data[\"tfm_centres\"]).T, c=\"k\", marker=\".\", s=5)\nax[2].scatter(*flattengrid(data[\"tfm_edges\"]).T, c=\"k\", marker=\".\", s=2)\nax[2].scatter(*data[\"tfm_tern_bound_points\"].T, c=\"k\")\n\nax[3].set_title(\"log-grid heatmap\", y=1.2)\nax[3].pcolormesh(*data[\"tfm_edges\"], H)\nax[3].scatter(*data[\"grid_transform\"](df.values).T, c=\"white\", alpha=0.8, s=1)\n\nax[4].set_title(\"ternary log-grid\", y=1.2)\nax[4].scatter(*data[\"tern_centres\"].T, c=\"k\", marker=\".\", s=5)\nax[4].scatter(*data[\"tern_edges\"].T, c=\"k\", marker=\".\", s=2)\nax[4].scatter(*data[\"tern_bound_points\"].T, c=\"k\")\n\nax[5].set_title(\"ternary heatmap\", y=1.2)\nax[5].tripcolor(*coords.T, H.flatten())\nax[5].scatter(*data[\"tern_bound_points\"].T, c=\"k\")\n\n\nplt.tight_layout()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "plt.close(\"all\") # let's save some memory.." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can see how this works almost exactly the same for the histograms:\n\n\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "coords, H, data = ternary_heatmap(\n df.values,\n bins=10,\n mode=\"histogram\",\n remove_background=True,\n transform=ilr,\n inverse_transform=inverse_ilr,\n grid_border_frac=0.2,\n)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig, ax = plt.subplots(3, 2, figsize=(6, 9))\nax = ax.flat\n\nshare_axes([ax[1], ax[2], ax[3]])\nax = axes_to_ternary([ax[0], ax[4], ax[5]])\n\nax[0].set_title(\"data\", y=1.2)\ndf.pyroplot.scatter(ax=ax[0], c=\"k\", alpha=0.1)\nax[0].scatter(*data[\"tern_bound_points\"].T, c=\"k\")\n\nax[1].set_title(\"transformed data\", y=1.2)\nax[1].scatter(*data[\"tfm_tern_bound_points\"].T, c=\"k\")\nax[1].scatter(*data[\"grid_transform\"](df.values).T, c=\"k\", alpha=0.1)\n\nax[2].set_title(\"log grid\", y=1.2)\nax[2].scatter(*flattengrid(data[\"tfm_centres\"]).T, c=\"k\", marker=\".\", s=5)\nax[2].scatter(*flattengrid(data[\"tfm_edges\"]).T, c=\"k\", marker=\".\", s=2)\nax[2].scatter(*data[\"tfm_tern_bound_points\"].T, c=\"k\")\n\nax[3].set_title(\"log-grid heatmap\", y=1.2)\nax[3].pcolormesh(*data[\"tfm_centres\"], H)\nax[3].scatter(*data[\"grid_transform\"](df.values).T, c=\"white\", alpha=0.8, s=1)\n\nax[4].set_title(\"ternary log-grid\", y=1.2)\nax[4].scatter(*data[\"tern_centres\"].T, c=\"k\", marker=\".\", s=5)\nax[4].scatter(*data[\"tern_edges\"].T, c=\"k\", marker=\".\", s=2)\nax[4].scatter(*data[\"tern_bound_points\"].T, c=\"k\")\n\nax[5].set_title(\"ternary heatmap\", y=1.2)\nax[5].tripcolor(*coords.T, H.flatten())\nax[5].scatter(*data[\"tern_bound_points\"].T, c=\"k\")\n\nplt.tight_layout()" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "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.7.4" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file diff --git a/docs/source/tutorials/ternary_density.py b/docs/source/tutorials/ternary_density.py deleted file mode 100644 index a04d2432..00000000 --- a/docs/source/tutorials/ternary_density.py +++ /dev/null @@ -1,136 +0,0 @@ -""" -One Way to Do Ternary Heatmaps -================================== - -There are multiple ways you can acheive ternary heatmaps, but those based on -the cartesian axes (e.g. a regularly spaced rectangular grid, or even a regularly -spaced triangular grid) can result in difficulties and data misrepresentation. - -Here we illustrate how the ternary heatmaps for pyrolite are constructed using an -irregualr triangulated grid and log transforms, and how this avoids some of the -potential issues of the methods mentioned above. -""" -####################################################################################### -# Let's first get some data to deal with. :mod:`mpltern` has a conventient dataset -# which we can use here: -# -import numpy as np -import pandas as pd -from mpltern.ternary.datasets import get_scatter_points - -np.random.seed(43) -df = pd.DataFrame(np.array([*get_scatter_points(n=80)]).T, columns=["A", "B", "C"]) -df = df.loc[(df > 0.1).all(axis=1), :] -####################################################################################### -# From this dataset we'll generate a -# :func:`~pyrolite.plot.density.ternary.ternary_heatmap`, which is the basis -# for ternary density diagrams via :func:`~pyrolite.plot.pyrochem.density`: -# -from pyrolite.comp.codata import ilr, inverse_ilr -from pyrolite.plot.density.ternary import ternary_heatmap - -coords, H, data = ternary_heatmap( - df.values, - bins=10, - mode="density", - remove_background=True, - transform=ilr, - inverse_transform=inverse_ilr, - grid_border_frac=0.2, -) -####################################################################################### -# This function returns more than just the coordinates and histogram/density estimate, -# which will come in handy for exploring how it came together. The data variable here -# is a dictonary with contains the grids and coordiantes used to construct the -# histogram/density diagram. We can use these to show how the ternary log-grid is -# constructed, and then transformed back to ternary space before being triangulated -# and interpoalted for the ternary heatmap: -# -import matplotlib.pyplot as plt - -import pyrolite.plot -from pyrolite.util.math import flattengrid -from pyrolite.util.plot.axes import axes_to_ternary, share_axes - -fig, ax = plt.subplots(3, 2, figsize=(6, 9)) -ax = ax.flat - -share_axes([ax[1], ax[2], ax[3]]) -ax = axes_to_ternary([ax[0], ax[4], ax[5]]) - -ax[0].set_title("data", y=1.2) -df.pyroplot.scatter(ax=ax[0], c="k", alpha=0.1) -ax[0].scatter(*data["tern_bound_points"].T, c="k") - -ax[1].set_title("transformed data", y=1.2) -ax[1].scatter(*data["tfm_tern_bound_points"].T, c="k") -ax[1].scatter(*data["grid_transform"](df.values).T, c="k", alpha=0.1) - -ax[2].set_title("log grid", y=1.2) -ax[2].scatter(*flattengrid(data["tfm_centres"]).T, c="k", marker=".", s=5) -ax[2].scatter(*flattengrid(data["tfm_edges"]).T, c="k", marker=".", s=2) -ax[2].scatter(*data["tfm_tern_bound_points"].T, c="k") - -ax[3].set_title("log-grid heatmap", y=1.2) -ax[3].pcolormesh(*data["tfm_edges"], H) -ax[3].scatter(*data["grid_transform"](df.values).T, c="white", alpha=0.8, s=1) - -ax[4].set_title("ternary log-grid", y=1.2) -ax[4].scatter(*data["tern_centres"].T, c="k", marker=".", s=5) -ax[4].scatter(*data["tern_edges"].T, c="k", marker=".", s=2) -ax[4].scatter(*data["tern_bound_points"].T, c="k") - -ax[5].set_title("ternary heatmap", y=1.2) -ax[5].tripcolor(*coords.T, H.flatten()) -ax[5].scatter(*data["tern_bound_points"].T, c="k") - - -plt.tight_layout() -####################################################################################### -plt.close("all") # let's save some memory.. -####################################################################################### -# We can see how this works almost exactly the same for the histograms: -# -coords, H, data = ternary_heatmap( - df.values, - bins=10, - mode="histogram", - remove_background=True, - transform=ilr, - inverse_transform=inverse_ilr, - grid_border_frac=0.2, -) -####################################################################################### -fig, ax = plt.subplots(3, 2, figsize=(6, 9)) -ax = ax.flat - -share_axes([ax[1], ax[2], ax[3]]) -ax = axes_to_ternary([ax[0], ax[4], ax[5]]) - -ax[0].set_title("data", y=1.2) -df.pyroplot.scatter(ax=ax[0], c="k", alpha=0.1) -ax[0].scatter(*data["tern_bound_points"].T, c="k") - -ax[1].set_title("transformed data", y=1.2) -ax[1].scatter(*data["tfm_tern_bound_points"].T, c="k") -ax[1].scatter(*data["grid_transform"](df.values).T, c="k", alpha=0.1) - -ax[2].set_title("log grid", y=1.2) -ax[2].scatter(*flattengrid(data["tfm_centres"]).T, c="k", marker=".", s=5) -ax[2].scatter(*flattengrid(data["tfm_edges"]).T, c="k", marker=".", s=2) -ax[2].scatter(*data["tfm_tern_bound_points"].T, c="k") - -ax[3].set_title("log-grid heatmap", y=1.2) -ax[3].pcolormesh(*data["tfm_centres"], H) -ax[3].scatter(*data["grid_transform"](df.values).T, c="white", alpha=0.8, s=1) - -ax[4].set_title("ternary log-grid", y=1.2) -ax[4].scatter(*data["tern_centres"].T, c="k", marker=".", s=5) -ax[4].scatter(*data["tern_edges"].T, c="k", marker=".", s=2) -ax[4].scatter(*data["tern_bound_points"].T, c="k") - -ax[5].set_title("ternary heatmap", y=1.2) -ax[5].tripcolor(*coords.T, H.flatten()) -ax[5].scatter(*data["tern_bound_points"].T, c="k") - -plt.tight_layout() diff --git a/docs/source/tutorials/ternary_density.py.md5 b/docs/source/tutorials/ternary_density.py.md5 deleted file mode 100644 index ff6fbc2c..00000000 --- a/docs/source/tutorials/ternary_density.py.md5 +++ /dev/null @@ -1 +0,0 @@ -0ec51686095a77e90c13a28377c64f31 \ No newline at end of file diff --git a/docs/source/tutorials/ternary_density.rst b/docs/source/tutorials/ternary_density.rst deleted file mode 100644 index 78c3e9eb..00000000 --- a/docs/source/tutorials/ternary_density.rst +++ /dev/null @@ -1,241 +0,0 @@ -.. rst-class:: sphx-glr-example-title - -.. _sphx_glr_tutorials_ternary_density.py: - - -One Way to Do Ternary Heatmaps -================================== - -There are multiple ways you can acheive ternary heatmaps, but those based on -the cartesian axes (e.g. a regularly spaced rectangular grid, or even a regularly -spaced triangular grid) can result in difficulties and data misrepresentation. - -Here we illustrate how the ternary heatmaps for pyrolite are constructed using an -irregualr triangulated grid and log transforms, and how this avoids some of the -potential issues of the methods mentioned above. - -Let's first get some data to deal with. :mod:`mpltern` has a conventient dataset -which we can use here: - - - -.. code-block:: default - - import numpy as np - import pandas as pd - from mpltern.ternary.datasets import get_scatter_points - - np.random.seed(43) - df = pd.DataFrame(np.array([*get_scatter_points(n=80)]).T, columns=["A", "B", "C"]) - df = df.loc[(df > 0.1).all(axis=1), :] - - - - - - - -From this dataset we'll generate a -:func:`~pyrolite.plot.density.ternary.ternary_heatmap`, which is the basis -for ternary density diagrams via :func:`~pyrolite.plot.pyrochem.density`: - - - -.. code-block:: default - - from pyrolite.comp.codata import ilr, inverse_ilr - from pyrolite.plot.density.ternary import ternary_heatmap - - coords, H, data = ternary_heatmap( - df.values, - bins=10, - mode="density", - remove_background=True, - transform=ilr, - inverse_transform=inverse_ilr, - grid_border_frac=0.2, - ) - - - - - - - -This function returns more than just the coordinates and histogram/density estimate, -which will come in handy for exploring how it came together. The data variable here -is a dictonary with contains the grids and coordiantes used to construct the -histogram/density diagram. We can use these to show how the ternary log-grid is -constructed, and then transformed back to ternary space before being triangulated -and interpoalted for the ternary heatmap: - - - -.. code-block:: default - - import matplotlib.pyplot as plt - import pyrolite.plot - from pyrolite.util.math import flattengrid - from pyrolite.util.plot.axes import axes_to_ternary, share_axes - - fig, ax = plt.subplots(3, 2, figsize=(6, 9)) - ax = ax.flat - - share_axes([ax[1], ax[2], ax[3]]) - ax = axes_to_ternary([ax[0], ax[4], ax[5]]) - - ax[0].set_title("data", y=1.2) - df.pyroplot.scatter(ax=ax[0], c="k", alpha=0.1) - ax[0].scatter(*data["tern_bound_points"].T, c="k") - - ax[1].set_title("transformed data", y=1.2) - ax[1].scatter(*data["tfm_tern_bound_points"].T, c="k") - ax[1].scatter(*data["grid_transform"](df.values).T, c="k", alpha=0.1) - - ax[2].set_title("log grid", y=1.2) - ax[2].scatter(*flattengrid(data["tfm_centres"]).T, c="k", marker=".", s=5) - ax[2].scatter(*flattengrid(data["tfm_edges"]).T, c="k", marker=".", s=2) - ax[2].scatter(*data["tfm_tern_bound_points"].T, c="k") - - ax[3].set_title("log-grid heatmap", y=1.2) - ax[3].pcolormesh(*data["tfm_edges"], H) - ax[3].scatter(*data["grid_transform"](df.values).T, c="white", alpha=0.8, s=1) - - ax[4].set_title("ternary log-grid", y=1.2) - ax[4].scatter(*data["tern_centres"].T, c="k", marker=".", s=5) - ax[4].scatter(*data["tern_edges"].T, c="k", marker=".", s=2) - ax[4].scatter(*data["tern_bound_points"].T, c="k") - - ax[5].set_title("ternary heatmap", y=1.2) - ax[5].tripcolor(*coords.T, H.flatten()) - ax[5].scatter(*data["tern_bound_points"].T, c="k") - - - plt.tight_layout() - - - -.. image:: /tutorials/images/sphx_glr_ternary_density_001.png - :class: sphx-glr-single-img - - - - - - -.. code-block:: default - - plt.close("all") # let's save some memory.. - - - - - - - -We can see how this works almost exactly the same for the histograms: - - - -.. code-block:: default - - coords, H, data = ternary_heatmap( - df.values, - bins=10, - mode="histogram", - remove_background=True, - transform=ilr, - inverse_transform=inverse_ilr, - grid_border_frac=0.2, - ) - - - - - - - - -.. code-block:: default - - fig, ax = plt.subplots(3, 2, figsize=(6, 9)) - ax = ax.flat - - share_axes([ax[1], ax[2], ax[3]]) - ax = axes_to_ternary([ax[0], ax[4], ax[5]]) - - ax[0].set_title("data", y=1.2) - df.pyroplot.scatter(ax=ax[0], c="k", alpha=0.1) - ax[0].scatter(*data["tern_bound_points"].T, c="k") - - ax[1].set_title("transformed data", y=1.2) - ax[1].scatter(*data["tfm_tern_bound_points"].T, c="k") - ax[1].scatter(*data["grid_transform"](df.values).T, c="k", alpha=0.1) - - ax[2].set_title("log grid", y=1.2) - ax[2].scatter(*flattengrid(data["tfm_centres"]).T, c="k", marker=".", s=5) - ax[2].scatter(*flattengrid(data["tfm_edges"]).T, c="k", marker=".", s=2) - ax[2].scatter(*data["tfm_tern_bound_points"].T, c="k") - - ax[3].set_title("log-grid heatmap", y=1.2) - ax[3].pcolormesh(*data["tfm_centres"], H) - ax[3].scatter(*data["grid_transform"](df.values).T, c="white", alpha=0.8, s=1) - - ax[4].set_title("ternary log-grid", y=1.2) - ax[4].scatter(*data["tern_centres"].T, c="k", marker=".", s=5) - ax[4].scatter(*data["tern_edges"].T, c="k", marker=".", s=2) - ax[4].scatter(*data["tern_bound_points"].T, c="k") - - ax[5].set_title("ternary heatmap", y=1.2) - ax[5].tripcolor(*coords.T, H.flatten()) - ax[5].scatter(*data["tern_bound_points"].T, c="k") - - plt.tight_layout() - - - -.. image:: /tutorials/images/sphx_glr_ternary_density_002.png - :class: sphx-glr-single-img - - - - - - -.. rst-class:: sphx-glr-timing - - **Total running time of the script:** ( 0 minutes 3.597 seconds) - - -.. _sphx_glr_download_tutorials_ternary_density.py: - - -.. only :: html - - .. container:: sphx-glr-footer - :class: sphx-glr-footer-example - - - .. container:: binder-badge - - .. image:: https://mybinder.org/badge_logo.svg - :target: https://mybinder.org/v2/gh/morganjwilliams/pyrolite/develop?filepath=docs/source/tutorials/ternary_density.ipynb - :width: 150 px - - - .. container:: sphx-glr-download sphx-glr-download-python - - :download:`Download Python source code: ternary_density.py ` - - - - .. container:: sphx-glr-download sphx-glr-download-jupyter - - :download:`Download Jupyter notebook: ternary_density.ipynb ` - - -.. only:: html - - .. rst-class:: sphx-glr-signature - - `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/source/tutorials/ternary_density_codeobj.pickle b/docs/source/tutorials/ternary_density_codeobj.pickle deleted file mode 100644 index 007c0886..00000000 Binary files a/docs/source/tutorials/ternary_density_codeobj.pickle and /dev/null differ diff --git a/environment.yml b/environment.yml index 62efa708..6b380fc0 100644 --- a/environment.yml +++ b/environment.yml @@ -20,7 +20,6 @@ dependencies: - tinydb - periodictable - mpltern>=0.4.0 - - mpmath - sympy>=1.7 # import changes after sympy 1.6 - joblib - requests @@ -35,8 +34,6 @@ dependencies: - pip - black - isort - - jedi<0.18.0 # for use on atom/ipython - - pyzmq - pytest - pytest-runner - pytest-cov diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..684958d4 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,107 @@ +[build-system] +requires = ["setuptools>=61.0", "versioneer[toml]"] +build-backend = "setuptools.build_meta" + + +[project] +name = "pyrolite" +authors = [{ name = "Morgan Williams", email = "morgan.williams@csiro.au" }] +description = "Tools for geochemical data analysis." +license = { file = "LICENSE" } +requires-python = ">=3.8" +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Science/Research", + "Intended Audience :: Education", + "Natural Language :: English", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Framework :: Matplotlib", + "Topic :: Scientific/Engineering", + "Topic :: Software Development :: Libraries :: Python Modules", +] +keywords = ["geochemistry", "compositional data", "visualisation", "petrology"] +dynamic = ["version", "readme"] +dependencies = [ + "numpy", + "numpydoc", + "tinydb>4.1", # >4.1 required for read-only access mode for JSON storage + "periodictable", + "matplotlib", + "mpltern>=0.4.0", + "scipy>=1.2", # uses scipy.optimize.Bounds, added around 1.2 + "sympy>=1.7", + "pandas>=1.0", # dataframe acccessors, attrs attribute + "requests", # used by alphaMELTS utilities, util.web +] + +[tool.setuptools.packages] +find = { exclude = ['test*', "docs*"] } # "**/__pycache__/*" +# include = ["Aitchison/*.py"], + +[tool.setuptools.dynamic] +readme = { file = "README.md", content-type = "text/markdown" } + +[project.urls] +"Issue tracker" = "https://github.com/morganjwilliams/pyrolite/issues" +"Documentation" = "https://pyrolite.readthedocs.io/" +"Code" = "https://github.com/morganjwilliams/pyrolite" + +[project.optional-dependencies] +docs = [ + "sphinx_rtd_theme", + "docutils<0.17", + "sphinx>=4", + "sphinx-autodoc-annotation", + "sphinx_gallery>=0.6.0", + "recommonmark", + # "jupyterlite-sphinx", + # "jupyterlite-pyodide-kernel", +] +db = ["pyodbc", "psycopg2"] +test = ["pytest", "pytest-runner", "pytest-cov", "coverage", "coveralls"] +skl = ["scikit-learn", "joblib"] +spatial = ["owslib", "geojson", "psutil"] +stats = ["statsmodels", "scikit-learn"] # statsmodels for conditional ke +excel = ["xlrd", "openpyxl"] +dev = [ + "pytest", + "versioneer", + "black", + "isort", + "twine", + "pyrolite[test,docs,skl]", + "build", +] + +[metadata] +url = "https://github.com/morganjwilliams/pyrolite" + +[tool.coverage.run] +relative_files = true +source = ["pyrolite"] +omit = [ + "test/*", # Omit test, docs, draft and data files + "docs/*", + "**/data", + "draft/*", + "pyrolite/util/database.py", # Omit extensions with extra dependencies + "*/_version.py", # Ignore _version.py +] + +[tool.versioneer] +VCS = "git" +style = "pep440" +versionfile_source = "pyrolite/_version.py" +versionfile_build = "pyrolite/_version.py" +tag_prefix = "" +parentdir_prefix = "pyrolite-" + +[tool.pytest.ini_options] +python_files = "*.py" +addopts = "--cov=pyrolite --cov-report html --cov-report xml --cov-report term-missing --cov-config .coveragerc" +testpaths = ["test"] +pythonpath = ["."] diff --git a/pyrolite/__init__.py b/pyrolite/__init__.py index 564a26c2..29a64537 100644 --- a/pyrolite/__init__.py +++ b/pyrolite/__init__.py @@ -44,3 +44,6 @@ def load_extensions(base="pyrolite_", replace=["util"]): # _export_pyrolite_mplstyle() should be called in .plot import regardless matplotlib.style.use("pyrolite") + +from . import _version +__version__ = _version.get_versions()['version'] diff --git a/pyrolite/_version.py b/pyrolite/_version.py index ee3b95da..1131671c 100644 --- a/pyrolite/_version.py +++ b/pyrolite/_version.py @@ -1,11 +1,13 @@ + # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. -# This file is released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) +# This file is released into the public domain. +# Generated by versioneer-0.29 +# https://github.com/python-versioneer/python-versioneer """Git implementation of _version.py.""" @@ -14,9 +16,11 @@ import re import subprocess import sys +from typing import Any, Callable, Dict, List, Optional, Tuple +import functools -def get_keywords(): +def get_keywords() -> Dict[str, str]: """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must @@ -32,8 +36,15 @@ def get_keywords(): class VersioneerConfig: """Container for Versioneer configuration parameters.""" + VCS: str + style: str + tag_prefix: str + parentdir_prefix: str + versionfile_source: str + verbose: bool + -def get_config(): +def get_config() -> VersioneerConfig: """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py @@ -51,41 +62,50 @@ class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" -LONG_VERSION_PY = {} -HANDLERS = {} - +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f - return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): +def run_command( + commands: List[str], + args: List[str], + cwd: Optional[str] = None, + verbose: bool = False, + hide_stderr: bool = False, + env: Optional[Dict[str, str]] = None, +) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: + process = None + + popen_kwargs: Dict[str, Any] = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: try: - dispcmd = str([c] + args) + dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen( - [c] + args, - cwd=cwd, - env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr else None), - ) + process = subprocess.Popen([command] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None), **popen_kwargs) break - except EnvironmentError: - e = sys.exc_info()[1] + except OSError as e: if e.errno == errno.ENOENT: continue if verbose: @@ -96,18 +116,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env= if verbose: print("unable to find command, tried %s" % (commands,)) return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode + return None, process.returncode + return stdout, process.returncode -def versions_from_parentdir(parentdir_prefix, root, verbose): +def versions_from_parentdir( + parentdir_prefix: str, + root: str, + verbose: bool, +) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both @@ -116,64 +138,64 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): - return { - "version": dirname[len(parentdir_prefix) :], - "full-revisionid": None, - "dirty": False, - "error": None, - "date": None, - } - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: - print( - "Tried directories %s but none started with prefix %s" - % (str(rootdirs), parentdir_prefix) - ) + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. - keywords = {} + keywords: Dict[str, str] = {} try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: pass return keywords @register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): +def git_versions_from_keywords( + keywords: Dict[str, str], + tag_prefix: str, + verbose: bool, +) -> Dict[str, Any]: """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because @@ -186,11 +208,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -199,7 +221,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r"\d", r)]) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -207,30 +229,33 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix) :] + r = ref[len(tag_prefix):] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r'\d', r): + continue if verbose: print("picking %s" % r) - return { - "version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": None, - "date": date, - } + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return { - "version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": "no suitable tags", - "date": None, - } + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs( + tag_prefix: str, + root: str, + verbose: bool, + runner: Callable = run_command +) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -241,7 +266,15 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -249,33 +282,57 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command( - GITS, - [ - "describe", - "--tags", - "--dirty", - "--always", - "--long", - "--match", - "%s*" % tag_prefix, - ], - cwd=root, - ) + describe_out, rc = runner(GITS, [ + "describe", "--tags", "--dirty", "--always", "--long", + "--match", f"{tag_prefix}[[:digit:]]*" + ], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() - pieces = {} + pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -284,16 +341,17 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[: git_describe.rindex("-dirty")] + git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out + # unparsable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) return pieces # tag @@ -302,12 +360,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( - full_tag, - tag_prefix, - ) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix) :] + pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -318,26 +374,27 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ - 0 - ].strip() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces -def plus_or_dot(pieces): +def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" -def render_pep440(pieces): +def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you @@ -355,29 +412,78 @@ def render_pep440(pieces): rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. +def render_pep440_branch(pieces: Dict[str, Any]) -> str: + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). Exceptions: - 1: no tags. 0.post.devDISTANCE + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces: Dict[str, Any]) -> str: + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%d" % (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] + rendered = "0.post0.dev%d" % pieces["distance"] return rendered -def render_pep440_post(pieces): +def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards @@ -404,12 +510,41 @@ def render_pep440_post(pieces): return rendered -def render_pep440_old(pieces): +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: @@ -426,7 +561,7 @@ def render_pep440_old(pieces): return rendered -def render_git_describe(pieces): +def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. @@ -446,7 +581,7 @@ def render_git_describe(pieces): return rendered -def render_git_describe_long(pieces): +def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. @@ -466,26 +601,28 @@ def render_git_describe_long(pieces): return rendered -def render(pieces, style): +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: - return { - "version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None, - } + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -495,16 +632,12 @@ def render(pieces, style): else: raise ValueError("unknown style '%s'" % style) - return { - "version": rendered, - "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], - "error": None, - "date": pieces.get("date"), - } + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} -def get_versions(): +def get_versions() -> Dict[str, Any]: """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some @@ -515,7 +648,8 @@ def get_versions(): verbose = cfg.verbose try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) except NotThisMethod: pass @@ -524,16 +658,13 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split("/"): + for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: - return { - "version": "0+unknown", - "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None, - } + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) @@ -547,10 +678,6 @@ def get_versions(): except NotThisMethod: pass - return { - "version": "0+unknown", - "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", - "date": None, - } + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} diff --git a/pyrolite/comp/codata.py b/pyrolite/comp/codata.py index 7ed883bf..bc49bf53 100644 --- a/pyrolite/comp/codata.py +++ b/pyrolite/comp/codata.py @@ -601,7 +601,7 @@ def sphere(ys): S = 1 else: # vector - the product of sin components - S = np.product(np.sin(θ[:, ix:]), axis=1) + S = np.prod(np.sin(θ[:, ix:]), axis=1) # where this evaluates to zero, the composition is all in the first component S[np.isclose(S, 0.0)] = 1.0 diff --git a/pyrolite/mineral/normative.py b/pyrolite/mineral/normative.py index 16de83d5..2bd7da56 100644 --- a/pyrolite/mineral/normative.py +++ b/pyrolite/mineral/normative.py @@ -667,6 +667,8 @@ def CIPW_norm( df["SO3"] = SO3 df["S"] = S + minors_trace.append("SO3") + ############################################################################ # Normalization # Adjust majors wt% to 100% then adjust again to account for trace components @@ -778,7 +780,7 @@ def corr_m_wt(oxide): minerals["An"]["mass"] = df["MW_CaO_corr"] + pt.formula("Al2O3 (SiO2)2").mass minerals["Mg-Di"]["mass"] = df["MW_CaO_corr"] + pt.formula("MgO (SiO2)2").mass minerals["Wo"]["mass"] = df["MW_CaO_corr"] + pt.formula("SiO2").mass - minerals["Cs"]["mass"] = 2 * df["MW_CaO_corr"] + pt.formula("SiO2").mass + minerals["Cs"]["mass"] = (2 * df["MW_CaO_corr"]) + pt.formula("SiO2").mass minerals["Tn"]["mass"] = df["MW_CaO_corr"] + pt.formula("TiO2 SiO2").mass minerals["Pf"]["mass"] = df["MW_CaO_corr"] + pt.formula("TiO2").mass minerals["CaF2-Ap"]["mass"] = ( @@ -827,7 +829,7 @@ def corr_m_wt(oxide): df["CaO"] >= (3 + 1 / 3) * df["P2O5"], df["CaO"] - (3 + 1 / 3) * df["Ap"], 0 ).T - df["P2O5"] = np.where( + df["P2O5_"] = np.where( df["CaO"] < (3 + 1 / 3) * df["P2O5"], df["P2O5"] - df["Ap"], 0 ).T @@ -851,7 +853,7 @@ def corr_m_wt(oxide): df["F"] = np.where(df["ap_option"] == 3, 0, df["F"]).T - df["FREE_P2O5"] = df["P2O5"] + df["FREE_P2O5"] = df["P2O5_"] df["FREEO_12b"] = np.where(df["ap_option"] == 2, 1 / 3 * df["Ap"], 0).T df["FREEO_12c"] = np.where(df["ap_option"] == 3, df["F"] / 2, 0).T @@ -859,77 +861,87 @@ def corr_m_wt(oxide): # Normative Fluorite df["Fr"] = np.where(df["CaO"] >= df["F"] / 2, df["F"] / 2, df["CaO"]).T - df["CaO"] = np.where(df["CaO"] >= df["F"] / 2, df["CaO"] - df["Fr"], 0).T + df["CaO_"] = np.where(df["CaO"] >= df["F"] / 2, df["CaO"] - df["Fr"], 0).T - df["F"] = np.where(df["CaO"] >= df["F"] / 2, df["F"], df["F"] - (2 * df["Fr"])).T + df["F"] = np.where(df["CaO"] >= df["F"] / 2, 0, df["F"] - (2 * df["Fr"])).T + df["CaO"] = df["CaO_"] df["FREEO_13"] = df["Fr"] df["FREE_F"] = df["F"] # Normative halite - df["Hl"] = np.where(df["Na2O"] >= 2 * df["Cl"], df["Cl"], df["Na2O"] / 2).T + df["Hl"] = np.where(df["Na2O"] >= (2 * df["Cl"]), df["Cl"], df["Na2O"]/2).T + + df["Na2O_"] = np.where(df["Na2O"] >= (2 * df["Cl"]), df["Na2O"] - df["Hl"]/2, 0).T - df["Na2O"] = np.where(df["Na2O"] >= 2 * df["Cl"], df["Na2O"] - df["Hl"] / 2, 0).T + df["Cl"] = np.where(df["Na2O"] >= (2 * df["Cl"]), 0, df["Cl"] - df["Hl"]).T - df["Cl"] = np.where(df["Na2O"] >= 2 * df["Cl"], df["Cl"], df["Cl"] - df["Hl"]).T + df["Na2O"] = df["Na2O_"] df["FREE_Cl"] = df["Cl"] df["FREEO_14"] = df["Hl"] / 2 # Normative thenardite - df["Th"] = np.where((df["SO3"] > 0) & (df["Na2O"] >= df["SO3"]), df["SO3"], 0).T df["Th"] = np.where( - (df["SO3"] > 0) & (df["Na2O"] < df["SO3"]), df["Na2O"], df["Th"] + df["Na2O"] >= df["SO3"], df["SO3"], df["Na2O"] ).T df["Na2O_"] = np.where( - (df["SO3"] > 0) & (df["Na2O"] >= df["SO3"]), df["Na2O"] - df["Th"], df["Na2O"] + df["Na2O"] >= df["SO3"], df["Na2O"] - df["Th"], 0 ).T - df["Na2O"] = np.where((df["SO3"] > 0) & (df["Na2O"] < df["SO3"]), 0, df["Na2O_"]).T - df["SO3"] = np.where( - (df["SO3"] > 0) & (df["Na2O"] < df["SO3"]), df["SO3"] - df["Th"], df["SO3"] + df["Na2O"] >= df["SO3"], 0, df["SO3"] - df["Th"] ).T + df["Na2O"] = df["Na2O_"] + df["FREE_SO3"] = df["SO3"] # Normative Pyrite - df["Pr"] = np.where(df["FeO"] >= 2 * df["S"], df["S"] / 2, df["S"]).T + df["Pr"] = np.where(df["FeO"] >= 2 * df["S"], df["S"] / 2, df["FeO"]).T df["FeO_"] = np.where(df["FeO"] >= 2 * df["S"], df["FeO"] - df["Pr"], 0).T - df["FeO"] = np.where(df["S"] > 0, df["FeO_"], df["FeO"]).T + df["S"] = np.where(df["FeO"] >= 2 * df["S"], 0, df["S"] - 2*df['Pr']).T - df["FREE_S"] = np.where(df["FeO"] >= 2 * df["S"], 0, df["S"]).T + df["FeO"] = df["FeO_"] + df['FREE_S'] = df['S'] df["FREEO_16"] = df["Pr"] # Normative sodium carbonate (cancrinite) or calcite df["Nc"] = np.where(df["Na2O"] >= df["CO2"], df["CO2"], df["Na2O"]).T - df["Na2O"] = np.where(df["Na2O"] >= df["CO2"], df["Na2O"] - df["Nc"], df["Na2O"]).T + df["Na2O_"] = np.where(df["Na2O"] >= df["CO2"], df["Na2O"] - df["Nc"], 0).T + + df["CO2"] = np.where(df["Na2O"] >= df["CO2"], 0, df["CO2"] - df["Nc"]).T - df["CO2"] = np.where(df["Na2O"] >= df["CO2"], df["CO2"], df["CO2"] - df["Nc"]).T + df['Na2O'] = df['Na2O_'] df["Cc"] = np.where(df["CaO"] >= df["CO2"], df["CO2"], df["CaO"]).T - df["CaO"] = np.where(df["Na2O"] >= df["CO2"], df["CaO"] - df["Cc"], df["CaO"]).T + df["CaO_"] = np.where(df["CaO"] >= df["CO2"], df["CaO"] - df["Cc"], 0).T - df["CO2"] = np.where(df["Na2O"] >= df["CO2"], df["CO2"], df["CO2"] - df["Cc"]).T + df["CO2"] = np.where(df["CaO"] >= df["CO2"], 0, df["CO2"] - df["Cc"]).T + + df['CaO'] = df['CaO_'] df["FREECO2"] = df["CO2"] # Normative Chromite df["Cm"] = np.where(df["FeO"] >= df["Cr2O3"], df["Cr2O3"], df["FeO"]).T - df["FeO"] = np.where(df["FeO"] >= df["Cr2O3"], df["FeO"] - df["Cm"], 0).T + df["FeO_"] = np.where(df["FeO"] >= df["Cr2O3"], df["FeO"] - df["Cm"], 0).T + df["Cr2O3"] = np.where( df["FeO"] >= df["Cr2O3"], df["Cr2O3"] - df["Cm"], df["Cr2O3"] ).T - df["FREE_CR2O3"] = df["Cm"] + df["FeO"] = df["FeO_"] + + df["FREE_CR2O3"] = df["Cr2O3"] # Normative Ilmenite df["Il"] = np.where(df["FeO"] >= df["TiO2"], df["TiO2"], df["FeO"]).T @@ -1072,7 +1084,7 @@ def corr_m_wt(oxide): df["Hy"] = np.where((df["D"] < df["Hy_p"] / 2), df["Hy_p"] - 2 * df["D"], 0).T - df["D1"] = df["D"] - df["Hy_p"] / 2 + df["D1"] = df["D"] - (df["Hy_p"] / 2) df["Ol"] = np.where((df["deficit"]), df["Ol_"], 0).T @@ -1093,9 +1105,9 @@ def corr_m_wt(oxide): df["deficit"] = df["D2"] > 0 # Normative Nepheline / Albite - df["Ne_"] = np.where((df["D2"] < 4 * df["Ab_p"]), df["D2"] / 4, df["Ab_p"]).T + df["Ne_"] = np.where(df["D2"] < 4 * df["Ab_p"], df["D2"] / 4, df["Ab_p"]).T - df["Ab"] = np.where((df["D2"] < 4 * df["Ab_p"]), df["Ab_p"] - df["D2"] / 4, 0).T + df["Ab"] = np.where(df["D2"] < 4 * df["Ab_p"], df["Ab_p"] - df["D2"] / 4, 0).T df["D3"] = df["D2"] - 4 * df["Ab_p"] @@ -1294,4 +1306,4 @@ def corr_m_wt(oxide): ) ) - return pd.concat(outputs, axis=1).round(rounding) + return pd.concat(outputs, axis=1).round(rounding) \ No newline at end of file diff --git a/pyrolite/util/meta.py b/pyrolite/util/meta.py index fea13576..986701d9 100644 --- a/pyrolite/util/meta.py +++ b/pyrolite/util/meta.py @@ -24,9 +24,7 @@ def get_module_datafolder(module="pyrolite", subfolder=None): ------- :class:`pathlib.Path` """ - pth = ( - Path(importlib.machinery.PathFinder().find_spec(module).origin).parent / "data" - ) + pth = Path(importlib.util.find_spec(module).origin).parent / "data" if subfolder: pth /= subfolder return pth diff --git a/pyrolite/util/spatial.py b/pyrolite/util/spatial.py index 73942910..1ce4151b 100644 --- a/pyrolite/util/spatial.py +++ b/pyrolite/util/spatial.py @@ -4,7 +4,11 @@ import itertools import numpy as np -from psutil import virtual_memory # memory check + +try: + from psutil import virtual_memory # memory check +except ImportError: + virtual_memory = None from .log import Handle @@ -176,14 +180,16 @@ def great_circle_distance( # but, with large arrays it'll spit out a memory error # so instead we can try to build it numerically size = np.max([a.shape[0] for a in [φ1, φ2, λ1, λ2]]) - mem = virtual_memory().total # total physical memory available estimated_matrix_size = np.array([[1.0]], dtype=dtype).nbytes * size**2 logger.debug( "Attempting to build {}x{} array of size {:.2f} Gb.".format( size, size, estimated_matrix_size / 1024**3 ) ) - if estimated_matrix_size > (mem * max_memory_fraction): + + infeasible = estimated_matrix_size > (virtual_memory().total * max_memory_fraction) if virtual_memory is not None else False + + if infeasible: logger.warn( "Angle array for segmented distance matrix larger than maximum memory " "fraction, computing mean global distances instead." diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index d6ceba15..00000000 --- a/setup.cfg +++ /dev/null @@ -1,18 +0,0 @@ -[aliases] -test=pytest - -[tool:pytest] -addopts = test --cov=pyrolite --cov-report html --cov-report xml --cov-report term-missing --cov-config .coveragerc -python_files = *.py - -[versioneer] -VCS = git -style = pep440 -versionfile_source = pyrolite/_version.py -versionfile_build = pyrolite/_version.py -tag_prefix = -parentdir_prefix = pyrolite- - -[metadata] -description_file = README.md -license_file = LICENSE diff --git a/setup.py b/setup.py index 163f6f90..01cfba14 100644 --- a/setup.py +++ b/setup.py @@ -1,86 +1,8 @@ -from setuptools import find_packages, setup +from setuptools import setup import versioneer -tests_require = ["pytest", "pytest-runner", "pytest-cov", "coverage", "coveralls"] -docs_require = [ - "sphinx_rtd_theme", - "docutils<0.17", - "sphinx>=4", - "sphinx-autodoc-annotation", - "sphinx_gallery>=0.6.0", - "recommonmark", - # "jupyterlite-sphinx", - # "jupyterlite-pyodide-kernel", -] -dev_require = ["pytest", "versioneer", "black", "isort", "twine"] + tests_require + docs_require -db_require = ["pyodbc", "psycopg2"] -skl_require = ["scikit-learn"] -stats_require = ["statsmodels", "scikit-learn"] -spatial_require = ["owslib", "geojson"] # this needs pyproj -> C compiler - -with open("README.md", "r") as src: - LONG_DESCRIPTION = src.read() - setup( - name="pyrolite", - description="Tools for geochemical data analysis.", - long_description=LONG_DESCRIPTION, - long_description_content_type="text/markdown", version=versioneer.get_version(), - url="https://github.com/morganjwilliams/pyrolite", - project_urls={ - "Documentation": "https://pyrolite.readthedocs.io/", - "Code": "https://github.com/morganjwilliams/pyrolite", - "Issue tracker": "https://github.com/morganjwilliams/pyrolite/issues", - }, - author="Morgan Williams", - author_email="morgan.williams@csiro.au", - classifiers=[ - "Development Status :: 4 - Beta", - "Intended Audience :: Science/Research", - "Intended Audience :: Education", - "Natural Language :: English", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Framework :: Matplotlib", - "Topic :: Scientific/Engineering", - "Topic :: Software Development :: Libraries :: Python Modules", - ], - keywords=["geochemistry", "compositional data", "visualisation", "petrology"], - packages=find_packages(exclude=["test*"]), - install_requires=[ - "numpy", - "numpydoc", - "tinydb>4.1", # >4.1 required for read-only access mode for JSON storage - "typing-extensions", # required for newer tinydb versions? - "psutil", - "periodictable", - "matplotlib", - "mpltern>=0.4.0", - "scipy>=1.2", # uses scipy.optimize.Bounds, added around 1.2 - "mpmath", - "sympy>=1.7", - "pandas>=1.0", # dataframe acccessors, attrs attribute - "xlrd", # reading excel from pandas - "openpyxl", # writing excel from pandas - "joblib", - "requests", # used by alphaMELTS utilities, util.web - ], - extras_require={ - "dev": dev_require, - "docs": docs_require, - "skl": skl_require, - "spatial": spatial_require, - "db": db_require, - "stats": stats_require, - }, - tests_require=tests_require, - test_suite="test", - include_package_data=True, - license="CSIRO Modifed MIT/BSD", cmdclass=versioneer.get_cmdclass(), ) diff --git a/test/pytest.ini b/test/pytest.ini deleted file mode 100644 index 7c479554..00000000 --- a/test/pytest.ini +++ /dev/null @@ -1,2 +0,0 @@ -[pytest] -python_files = *.py diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 2b545405..00000000 --- a/versioneer.py +++ /dev/null @@ -1,1885 +0,0 @@ -# Version: 0.18 - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/warner/python-versioneer -* Brian Warner -* License: Public Domain -* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy -* [![Latest Version] -(https://pypip.in/version/versioneer/badge.svg?style=flat) -](https://pypi.python.org/pypi/versioneer/) -* [![Build Status] -(https://travis-ci.org/warner/python-versioneer.png?branch=master) -](https://travis-ci.org/warner/python-versioneer) - -This is a tool for managing a recorded version number in distutils-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -* `pip install versioneer` to somewhere to your $PATH -* add a `[versioneer]` section to your setup.cfg (see below) -* run `versioneer install` in your source tree, commit the results - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes. - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on Github -[issues page](https://github.com/warner/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other langauges) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - -### Unicode version strings - -While Versioneer works (and is continually tested) with both Python 2 and -Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. -Newer releases probably generate unicode version strings on py2. It's not -clear that this is wrong, but it may be surprising for applications when then -write these strings to a network connection or include them in bytes-oriented -APIs like cryptographic checksums. - -[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates -this question. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg`, if necessary, to include any new configuration settings - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . - -""" - -from __future__ import print_function - -try: - import configparser -except ImportError: - import ConfigParser as configparser -import errno -import json -import os -import re -import subprocess -import sys - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ( - "Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND')." - ) - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - me = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(me)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir: - print( - "Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py) - ) - except NameError: - pass - return root - - -def get_config_from_root(root): - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise EnvironmentError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.SafeConfigParser() - with open(setup_cfg, "r") as f: - parser.readfp(f) - VCS = parser.get("versioneer", "VCS") # mandatory - - def get(parser, name): - if parser.has_option("versioneer", name): - return parser.get("versioneer", name) - return None - - cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = get(parser, "style") or "" - cfg.versionfile_source = get(parser, "versionfile_source") - cfg.versionfile_build = get(parser, "versionfile_build") - cfg.tag_prefix = get(parser, "tag_prefix") - if cfg.tag_prefix in ("''", '""'): - cfg.tag_prefix = "" - cfg.parentdir_prefix = get(parser, "parentdir_prefix") - cfg.verbose = get(parser, "verbose") - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen( - [c] + args, - cwd=cwd, - env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr else None), - ) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode - - -LONG_VERSION_PY[ - "git" -] = ''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - p = None - for c in commands: - try: - dispcmd = str([c] + args) - # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, p.returncode - return stdout, p.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%%s*" %% tag_prefix], - cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], - cwd=root)[0].strip() - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%%d" %% pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") - date = keywords.get("date") - if date is not None: - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r"\d", r)]) - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix) :] - if verbose: - print("picking %s" % r) - return { - "version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": None, - "date": date, - } - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return { - "version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, - "error": "no suitable tags", - "date": None, - } - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command( - GITS, - [ - "describe", - "--tags", - "--dirty", - "--always", - "--long", - "--match", - "%s*" % tag_prefix, - ], - cwd=root, - ) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[: git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( - full_tag, - tag_prefix, - ) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix) :] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ - 0 - ].strip() - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def do_vcs_install(manifest_in, versionfile_source, ipy): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] - if ipy: - files.append(ipy) - try: - me = __file__ - if me.endswith(".pyc") or me.endswith(".pyo"): - me = os.path.splitext(me)[0] + ".py" - versioneer_file = os.path.relpath(me) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - f = open(".gitattributes", "r") - for line in f.readlines(): - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - f.close() - except EnvironmentError: - pass - if not present: - f = open(".gitattributes", "a+") - f.write("%s export-subst\n" % versionfile_source) - f.close() - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for i in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return { - "version": dirname[len(parentdir_prefix) :], - "full-revisionid": None, - "dirty": False, - "error": None, - "date": None, - } - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print( - "Tried directories %s but none started with prefix %s" - % (str(rootdirs), parentdir_prefix) - ) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.18) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except EnvironmentError: - raise NotThisMethod("unable to read _version.py") - mo = re.search( - r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S - ) - if not mo: - mo = re.search( - r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S - ) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Eexceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return { - "version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None, - } - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return { - "version": rendered, - "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], - "error": None, - "date": pieces.get("date"), - } - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert ( - cfg.versionfile_source is not None - ), "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return { - "version": "0+unknown", - "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", - "date": None, - } - - -def get_version(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(): - """Get the custom setuptools/distutils subclasses used by Versioneer.""" - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/warner/python-versioneer/issues/52 - - cmds = {} - - # we add "version" to both distutils and setuptools - from distutils.core import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - - cmds["version"] = cmd_version - - # we override "build_py" in both distutils and setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # we override different "build_py" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py - else: - from distutils.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - cmds["build_py"] = cmd_build_py - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write( - LONG - % { - "DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - } - ) - - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if "py2exe" in sys.modules: # py2exe enabled? - try: - from py2exe.distutils_buildexe import py2exe as _py2exe # py3 - except ImportError: - from py2exe.build_exe import py2exe as _py2exe # py2 - - class cmd_py2exe(_py2exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write( - LONG - % { - "DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - } - ) - - cmds["py2exe"] = cmd_py2exe - - # we override different "sdist" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist - else: - from distutils.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file( - target_versionfile, self._versioneer_generated_versions - ) - - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -INIT_PY_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - - -def do_setup(): - """Main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except ( - EnvironmentError, - configparser.NoSectionError, - configparser.NoOptionError, - ) as e: - if isinstance(e, (EnvironmentError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write( - LONG - % { - "DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - } - ) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except EnvironmentError: - old = "" - if INIT_PY_SNIPPET not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except EnvironmentError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print( - " appending versionfile_source ('%s') to MANIFEST.in" - % cfg.versionfile_source - ) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1)