Skip to content

Commit

Permalink
Merge branch 'release/0.1.5'
Browse files Browse the repository at this point in the history
  • Loading branch information
morganjwilliams committed Mar 26, 2019
2 parents 6aad213 + d95551b commit 4c7b3ab
Show file tree
Hide file tree
Showing 39 changed files with 585 additions and 151 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# `pyrolite`

<img src="https://raw.githubusercontent.com/morganjwilliams/pyrolite/develop/docs/source/_static/icon.png" alt="pyrolite Logo" width="30%" align="right">
<img src="https://raw.githubusercontent.com/morganjwilliams/pyrolite/develop/docs/source/_static/icon.jpg" alt="pyrolite Logo" width="30%" align="right">

<p align="left">
<a href="https://pypi.python.org/pypi/pyrolite/">
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/plotting/REE_v_radii.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@
fig, ax = plt.subplots(1, 2, sharey=True, figsize=(12, 4))

df1.pyroplot.REE(ax=ax[0])
# we can also change the mode of the second figure
ax1 = df2.pyroplot.REE(ax=ax[1], color='k', mode='elements')
# we can also change the index of the second figure
ax1 = df2.pyroplot.REE(ax=ax[1], color='k', index='elements')
plt.tight_layout()

# %% Save Figure
Expand Down
69 changes: 69 additions & 0 deletions docs/examples/plotting/conditionalspider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pyrolite.geochem.norm import ReferenceCompositions
from pyrolite.geochem.ind import REE
from pyrolite.plot.spider import spider
import logging

rc = ReferenceCompositions()
rn = rc["EMORB_SM89"] # emorb composition as a starting point
components = [i for i in rn.data.index if i in REE()]
data = rn[components]["value"]
nindex, nobs = data.index.size, 200
ss = [0.1, 0.2, 0.5] # sigmas for noise

modes = [
("plot", "plot", [], dict(color="k", alpha=0.01)),
("fill", "fill", [], dict()),
("binkde", "binkde", [], dict(resolution=5)),
(
"binkde",
"binkde percentiles specified",
[],
dict(percentiles=[0.95, 0.5], resolution=5),
),
("ckde", "ckde", [], dict(resolution=5)),
("kde", "kde", [], dict(resolution=5)),
("histogram", "histogram", [], dict(resolution=5)),
]

fig, ax = plt.subplots(
len(modes), len(ss), sharey=True, figsize=(len(ss) * 3, 2 * len(modes))
)
ax[0, 0].set_ylim((0.1, 100))

for a, (m, name, args, kwargs) in zip(ax, modes):
a[0].annotate( # label the axes rows
"Mode: {}".format(name),
xy=(0.1, 1.05),
xycoords=a[0].transAxes,
fontsize=8,
ha="left",
va="bottom",
)
for ix, s in enumerate(ss):
x = np.arange(nindex)
y = rc["PM_PON"].normalize(data).applymap(np.log)
y = np.tile(y, nobs).reshape(nobs, nindex)
y += np.random.normal(0, s / 2, size=(nobs, nindex)) # noise
y += np.random.normal(0, s, size=(1, nobs)).T # random pattern offset
df = pd.DataFrame(y, columns=components)
df["Eu"] += 1.0 # significant offset
df = df.applymap(np.exp)
for mix, (m, name, args, kwargs) in enumerate(modes):
df.pyroplot.spider(
indexes=x,
mode=m,
ax=ax[mix, ix],
cmap="viridis",
vmin=0.05,
*args,
**kwargs
)

plt.tight_layout()
# %% save figure
from pyrolite.util.plot import save_figure, save_axes

save_figure(fig, save_at="../../source/_static", name="spider_modes")
14 changes: 9 additions & 5 deletions docs/examples/plotting/logo.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@
for ix, sample in enumerate(df.Sample.unique()):
comp = df.query("Sample == {}".format(sample)).loc[:, ["SiO2", "MgO", "FeO"]]
tcomp = to_log(comp)
plot_stdev_ellipses(tcomp, color=t10b3[ix], **kwargs)
plot_pca_vectors(tcomp, ls="-", lw=0.5, color="k", **kwargs)
plot_stdev_ellipses(tcomp.values, color=t10b3[ix], **kwargs)
plot_pca_vectors(tcomp.values, ls="-", lw=0.5, color="k", **kwargs)
# %% individual density diagrams ------------------------------------------------------
kwargs = dict(ax=ax[-2], bins=100, no_ticks=True, axlabels=False)
for ix, sample in enumerate(df.Sample.unique()):
Expand All @@ -95,25 +95,29 @@
a.patch.set_facecolor(None)
a.patch.set_visible(False)
a.set_aspect("equal")
plt.tight_layout()

# %% Save Figure
from pyrolite.util.plot import save_axes, save_figure
from pathlib import Path
import svgutils

dpi = 600
save_at = Path("./../../source/_static/")
fmts = ["png", "jpg"]
save_axes(ax[1], name="icon", save_at=save_at, save_fmts=fmts+['svg'], dpi=dpi)
save_axes(ax[1], name="icon", save_at=save_at, save_fmts=fmts, dpi=dpi)

ax[0].set_title("Synthetic Data")
ax[1].set_title("Covariance Ellipses and PCA Vectors")
ax[-2].set_title("Individual Density, with Contours")
ax[-1].set_title("Overall Density")
save_figure(fig, name="logo_eg_all", save_at=save_at, save_fmts=fmts, dpi=dpi)

save_axes(ax[0], name="logo_eg_points", save_at=save_at, save_fmts=fmts, dpi=dpi)
save_axes(ax[1], name="logo_eg_ellipses", save_at=save_at, save_fmts=fmts, dpi=dpi)
save_axes(ax[2], name="logo_eg_contours", save_at=save_at, save_fmts=fmts, dpi=dpi)
save_axes(ax[3], name="logo_eg_density", save_at=save_at, save_fmts=fmts, dpi=dpi)
plt.tight_layout()
save_figure(fig, name="logo_eg_all", save_at=save_at, save_fmts=fmts, dpi=dpi)

"""
svg = svgutils.transform.fromfile(save_at / "logo_eg_points.svg")
originalSVG = svgutils.compose.SVG(save_at / "logo_eg_points.svg")
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/plotting/spider.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@

# %% Fill Plot -------------------------------------------------------------------------
# This behaviour can be modified (see spider docs) to provide filled ranges:
ax = spider(df.values, fill=True, plot=False, color="k", alpha=0.5)
ax = spider(df.values, mode='fill', color="k", alpha=0.5)
# or, alternatively directly from the dataframe:
ax = df.pyroplot.spider(fill=True, plot=False, color="k", alpha=0.5)
ax = df.pyroplot.spider(mode='fill', color="k", alpha=0.5)
ax.set_ylabel('Abundance')
# %% Save Figure
save_figure(ax.figure, save_at="../../source/_static", name="spider_fill")
Expand Down
Binary file modified docs/source/_static/REE_v_radii_df.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/source/_static/REE_v_radii_dual.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/source/_static/REE_v_radii_fill.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/source/_static/REE_v_radii_minimal.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/source/_static/spider_dual.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/source/_static/spider_fill.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/source/_static/spider_minimal.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/source/_static/spider_modes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/source/_static/spider_norm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 4 additions & 7 deletions docs/source/future.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ planned be integrated over the longer term.

:code:`pyrolite.comp.impute`

Compositional data imputation algorithms (including EMCOMP,
`Issue #6 <https://github.com/morganjwilliams/pyrolite/issues/6>`__)
Expansion of compositional data imputation algorithms beyond EMCOMP
(`Issue #6 <https://github.com/morganjwilliams/pyrolite/issues/6>`__).

:code:`pyrolite.geochem.isotope`

Expand All @@ -56,11 +56,8 @@ planned be integrated over the longer term.

:code:`pyrolite.plot`

A few improvements to plotting functionality are on the horizon:
* Native integration of a ternary projection for :code:`matplotlib`.
* Conditional probability density plot for :code:`scatterplot` like diagrams with a
non-continuous index on the x-axis (
`Issue #10 <https://github.com/morganjwilliams/pyrolite/issues/10>`__)
A few improvements to plotting functionality are on the horizon, including native
integration of a ternary projection for :code:`matplotlib`.

:code:`pyrolite.geochem.magma`

Expand Down
4 changes: 2 additions & 2 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
`Pyrolite`
====================================

.. image:: ./_static/icon.svg
:width: 70%
.. image:: ./_static/icon.png
:width: 40%
:align: right

.. toctree::
Expand Down
3 changes: 2 additions & 1 deletion docs/source/usage/eg/plotting/REE_v_radii.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,5 @@ REE Radii Plots
:align: center

.. seealso:: `Visualising Orthogonal Polynomials <../lambdas/lambdavis.html>`__,
`Dimensional Reduction <../lambdas/lambdadimreduction.html>`__
`Dimensional Reduction <../lambdas/lambdadimreduction.html>`__,
`Spider Density Diagrams <conditionaldensity.html>`__,
16 changes: 16 additions & 0 deletions docs/source/usage/eg/plotting/conditionaldensity.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Conditional Density Spiderplots
==================================

The spiderplot can be extended to provide visualisations of ranges and density via the
various modes:

.. literalinclude:: ../../../../examples/plotting/conditionalspider.py
:language: python
:end-before: # %% save figure

.. image:: ../../../_static/spider_modes.png
:width: 100%
:align: center

.. seealso:: `Density Plots <density.html>`__,
`Spiderplots <spider.html>`__
3 changes: 2 additions & 1 deletion docs/source/usage/eg/plotting/density.rst
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,5 @@ are specified:
where the edges of bins within a ``pcolormesh`` image (used for plotting the
KDE estimate) are over-emphasized, giving a gridded look.

.. seealso:: `Ternary Plots <../plotting/ternary.html>`__
.. seealso:: `Ternary Plots <../plotting/ternary.html>`__,
`Spider Density Diagrams <conditionaldensity.html>`__,
5 changes: 3 additions & 2 deletions docs/source/usage/eg/plotting/spider.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,6 @@ Spider Plots
:align: center

.. seealso:: `Dimensional Reduction <lambdadimreduction.html>`__,
`REE Radii Plot <../plotting/REE_v_radii.html>`__,
`Normalisation <../normalisation/normalisation.html>`__
`REE Radii Plot <REE_v_radii.html>`__,
`Spider Density Diagrams <conditionaldensity.html>`__,
`Normalisation <../normalisation/normalisation.html>`__
11 changes: 5 additions & 6 deletions pyrolite/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import sys
import logging
from ._version import get_versions
from .plot import pyroplot

__version__ = get_versions()["version"]
del get_versions

# http://docs.python-guide.org/en/latest/writing/logging/
logging.getLogger(__name__).addHandler(logging.NullHandler())
logging.captureWarnings(True)

from ._version import get_versions
from .plot import pyroplot # import after logger setup to suppress numpydoc warnings
__version__ = get_versions()["version"]
del get_versions

__all__ = ['plot', 'comp', 'geochem', 'mineral', 'util']
2 changes: 1 addition & 1 deletion pyrolite/comp/codata.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def close(X: np.ndarray, sumf=np.sum):
:class:`numpy.ndarray`
Closed array.
Note
Notes
------
* Does not check for non-positive entries.
"""
Expand Down
2 changes: 1 addition & 1 deletion pyrolite/comp/impute.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def _little_sweep(G, k: int = 0, verify=False):
Little R. J. A. and Rubin D. B. (2014).
Statistical analysis with missing data. 2nd ed., Wiley, Hoboken, N.J.
Note
Notes
------
The sweep operator is defined for symmetric matrices as follows. A p x p
symmetric matrix G is said to be swept on row and column k if it is replaced by
Expand Down
8 changes: 4 additions & 4 deletions pyrolite/geochem/ind.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ def common_elements(cutoff=92, output="string", order=None, as_set=False):
:class:`list` | :class:`set`
List of elements.
Note
-----
Notes
------
Formulae cannot be used as members of a set, and hence sets returned will
instead consist only of strings.
Expand Down Expand Up @@ -130,8 +130,8 @@ def common_oxides(
:class:`list` | :class:`set`
List of oxides.
Note
-----
Notes
------
Formulae cannot be used as members of a set, and hence sets returned will
instead consist only of strings.
Expand Down
2 changes: 0 additions & 2 deletions pyrolite/geochem/norm.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ def scale_multiplier(in_unit, target_unit="ppm"):
"""
Provides the scale difference between to mass units.
Todo: implement different inputs - string, list, pandas series
Parameters
----------
in_unit: current units
Expand Down
15 changes: 9 additions & 6 deletions pyrolite/geochem/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,9 +464,10 @@ def convert_chemistry(input_df, to=[], logdata=False, renorm=False):
# can't deal with more than one component/component speciation
if len(get_fe) > 1:
raise NotImplementedError
get_fe = get_fe[0]
df = recalculate_Fe(df, to=get_fe, renorm=False, logdata=logdata)
logger.info("Reducing {} to {}.".format(c_fe_str, get_fe))
else:
get_fe = get_fe[0]
df = recalculate_Fe(df, to=get_fe, renorm=False, logdata=logdata)
logger.info("Transforming {} to {}.".format(c_fe_str, get_fe))

# Try to get some ratios -----------------------------------------------------------
ratios = [i for i in to if "/" in i and i in get]
Expand All @@ -479,12 +480,14 @@ def convert_chemistry(input_df, to=[], logdata=False, renorm=False):

# Last Minute Checks ---------------------------------------------------------------
remaining = [i for i in to if i not in df.columns]
df_comp_c = [i for i in df.columns if i in c_components]
assert not len(remaining), "Columns not attained: {}".format(", ".join(remaining))
if renorm:
logger.info("Recalculation Done, Renormalising")
return renormalise(df.loc[:, to])
logger.info("Recalculation Done, Renormalising compositional components.")
df.loc[:, df_comp_c] = renormalise(df.loc[:, df_comp_c])
return df.loc[:, to]
else:
logger.info("Recalculation Done.")
logger.info("Recalculation Done. Data not renormalised.")
return df.loc[:, to]


Expand Down
Loading

0 comments on commit 4c7b3ab

Please sign in to comment.