diff --git a/docs/source/_patch/sphinx_gallery_scrapers.py b/docs/source/_patch/sphinx_gallery_scrapers.py index 522c7cd9..883d8e3a 100644 --- a/docs/source/_patch/sphinx_gallery_scrapers.py +++ b/docs/source/_patch/sphinx_gallery_scrapers.py @@ -45,7 +45,7 @@ def alt_matplotlib_scraper(block, block_vars, gallery_conf, **kwargs): save_at=Path(image_path).parent, name=Path(image_path).stem, save_fmts=["png"], - **kwargs.copy() + **kwargs.copy(), ) image_paths.append(image_path) diff --git a/docs/source/conf.py b/docs/source/conf.py index 1d1f055e..3cc4d3ec 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -288,7 +288,7 @@ def reset_mpl(gallery_conf, fname): # "jupyterlite": {"use_jupyter_lab": True}, "first_notebook_cell": "%matplotlib inline\n", "reset_modules": (reset_mpl), - "nested_sections": False + "nested_sections": False, } # Remove matplotlib agg warnings from generated doc when using plt.show warnings.filterwarnings( @@ -345,9 +345,7 @@ def reset_mpl(gallery_conf, fname): Archive -""".format( - rc=refcomps, year=str(date.today().year), version=version -) +""".format(rc=refcomps, year=str(date.today().year), version=version) rst_prolog += """ diff --git a/docs/source/gallery/data/aitchison.py b/docs/source/gallery/data/aitchison.py index 2faaa6e4..03fefa7f 100644 --- a/docs/source/gallery/data/aitchison.py +++ b/docs/source/gallery/data/aitchison.py @@ -11,6 +11,7 @@ (all returning a :class:`~pandas.DataFrame`). """ + from pyrolite.data.Aitchison import load_boxite, load_coxite, load_hongite, load_kongite df = load_boxite() diff --git a/docs/source/gallery/data/radii.py b/docs/source/gallery/data/radii.py index 1ce59f1a..163ca322 100644 --- a/docs/source/gallery/data/radii.py +++ b/docs/source/gallery/data/radii.py @@ -9,6 +9,7 @@ to get radii for individual elements, using a :code:`source` keyword argument to swap between the datasets: """ + import matplotlib.pyplot as plt import pandas as pd diff --git a/docs/source/gallery/data/refcomp.py b/docs/source/gallery/data/refcomp.py index 4732083e..edc8bb9d 100644 --- a/docs/source/gallery/data/refcomp.py +++ b/docs/source/gallery/data/refcomp.py @@ -7,6 +7,7 @@ contain extended descriptions and notes for some of the compositions and associated references. """ + import matplotlib.pyplot as plt from pyrolite.geochem.norm import all_reference_compositions, get_reference_composition diff --git a/docs/source/gallery/data/timescale.py b/docs/source/gallery/data/timescale.py index 0cc0b91a..fb9557d3 100644 --- a/docs/source/gallery/data/timescale.py +++ b/docs/source/gallery/data/timescale.py @@ -8,6 +8,7 @@ specific geological ages, to look up times for known geological age names and to access a reference table for all of these. """ + from pyrolite.util.time import Timescale, age_name ts = Timescale() diff --git a/docs/source/gallery/examples/comp/logratiomeans.py b/docs/source/gallery/examples/comp/logratiomeans.py index 416f001e..346e46c2 100644 --- a/docs/source/gallery/examples/comp/logratiomeans.py +++ b/docs/source/gallery/examples/comp/logratiomeans.py @@ -2,6 +2,7 @@ Log Ratio Means ----------------- """ + import matplotlib.pyplot as plt import numpy as np import pandas as pd diff --git a/docs/source/gallery/examples/comp/sphericalcoords.py b/docs/source/gallery/examples/comp/sphericalcoords.py index 8c24e63c..764ac063 100644 --- a/docs/source/gallery/examples/comp/sphericalcoords.py +++ b/docs/source/gallery/examples/comp/sphericalcoords.py @@ -24,6 +24,7 @@ First let's create some example mineralogical abundance data, where at least one of the minerals might occasionally have zero abundance: """ + import numpy as np from pyrolite.util.synthetic import normal_frame diff --git a/docs/source/gallery/examples/geochem/CIPW.py b/docs/source/gallery/examples/geochem/CIPW.py index b065901f..e8eef278 100644 --- a/docs/source/gallery/examples/geochem/CIPW.py +++ b/docs/source/gallery/examples/geochem/CIPW.py @@ -25,9 +25,10 @@ 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. -We import this file and do a little cleaning and registration of geochemical +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 warnings import matplotlib.pyplot as plt @@ -198,7 +199,6 @@ def compare_NORMs(SINCLAS_outputs, NORM_outputs, name=""): volcanic_filter = df.loc[:, "ROCK_TYPE"].str.lower().str.startswith("volc") fig, ax = compare_NORMs(df.loc[volcanic_filter, :], NORM.loc[volcanic_filter]) - ######################################################################################## # And everything else: # diff --git a/docs/source/gallery/examples/geochem/convert_chemistry.py b/docs/source/gallery/examples/geochem/convert_chemistry.py index a79c685b..b55a41ed 100644 --- a/docs/source/gallery/examples/geochem/convert_chemistry.py +++ b/docs/source/gallery/examples/geochem/convert_chemistry.py @@ -7,6 +7,7 @@ :func:`~pyrolite.geochem.transform.convert_chemistry` function. Note that by default pyrolite assumes that data are in the same units. """ + import pandas as pd import pyrolite.geochem diff --git a/docs/source/gallery/examples/geochem/indexes_selectors.py b/docs/source/gallery/examples/geochem/indexes_selectors.py index 955597e8..8033f479 100644 --- a/docs/source/gallery/examples/geochem/indexes_selectors.py +++ b/docs/source/gallery/examples/geochem/indexes_selectors.py @@ -3,6 +3,7 @@ ================================== """ + import pandas as pd import pyrolite.geochem diff --git a/docs/source/gallery/examples/geochem/ionic_radii.py b/docs/source/gallery/examples/geochem/ionic_radii.py index 6d952ccf..b8b68922 100644 --- a/docs/source/gallery/examples/geochem/ionic_radii.py +++ b/docs/source/gallery/examples/geochem/ionic_radii.py @@ -8,6 +8,7 @@ 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 REE, get_ionic_radii Cu_radii = get_ionic_radii("Cu") diff --git a/docs/source/gallery/examples/geochem/lambdas.py b/docs/source/gallery/examples/geochem/lambdas.py index 2c0409ec..09d1f883 100644 --- a/docs/source/gallery/examples/geochem/lambdas.py +++ b/docs/source/gallery/examples/geochem/lambdas.py @@ -21,6 +21,7 @@ Here we generate some example data, reduce these to lambda values, and visualise the results. """ + import matplotlib.pyplot as plt import numpy as np import pandas as pd diff --git a/docs/source/gallery/examples/geochem/mineral_endmembers.py b/docs/source/gallery/examples/geochem/mineral_endmembers.py index a426c80c..d9205f00 100644 --- a/docs/source/gallery/examples/geochem/mineral_endmembers.py +++ b/docs/source/gallery/examples/geochem/mineral_endmembers.py @@ -7,6 +7,7 @@ pyrolite includes some utilities to achieve this and a limited mineral database for looking up endmember compositions. """ + import numpy as np import pandas as pd diff --git a/docs/source/gallery/examples/geochem/mineral_lattice.py b/docs/source/gallery/examples/geochem/mineral_lattice.py index 0a711a19..7a4d4549 100644 --- a/docs/source/gallery/examples/geochem/mineral_lattice.py +++ b/docs/source/gallery/examples/geochem/mineral_lattice.py @@ -25,6 +25,7 @@ generates plagioclase's hallmark 'europium anomaly', and the effects of variable europium oxidation state on bulk europium partitioning. """ + import matplotlib.pyplot as plt import numpy as np diff --git a/docs/source/gallery/examples/geochem/mineral_mindb.py b/docs/source/gallery/examples/geochem/mineral_mindb.py index 6d749a69..accc1b0f 100644 --- a/docs/source/gallery/examples/geochem/mineral_mindb.py +++ b/docs/source/gallery/examples/geochem/mineral_mindb.py @@ -5,6 +5,7 @@ pyrolite includes a limited mineral database which is useful for looking up endmember compositions. """ + import pandas as pd from pyrolite.mineral.mindb import ( diff --git a/docs/source/gallery/examples/geochem/normalization.py b/docs/source/gallery/examples/geochem/normalization.py index 7836ad87..cbde57b6 100644 --- a/docs/source/gallery/examples/geochem/normalization.py +++ b/docs/source/gallery/examples/geochem/normalization.py @@ -6,6 +6,7 @@ accessed with :func:`pyrolite.geochem.norm.get_reference_composition` (see the list at the bottom of the page for a complete list): """ + import matplotlib.pyplot as plt import pandas as pd diff --git a/docs/source/gallery/examples/geochem/scaling.py b/docs/source/gallery/examples/geochem/scaling.py index d8b5f11b..6a7e5d63 100644 --- a/docs/source/gallery/examples/geochem/scaling.py +++ b/docs/source/gallery/examples/geochem/scaling.py @@ -2,6 +2,7 @@ Unit Scaling ============= """ + import numpy as np import pandas as pd @@ -88,9 +89,9 @@ ) converted_wt_pct.head(2) ######################################################################################## -# Here we rename the columns before we export them, just so we know explicitly +# 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( +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) diff --git a/docs/source/gallery/examples/plotting/REE_v_radii.py b/docs/source/gallery/examples/plotting/REE_v_radii.py index 1ad85481..1cd969ad 100644 --- a/docs/source/gallery/examples/plotting/REE_v_radii.py +++ b/docs/source/gallery/examples/plotting/REE_v_radii.py @@ -2,6 +2,7 @@ REE Radii Plots ============================ """ + import matplotlib.pyplot as plt import numpy as np import pandas as pd diff --git a/docs/source/gallery/examples/plotting/density.py b/docs/source/gallery/examples/plotting/density.py index e92e008f..eb9d0bc3 100644 --- a/docs/source/gallery/examples/plotting/density.py +++ b/docs/source/gallery/examples/plotting/density.py @@ -9,6 +9,7 @@ and evaluation over a grid. The below examples highlight some of the currently implemented features. """ + import matplotlib.pyplot as plt import numpy as np import pandas as pd diff --git a/docs/source/gallery/examples/plotting/heatscatter.py b/docs/source/gallery/examples/plotting/heatscatter.py index c154281a..7ba300cd 100644 --- a/docs/source/gallery/examples/plotting/heatscatter.py +++ b/docs/source/gallery/examples/plotting/heatscatter.py @@ -10,6 +10,7 @@ represents the best of both worlds. A version inspired by similar existing visualisations is implemented with :func:`~pyrolite.plot.pyroplot.heatscatter`. """ + import matplotlib.pyplot as plt import numpy as np import pandas as pd diff --git a/docs/source/gallery/examples/plotting/parallel.py b/docs/source/gallery/examples/plotting/parallel.py index df6ed839..e06011b7 100644 --- a/docs/source/gallery/examples/plotting/parallel.py +++ b/docs/source/gallery/examples/plotting/parallel.py @@ -6,6 +6,7 @@ higher dimensional data. pyrolite now includes an implementation of this which allows a handy quick exploratory visualisation. """ + import matplotlib.axes import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable @@ -44,18 +45,18 @@ compdata[comp] = CLRTransform().transform(compdata[comp]) ax = compdata.loc[:, comp].pyroplot.parallel(color=compdata.Depth.values, cmap=cmap) divider = make_axes_locatable(ax) -cax = divider.append_axes('right', size='5%', pad=0.05) +cax = divider.append_axes("right", size="5%", pad=0.05) # 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, cax=cax, orientation='vertical') +plt.colorbar(sm, cax=cax, orientation="vertical") plt.show() ######################################################################################## ax = compdata.loc[:, comp].pyroplot.parallel( rescale=True, color=compdata.Depth.values, cmap=cmap ) divider = make_axes_locatable(ax) -cax = divider.append_axes('right', size='5%', pad=0.05) -plt.colorbar(sm, cax=cax, orientation='vertical') +cax = divider.append_axes("right", size="5%", pad=0.05) +plt.colorbar(sm, cax=cax, orientation="vertical") plt.show() diff --git a/docs/source/gallery/examples/plotting/spider.py b/docs/source/gallery/examples/plotting/spider.py index 180c9faf..aa55f509 100644 --- a/docs/source/gallery/examples/plotting/spider.py +++ b/docs/source/gallery/examples/plotting/spider.py @@ -2,6 +2,7 @@ Spiderplots & Density Spiderplots ================================== """ + import matplotlib.pyplot as plt import numpy as np import pandas as pd @@ -265,7 +266,7 @@ unity_line=True, index_order="incompatibility", *args, - **kwargs + **kwargs, ) plt.tight_layout() diff --git a/docs/source/gallery/examples/plotting/stem.py b/docs/source/gallery/examples/plotting/stem.py index 9c9d1278..b23d82fe 100644 --- a/docs/source/gallery/examples/plotting/stem.py +++ b/docs/source/gallery/examples/plotting/stem.py @@ -8,6 +8,7 @@ so (such that the sampling frequency along this axis is important, which is not emphasised by a scatter plot). """ + import matplotlib.pyplot as plt import numpy as np import pandas as pd diff --git a/docs/source/gallery/examples/plotting/templates.py b/docs/source/gallery/examples/plotting/templates.py index 16df9281..b29acd60 100644 --- a/docs/source/gallery/examples/plotting/templates.py +++ b/docs/source/gallery/examples/plotting/templates.py @@ -6,6 +6,7 @@ be used to create new plots, or add a template to an existing :class:`matplotlib.axes.Axes`. """ + import matplotlib.pyplot as plt ######################################################################################## diff --git a/docs/source/gallery/examples/plotting/ternary.py b/docs/source/gallery/examples/plotting/ternary.py index 409cbf05..99d9d10b 100644 --- a/docs/source/gallery/examples/plotting/ternary.py +++ b/docs/source/gallery/examples/plotting/ternary.py @@ -2,6 +2,7 @@ Ternary Plots ============= """ + import matplotlib.pyplot as plt import numpy as np import pandas as pd diff --git a/docs/source/gallery/examples/plotting/ternary_color.py b/docs/source/gallery/examples/plotting/ternary_color.py index af1611c7..aaae15eb 100644 --- a/docs/source/gallery/examples/plotting/ternary_color.py +++ b/docs/source/gallery/examples/plotting/ternary_color.py @@ -8,6 +8,7 @@ well with some of the plot templates (:mod:`pyrolite.plot.templates`) and associated classifiers (:mod:`pyrolite.util.classification`). """ + import numpy as np import matplotlib.pyplot as plt diff --git a/docs/source/gallery/examples/util/TAS.py b/docs/source/gallery/examples/util/TAS.py index ba8469b5..3d11d136 100644 --- a/docs/source/gallery/examples/util/TAS.py +++ b/docs/source/gallery/examples/util/TAS.py @@ -5,6 +5,7 @@ Some simple discrimination methods are implemented, including the Total Alkali-Silica (TAS) classification. """ + import matplotlib.pyplot as plt import numpy as np import pandas as pd @@ -54,10 +55,20 @@ fig, ax = plt.subplots(1) -cm.add_to_axes(ax, alpha=0.5, linewidth=0.0, zorder=-2, add_labels=False, - which_ids=np.unique(df["TAS"]), fill=True, facecolor=[0.9, 0.8, 1.0]) +cm.add_to_axes( + ax, + alpha=0.5, + linewidth=0.0, + zorder=-2, + add_labels=False, + which_ids=np.unique(df["TAS"]), + fill=True, + facecolor=[0.9, 0.8, 1.0], +) cm.add_to_axes(ax, alpha=0.5, linewidth=0.5, zorder=-1, add_labels=True) -df[["SiO2", "Na2O + K2O"]].pyroplot.scatter(ax=ax, c=df["TAS"], alpha=0.7, axlabels=False) +df[["SiO2", "Na2O + K2O"]].pyroplot.scatter( + ax=ax, c=df["TAS"], alpha=0.7, axlabels=False +) ######################################################################################## # Variations of the Diagram diff --git a/docs/source/gallery/examples/util/manifold_vis.py b/docs/source/gallery/examples/util/manifold_vis.py index 4bbca090..cc1e5992 100644 --- a/docs/source/gallery/examples/util/manifold_vis.py +++ b/docs/source/gallery/examples/util/manifold_vis.py @@ -8,6 +8,7 @@ predictions and relative prediction certainty (using entropy across predicted probability for each individual class) for a toy :mod:`sklearn` dataset. """ + import matplotlib.pyplot as plt import numpy as np import sklearn.datasets diff --git a/docs/source/gallery/examples/util/timescale.py b/docs/source/gallery/examples/util/timescale.py index d76a84f4..afabba2d 100644 --- a/docs/source/gallery/examples/util/timescale.py +++ b/docs/source/gallery/examples/util/timescale.py @@ -12,6 +12,7 @@ `The ICS International Chronostratigraphic Chart `__. Episodes 36, 199–204. """ + ######################################################################################## # First we'll create a timescale: # diff --git a/docs/source/gallery/tutorials/logo.py b/docs/source/gallery/tutorials/logo.py index eeb1c093..d49e747d 100644 --- a/docs/source/gallery/tutorials/logo.py +++ b/docs/source/gallery/tutorials/logo.py @@ -2,6 +2,7 @@ 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 diff --git a/docs/source/gallery/tutorials/plot_formatting.py b/docs/source/gallery/tutorials/plot_formatting.py index 1348e70c..09b93192 100644 --- a/docs/source/gallery/tutorials/plot_formatting.py +++ b/docs/source/gallery/tutorials/plot_formatting.py @@ -10,6 +10,7 @@ (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: # @@ -209,6 +210,11 @@ ax = df[["CaO", "MgO", "Al2O3"]].pyroplot.scatter() ax.set_ternary_lim( - 0.1, 0.5, 0.2, 0.6, 0.3, 0.7 # tmin # tmax # lmin # lmax # rmin # rmax + 0.1, + 0.5, + 0.2, + 0.6, + 0.3, + 0.7, # tmin # tmax # lmin # lmax # rmin # rmax ) plt.show() diff --git a/docs/source/gallery/tutorials/templates.py b/docs/source/gallery/tutorials/templates.py index c3f41608..7e2bc9df 100644 --- a/docs/source/gallery/tutorials/templates.py +++ b/docs/source/gallery/tutorials/templates.py @@ -7,6 +7,7 @@ * Add plot.templates file """ + ####################################################################################### # First let's pull in a simple dataset to use throughout these examples: # diff --git a/docs/source/gallery/tutorials/ternary_density.py b/docs/source/gallery/tutorials/ternary_density.py index c78db901..fa8b1288 100644 --- a/docs/source/gallery/tutorials/ternary_density.py +++ b/docs/source/gallery/tutorials/ternary_density.py @@ -10,6 +10,7 @@ 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: diff --git a/pyrolite/__init__.py b/pyrolite/__init__.py index 679b354c..7368ee1e 100644 --- a/pyrolite/__init__.py +++ b/pyrolite/__init__.py @@ -47,5 +47,6 @@ def load_extensions(base="pyrolite_", replace=["util"]): n = n.replace(r, "") setattr(extensions, n, m) + # _export_pyrolite_mplstyle() should be called in .plot import regardless matplotlib.style.use("pyrolite") diff --git a/pyrolite/_version.py b/pyrolite/_version.py index 1131671c..7bb1f37b 100644 --- a/pyrolite/_version.py +++ b/pyrolite/_version.py @@ -1,4 +1,3 @@ - # 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 @@ -68,12 +67,14 @@ class NotThisMethod(Exception): 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 @@ -100,10 +101,14 @@ def run_command( try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) + process = subprocess.Popen( + [command] + args, + cwd=cwd, + env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr else None), + **popen_kwargs, + ) break except OSError as e: if e.errno == errno.ENOENT: @@ -141,15 +146,21 @@ def versions_from_parentdir( 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} + 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") @@ -212,7 +223,7 @@ def git_versions_from_keywords( # 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 = {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 @@ -221,7 +232,7 @@ def git_versions_from_keywords( # 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 = {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: @@ -229,32 +240,36 @@ def git_versions_from_keywords( 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): + 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: str, - root: str, - verbose: bool, - runner: Callable = run_command + 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. @@ -273,8 +288,7 @@ def git_pieces_from_vcs( env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) + _, 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) @@ -282,10 +296,19 @@ def git_pieces_from_vcs( # 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 = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], 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") @@ -300,8 +323,7 @@ def git_pieces_from_vcs( pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) + 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") @@ -341,17 +363,16 @@ def git_pieces_from_vcs( 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: # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -360,10 +381,12 @@ def git_pieces_from_vcs( 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)) @@ -412,8 +435,7 @@ def render_pep440(pieces: Dict[str, Any]) -> str: 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 @@ -442,8 +464,7 @@ def render_pep440_branch(pieces: Dict[str, Any]) -> str: rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -604,11 +625,13 @@ def render_git_describe_long(pieces: Dict[str, Any]) -> str: 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 @@ -632,9 +655,13 @@ def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: 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() -> Dict[str, Any]: @@ -648,8 +675,7 @@ def get_versions() -> Dict[str, Any]: 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 @@ -658,13 +684,16 @@ def get_versions() -> Dict[str, Any]: # 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 _ 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) @@ -678,6 +707,10 @@ def get_versions() -> Dict[str, Any]: 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/__init__.py b/pyrolite/comp/__init__.py index 907cf50b..6f1fd40a 100644 --- a/pyrolite/comp/__init__.py +++ b/pyrolite/comp/__init__.py @@ -188,9 +188,9 @@ def CLR(self, label_mode="simple"): index=self._obj.index, columns=colnames, ) - tfm_df.attrs[ - "inverts_to" - ] = self._obj.columns.to_list() # save parameter for inverse_transform + tfm_df.attrs["inverts_to"] = ( + self._obj.columns.to_list() + ) # save parameter for inverse_transform return tfm_df def inverse_CLR(self): @@ -241,9 +241,9 @@ def ILR(self, label_mode="simple"): index=self._obj.index, columns=colnames, ) - tfm_df.attrs[ - "inverts_to" - ] = self._obj.columns.to_list() # save parameter for inverse_transform + tfm_df.attrs["inverts_to"] = ( + self._obj.columns.to_list() + ) # save parameter for inverse_transform return tfm_df def inverse_ILR(self, X=None): diff --git a/pyrolite/comp/impute.py b/pyrolite/comp/impute.py index 591e6216..ba55e7c4 100644 --- a/pyrolite/comp/impute.py +++ b/pyrolite/comp/impute.py @@ -285,7 +285,7 @@ def EMCOMP( ) Ystar[np.ix_(rows, varmiss)] = np.ones((rows.size, 1)) * B[0, :] + ( - (Y[np.ix_(rows, varobs)] @ B[1 : (varobs.size + 1), :]) + Y[np.ix_(rows, varobs)] @ B[1 : (varobs.size + 1), :] ) sigmas[varmiss] = np.sqrt(np.diag(σ2_res)) assert np.isfinite(sigmas[varmiss]).all() diff --git a/pyrolite/data/Aitchison/__init__.py b/pyrolite/data/Aitchison/__init__.py index 398f8293..b512b0d6 100644 --- a/pyrolite/data/Aitchison/__init__.py +++ b/pyrolite/data/Aitchison/__init__.py @@ -9,6 +9,7 @@ Journal of the International Association for Mathematical Geology 16, 531–564. doi: {aitchison1984} """ + import logging import pandas as pd diff --git a/pyrolite/extensions/__init__.py b/pyrolite/extensions/__init__.py index de4b7e15..9f97ebdf 100644 --- a/pyrolite/extensions/__init__.py +++ b/pyrolite/extensions/__init__.py @@ -2,6 +2,7 @@ A stub module to house pyrolite extensions, where they are installed. """ + from ..util.log import Handle logger = Handle(__name__) diff --git a/pyrolite/geochem/isotope/__init__.py b/pyrolite/geochem/isotope/__init__.py index a3aed75e..d4b04041 100644 --- a/pyrolite/geochem/isotope/__init__.py +++ b/pyrolite/geochem/isotope/__init__.py @@ -42,6 +42,7 @@ Associated Equipment 301, 543–551. doi: {muller1991} """ + from ...util.meta import sphinx_doi_link __doc__ = __doc__.format( diff --git a/pyrolite/geochem/magma.py b/pyrolite/geochem/magma.py index 52f3588c..19afdb32 100644 --- a/pyrolite/geochem/magma.py +++ b/pyrolite/geochem/magma.py @@ -2,6 +2,7 @@ Submodule for calculating and modelling melt chemistry. Includes common functions for predicting and accounting for melt evolution. """ + import numpy as np import periodictable as pt diff --git a/pyrolite/geochem/parse.py b/pyrolite/geochem/parse.py index 26eccffc..decb180f 100644 --- a/pyrolite/geochem/parse.py +++ b/pyrolite/geochem/parse.py @@ -1,6 +1,7 @@ """ Functions for parsing, formatting and validating chemical names and formulae. """ + import re import pandas as pd @@ -126,14 +127,19 @@ def tochem(strings: list, abbrv=["ID", "IGSN"], split_on=r"[\s_]+"): # translate elements and oxides # elements second, Co guaranteed to override CO for python 3.6 + - + chems = _common_oxides | _common_elements trans = {str(e).upper(): str(e) for e in chems} strings = [trans[str(h).upper()] if str(h).upper() in trans else h for h in strings] # translate potential isotope ratios split_pattern = re.compile(split_on) - strings = [h if (h in chems) else (repr_isotope_ratio(h) if split_pattern.match(h) is not None else h) for h in strings] + strings = [ + h + if (h in chems) + else (repr_isotope_ratio(h) if split_pattern.match(h) is not None else h) + for h in strings + ] if listified: strings = strings[0] return strings diff --git a/pyrolite/geochem/quality/__init__.py b/pyrolite/geochem/quality/__init__.py index 8e5df7d5..8c661e9c 100644 --- a/pyrolite/geochem/quality/__init__.py +++ b/pyrolite/geochem/quality/__init__.py @@ -23,6 +23,7 @@ offset from a zero-offset to 0+n, 0+2n, 0+3n.. etc peaks with decreasing magnitude (which occur at lower value) """ + from ...util.log import Handle logger = Handle(__name__) diff --git a/pyrolite/geochem/transform.py b/pyrolite/geochem/transform.py index 0443556f..f58b55db 100644 --- a/pyrolite/geochem/transform.py +++ b/pyrolite/geochem/transform.py @@ -749,7 +749,7 @@ def convert_chemistry( **kwargs, ) - # TODO: warning for duplication should also be crossed over into speciated components above.. + # TODO: warning for duplication should also be crossed over into speciated components above.. _duplicated_cations = [ str(k) for k, v in Counter( # get the first cation in each component, and count duplicates @@ -758,7 +758,11 @@ def convert_chemistry( if v > 1 ] if _duplicated_cations: - logger.warning("Cations duplicated in compositional components: {}. The output retains this duplication!".format(','.join(_duplicated_cations))) + logger.warning( + "Cations duplicated in compositional components: {}. The output retains this duplication!".format( + ",".join(_duplicated_cations) + ) + ) # Aggregate the singular compositional items, then get new columns for item in output_compositional: df = aggregate_element(df, to=item, logdata=logdata, molecular=molecular) diff --git a/pyrolite/mineral/__init__.py b/pyrolite/mineral/__init__.py index e7e39eab..3650375e 100644 --- a/pyrolite/mineral/__init__.py +++ b/pyrolite/mineral/__init__.py @@ -1,6 +1,7 @@ """ A submodule for working with mineral data. """ + from ..util.log import Handle logger = Handle(__name__) diff --git a/pyrolite/plot/biplot.py b/pyrolite/plot/biplot.py index 97111c16..0e49a22f 100644 --- a/pyrolite/plot/biplot.py +++ b/pyrolite/plot/biplot.py @@ -37,7 +37,7 @@ def plot_origin_to_points( color="k", marker="o", pad=0.05, - **kwargs + **kwargs, ): """ Plot lines radiating from a specific origin. Fornulated for creation of diff --git a/pyrolite/plot/density/ternary.py b/pyrolite/plot/density/ternary.py index 200022c1..e69ecbd8 100644 --- a/pyrolite/plot/density/ternary.py +++ b/pyrolite/plot/density/ternary.py @@ -20,7 +20,7 @@ def ternary_heatmap( ternary_min_value=0.0001, # 0.01% grid_border_frac=0.1, # 110% range for grid grid=None, - **kwargs + **kwargs, ): """ Heatmap for ternary diagrams. This invokes a 3D to 2D transform such as a diff --git a/pyrolite/plot/spider.py b/pyrolite/plot/spider.py index a55c1443..ef483438 100644 --- a/pyrolite/plot/spider.py +++ b/pyrolite/plot/spider.py @@ -43,7 +43,7 @@ def spider( line_kw={}, set_ticks=True, autoscale=True, - **kwargs + **kwargs, ): """ Plots spidergrams for trace elements data. Additional arguments are typically forwarded @@ -209,7 +209,10 @@ def spider( ) # do these need to be ravelled? ax.scatter( - indexes.ravel(), arr.ravel(), color=scattercolor, **{"zorder": 2, **s_kw} + indexes.ravel(), + arr.ravel(), + color=scattercolor, + **{"zorder": 2, **s_kw}, ) # should create a custom legend handle here @@ -227,7 +230,7 @@ def spider( yextent=yextent, mode=mode, ret_centres=True, - **kwargs + **kwargs, ) # can have issues with nans here? vmin = kwargs.pop("vmin", 0) @@ -290,7 +293,7 @@ def REE_v_radii( line_kw={}, set_labels=True, set_ticks=True, - **kwargs + **kwargs, ): r""" Creates an axis for a REE diagram with ionic radii along the x axis. @@ -374,7 +377,7 @@ def REE_v_radii( indexes=indexes, scatter_kw=scatter_kw, line_kw=line_kw, - **kwargs + **kwargs, ) twinys = get_twins(ax, which="y") diff --git a/pyrolite/plot/templates/TAS.py b/pyrolite/plot/templates/TAS.py index 942bb6dd..fba76a77 100644 --- a/pyrolite/plot/templates/TAS.py +++ b/pyrolite/plot/templates/TAS.py @@ -16,7 +16,7 @@ def TAS( relim=True, color="k", which_model=None, - **kwargs + **kwargs, ): """ Adds the TAS diagram to an axes. Diagram from Middlemost (1994) [#ref_1]_, diff --git a/pyrolite/plot/templates/components.py b/pyrolite/plot/templates/components.py index 0a918627..f162e2ad 100644 --- a/pyrolite/plot/templates/components.py +++ b/pyrolite/plot/templates/components.py @@ -86,7 +86,7 @@ def add_to_axes(self, ax, label=False, **kwargs): self.x, self.y, label=[None, self.name][label], - **{**self.kwargs, **subkwargs(kwargs, ax.scatter, PathCollection)} + **{**self.kwargs, **subkwargs(kwargs, ax.scatter, PathCollection)}, ) @@ -105,7 +105,7 @@ def __init__( name=None, xlim=None, ylim=None, - **kwargs + **kwargs, ): r""" Simple container for a 2D line object with basic utility functions. @@ -300,7 +300,7 @@ def add_to_axes(self, ax, xs=None, label=False, **kwargs): linexs, lineys, label=[None, self.name][label], - **{**self.kwargs, **subkwargs(kwargs, ax.plot, Line2D)} + **{**self.kwargs, **subkwargs(kwargs, ax.plot, Line2D)}, ) def __add__(self, obj): diff --git a/pyrolite/plot/templates/feldspar.py b/pyrolite/plot/templates/feldspar.py index 6c8811a7..231c4ad6 100644 --- a/pyrolite/plot/templates/feldspar.py +++ b/pyrolite/plot/templates/feldspar.py @@ -13,7 +13,7 @@ def FeldsparTernary( which_labels="ID", mode="miscibility-gap", color="k", - **kwargs + **kwargs, ): """ Simplified feldspar classifcation diagram, based on a version printed in the diff --git a/pyrolite/util/classification.py b/pyrolite/util/classification.py index 58328ee9..782c3012 100644 --- a/pyrolite/util/classification.py +++ b/pyrolite/util/classification.py @@ -8,6 +8,7 @@ gabbroic Pyroxene-Olivine-Plagioclase, ultramafic Olivine-Orthopyroxene-Clinopyroxene """ + import json import matplotlib.lines @@ -79,7 +80,7 @@ def __init__( scale=1.0, transform=None, mode=None, - **kwargs + **kwargs, ): self.default_scale = scale self._scale = self.default_scale @@ -195,7 +196,7 @@ def _add_polygons_to_axes( add_labels=False, which_labels="ID", which_ids=[], - **kwargs + **kwargs, ): """ Add the polygonal fields from the classifier to an axis. @@ -294,7 +295,7 @@ def add_to_axes( add_labels=False, which_labels="ID", which_ids=[], - **kwargs + **kwargs, ): """ Add the fields from the classifier to an axis. @@ -408,7 +409,7 @@ def add_to_axes( which_labels="ID", which_ids=[], label_at_centroid=True, - **kwargs + **kwargs, ): """ Add the TAS fields from the classifier to an axis. @@ -442,8 +443,12 @@ def add_to_axes( # here we don't want to add the labels in the normal way, because there # are two sets - one for volcanic rocks and one for plutonic rocks ax = self._add_polygons_to_axes( - ax=ax, fill=fill, axes_scale=axes_scale, add_labels=False, - which_ids=which_ids, **kwargs + ax=ax, + fill=fill, + axes_scale=axes_scale, + add_labels=False, + which_ids=which_ids, + **kwargs, ) if not label_at_centroid: @@ -454,8 +459,8 @@ def add_to_axes( # so we want to promote the labels # being placed at the widest part of the field. scale_factor = 1.5 - p = ax.transData.transform([[0., 0.], [1., 1.]]) - yx_scaling = (p[1][1] - p[0][1])/(p[1][0] - p[0][0])*scale_factor + p = ax.transData.transform([[0.0, 0.0], [1.0, 1.0]]) + yx_scaling = (p[1][1] - p[0][1]) / (p[1][0] - p[0][0]) * scale_factor rescale_by = 1.0 if axes_scale is not None: # rescale polygons to fit ax diff --git a/pyrolite/util/database.py b/pyrolite/util/database.py index d0138588..391e95e3 100644 --- a/pyrolite/util/database.py +++ b/pyrolite/util/database.py @@ -21,6 +21,7 @@ try: import pyodbc from pyodbc import DatabaseError, OperationalError, ProgrammingError + __backend__ = pyodbc except: pass diff --git a/pyrolite/util/lambdas/__init__.py b/pyrolite/util/lambdas/__init__.py index d25a4c53..3d074455 100644 --- a/pyrolite/util/lambdas/__init__.py +++ b/pyrolite/util/lambdas/__init__.py @@ -26,7 +26,7 @@ def calc_lambdas( sigmas=None, add_uncertainties=False, add_X2=False, - **kwargs + **kwargs, ): """ Parameterises values based on linear combination of orthogonal polynomials @@ -120,7 +120,7 @@ def calc_lambdas( add_uncertainties=add_uncertainties, add_X2=add_X2, sigmas=sigmas, - **kwargs + **kwargs, ) else: logger.debug("Using optimization algorithm.") @@ -132,7 +132,7 @@ def calc_lambdas( add_uncertainties=add_uncertainties, add_X2=add_X2, sigmas=sigmas, - **kwargs + **kwargs, ) if anomalies: logger.debug("Calculating anomalies.") @@ -142,7 +142,7 @@ def calc_lambdas( get_ionic_radii(ree, charge=3, coordination=8), params=params, fit_tetrads=fit_tetrads, - **kwargs + **kwargs, ) npars = ls.columns.size - int(add_X2) # exclude chi_squared if included npars -= int(add_uncertainties) * npars // 2 # remove parameter uncertainties diff --git a/pyrolite/util/lambdas/eval.py b/pyrolite/util/lambdas/eval.py index 986176d4..35063dca 100644 --- a/pyrolite/util/lambdas/eval.py +++ b/pyrolite/util/lambdas/eval.py @@ -2,6 +2,7 @@ Generation and evalutation of orthogonal polynomial and tetrad functions from sets of parameters (the sequence of polymomial roots and tetrad centres and widths). """ + import numpy as np from ..log import Handle diff --git a/pyrolite/util/lambdas/params.py b/pyrolite/util/lambdas/params.py index 4139e3ef..d1cc3223 100644 --- a/pyrolite/util/lambdas/params.py +++ b/pyrolite/util/lambdas/params.py @@ -2,6 +2,7 @@ Functions to generate parameters for the construction of orthogonal polynomials which are used to fit REE patterns. """ + import numpy as np import sympy.solvers.solvers from sympy import symbols, var diff --git a/pyrolite/util/lambdas/plot.py b/pyrolite/util/lambdas/plot.py index 9b874508..30eeef62 100644 --- a/pyrolite/util/lambdas/plot.py +++ b/pyrolite/util/lambdas/plot.py @@ -3,6 +3,7 @@ profiles based on parameterisations using 'lambdas' (and tetrad-equivalent weights 'taus'). """ + import numpy as np from ... import plot @@ -127,7 +128,7 @@ def plot_profiles( ax=None, index="radii", logy=False, - **kwargs + **kwargs, ): r""" Plot the reconstructed REE profiles of a 2D dataset of coefficients ($\lambda$s, @@ -206,7 +207,7 @@ def plot_profiles( indexes=linex, logy=logy, set_ticks=False, - **{**kwargs, "marker": ""} + **{**kwargs, "marker": ""}, ) return ax diff --git a/pyrolite/util/lambdas/transform.py b/pyrolite/util/lambdas/transform.py index 490b7063..040faa31 100644 --- a/pyrolite/util/lambdas/transform.py +++ b/pyrolite/util/lambdas/transform.py @@ -2,6 +2,7 @@ Functions for transforming ionic radii to and from atomic number for the visualisation of REE patterns. """ + import numpy as np from ...geochem.ind import REE, get_ionic_radii diff --git a/pyrolite/util/log.py b/pyrolite/util/log.py index b1aa4495..cd4197fb 100644 --- a/pyrolite/util/log.py +++ b/pyrolite/util/log.py @@ -69,7 +69,7 @@ class ToLogger(io.StringIO): def __init__(self, logger, level=None): super(ToLogger, self).__init__() self.logger = logger - if isinstance(level,str): + if isinstance(level, str): level = getattr(logging, level.upper()) self.level = level or logging.INFO diff --git a/pyrolite/util/math.py b/pyrolite/util/math.py index cd104192..99683ba9 100644 --- a/pyrolite/util/math.py +++ b/pyrolite/util/math.py @@ -424,8 +424,10 @@ def signify_digit(n, unc=None, leeway=0, low_filter=True): if round_to <= 0: fmt = int else: + def fmt(x): return x + sig_n = round(n, round_to) if low_filter and sig_n == 0.0: return np.nan diff --git a/pyrolite/util/plot/__init__.py b/pyrolite/util/plot/__init__.py index 9d90c6d8..bfe2cdba 100644 --- a/pyrolite/util/plot/__init__.py +++ b/pyrolite/util/plot/__init__.py @@ -11,6 +11,7 @@ Option to use the :func:`matplotlib.pyplot.pcolor` function in place of :func:`matplotlib.pyplot.pcolormesh`. """ + from ..log import Handle logger = Handle(__name__) diff --git a/pyrolite/util/plot/axes.py b/pyrolite/util/plot/axes.py index f487c57d..629d3187 100644 --- a/pyrolite/util/plot/axes.py +++ b/pyrolite/util/plot/axes.py @@ -1,6 +1,7 @@ """ Functions for creating, ordering and modifying :class:`~matplolib.axes.Axes`. """ + import warnings import matplotlib.pyplot as plt @@ -197,7 +198,7 @@ def init_axes(ax=None, projection=None, minsize=1.0, **kwargs): fig, ax = plt.subplots( 1, subplot_kw=dict(projection=projection), - **subkwargs(kwargs, plt.subplots, plt.figure) + **subkwargs(kwargs, plt.subplots, plt.figure), ) else: # axes passed if ax.name != "ternary": diff --git a/pyrolite/util/plot/center.py b/pyrolite/util/plot/center.py index 49fabb16..32b13e05 100644 --- a/pyrolite/util/plot/center.py +++ b/pyrolite/util/plot/center.py @@ -3,6 +3,7 @@ Taken from https://github.com/Twista/python-polylabel, Originally released under an MIT licence. """ + from math import sqrt, inf import time from queue import PriorityQueue @@ -15,9 +16,9 @@ def _point_to_polygon_distance(x, y, polygon): for ring in polygon: b = ring[-1] for a in ring: - - if ((a[1] > y) != (b[1] > y) and - (x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0])): + if (a[1] > y) != (b[1] > y) and ( + x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0] + ): inside = not inside min_dist_sq = min(min_dist_sq, _get_seg_dist_sq(x, y, a, b)) @@ -149,8 +150,11 @@ def visual_center(polygon, precision=1.0, debug=False, with_distance=False): best_cell = cell if debug: - print('found best {} after {} probes'.format( - round(1e4 * cell.d) / 1e4, num_of_probes)) + print( + "found best {} after {} probes".format( + round(1e4 * cell.d) / 1e4, num_of_probes + ) + ) if cell.max - best_cell.d <= precision: continue @@ -167,9 +171,9 @@ def visual_center(polygon, precision=1.0, debug=False, with_distance=False): num_of_probes += 4 if debug: - print('num probes: {}'.format(num_of_probes)) - print('best distance: {}'.format(best_cell.d)) + print("num probes: {}".format(num_of_probes)) + print("best distance: {}".format(best_cell.d)) if with_distance: return [best_cell.x, best_cell.y], best_cell.d else: - return [best_cell.x, best_cell.y] \ No newline at end of file + return [best_cell.x, best_cell.y] diff --git a/pyrolite/util/plot/density.py b/pyrolite/util/plot/density.py index c85e9c19..2c67d312 100644 --- a/pyrolite/util/plot/density.py +++ b/pyrolite/util/plot/density.py @@ -7,6 +7,7 @@ Option to use the :func:`matplotlib.pyplot.pcolor` function in place of :func:`matplotlib.pyplot.pcolormesh`. """ + import matplotlib.pyplot as plt import numpy as np import scipy.interpolate @@ -121,7 +122,7 @@ def plot_Z_percentiles( linestyles=None, contour_labels=None, label_contours=True, - **kwargs + **kwargs, ): """ Plot percentile contours onto a 2D (scaled or unscaled) probability density @@ -204,7 +205,7 @@ def plot_Z_percentiles( zi, levels=contour_values[ordering], # must increase cmap=cmap, - **{**cntr_config, **kwargs} + **{**cntr_config, **kwargs}, ) if label_contours: fs = kwargs.pop("fontsize", None) or 8 @@ -239,7 +240,7 @@ def conditional_prob_density( rescale=True, mode="binkde", ret_centres=False, - **kwargs + **kwargs, ): """ Estimate the conditional probability density of one dependent variable. diff --git a/pyrolite/util/plot/grid.py b/pyrolite/util/plot/grid.py index e6eaf9b3..62b6484d 100644 --- a/pyrolite/util/plot/grid.py +++ b/pyrolite/util/plot/grid.py @@ -1,6 +1,7 @@ """ Gridding and binning functions. """ + import numpy as np import scipy.interpolate diff --git a/pyrolite/util/plot/helpers.py b/pyrolite/util/plot/helpers.py index 2ef595e1..65929e3a 100644 --- a/pyrolite/util/plot/helpers.py +++ b/pyrolite/util/plot/helpers.py @@ -1,6 +1,7 @@ """ matplotlib helper functions for commong drawing tasks. """ + import matplotlib.patches import matplotlib.pyplot as plt import numpy as np @@ -90,7 +91,7 @@ def get_visual_center(poly, vertical_exaggeration=1): vertical_exaggeration : :class:`float` Apparent vertical exaggeration of the plot - (pixels per unit in y direction divided by pixels + (pixels per unit in y direction divided by pixels per unit in the x direction). Returns @@ -98,9 +99,9 @@ def get_visual_center(poly, vertical_exaggeration=1): cx, cy : :class:`tuple` Centroid coordinates. """ - poly_scaled = np.array([poly.get_xy() * [1., vertical_exaggeration]]) + poly_scaled = np.array([poly.get_xy() * [1.0, vertical_exaggeration]]) x, y = visual_center(poly_scaled) - return tuple([x, y/vertical_exaggeration]) + return tuple([x, y / vertical_exaggeration]) def rect_from_centre(x, y, dx=0, dy=0, **kwargs): @@ -220,7 +221,7 @@ def plot_pca_vectors( ax=None, colors=None, linestyles=None, - **kwargs + **kwargs, ): """ Plot vectors corresponding to principal components and their magnitudes. diff --git a/pyrolite/util/plot/legend.py b/pyrolite/util/plot/legend.py index 46caf606..5b0105c5 100644 --- a/pyrolite/util/plot/legend.py +++ b/pyrolite/util/plot/legend.py @@ -8,6 +8,7 @@ ax.lines + ax.patches + ax.collections + ax.containers, handle ax.parasites """ + from copy import copy import matplotlib.lines diff --git a/pyrolite/util/plot/style.py b/pyrolite/util/plot/style.py index 5aa1cc02..5cd896fe 100644 --- a/pyrolite/util/plot/style.py +++ b/pyrolite/util/plot/style.py @@ -8,6 +8,7 @@ DEFAULT_DISC_COLORMAP : :class:`matplotlib.colors.ScalarMappable` Default discrete colormap. """ + import itertools from pathlib import Path diff --git a/pyrolite/util/plot/transform.py b/pyrolite/util/plot/transform.py index 2fb7b55c..4d0f770a 100644 --- a/pyrolite/util/plot/transform.py +++ b/pyrolite/util/plot/transform.py @@ -1,6 +1,7 @@ """ Transformation utilites for matplotlib. """ + import numpy as np from ...comp.codata import close diff --git a/pyrolite/util/resampling.py b/pyrolite/util/resampling.py index 8074b7b4..4107e8a9 100644 --- a/pyrolite/util/resampling.py +++ b/pyrolite/util/resampling.py @@ -1,6 +1,7 @@ """ Utilities for (weighted) bootstrap resampling applied to geoscientific point-data. """ + import numpy as np import pandas as pd @@ -85,7 +86,7 @@ def get_spatiotemporal_resampling_weights( age_name="Age", max_memory_fraction=0.25, normalized_weights=True, - **kwargs + **kwargs, ): """ Takes a dataframe with lat, long and age and returns a sampling weight for each @@ -132,7 +133,7 @@ def get_spatiotemporal_resampling_weights( df[[*latlong_names]], absolute=False, max_memory_fraction=max_memory_fraction, - **subkwargs(kwargs, great_circle_distance) + **subkwargs(kwargs, great_circle_distance), ) # angular distances _invnormdistances = np.zeros_like(z) @@ -211,9 +212,9 @@ def add_age_noise( age_uncertainty = ( np.abs(df[max_age_name] - df[min_age_name]) / 2 ) # half bin width - age_uncertainty[ - ~np.isfinite(age_uncertainty) | age_uncertainty < min_sigma - ] = min_sigma + age_uncertainty[~np.isfinite(age_uncertainty) | age_uncertainty < min_sigma] = ( + min_sigma + ) # generate gaussian age noise age_noise = np.random.randn(df.index.size) * age_uncertainty.values age_noise *= noise_level # scale the noise @@ -238,7 +239,7 @@ def spatiotemporal_bootstrap_resample( noise_level=1, age_name="Age", latlong_names=["Latitude", "Longitude"], - **kwargs + **kwargs, ): """ Resample and aggregate metrics from a dataframe, optionally aggregating by a given @@ -316,7 +317,7 @@ def spatiotemporal_bootstrap_resample( df, age_name=age_name, latlong_names=latlong_names, - **subkwargs(kwargs, get_spatiotemporal_resampling_weights) + **subkwargs(kwargs, get_spatiotemporal_resampling_weights), ) # to efficiently manage categories we can make sure we have an iterable here @@ -358,7 +359,7 @@ def _metric_name(metric): min_sigma=50, age_name=age_name, noise_level=noise_level, - **subkwargs(kwargs, add_age_noise) + **subkwargs(kwargs, add_age_noise), ) # transform the parameters to be estimated before adding parameter noise? diff --git a/pyrolite/util/skl/__init__.py b/pyrolite/util/skl/__init__.py index e17c530b..ceaed00e 100644 --- a/pyrolite/util/skl/__init__.py +++ b/pyrolite/util/skl/__init__.py @@ -1,6 +1,7 @@ """ Utilities for use with :mod:`sklearn`. """ + from ..log import Handle logger = Handle(__name__) diff --git a/pyrolite/util/skl/impute.py b/pyrolite/util/skl/impute.py index d836e997..d150b7e0 100644 --- a/pyrolite/util/skl/impute.py +++ b/pyrolite/util/skl/impute.py @@ -90,7 +90,7 @@ def fit(self, X, y=None): max_iter=self.max_iter, sample_posterior=True, random_state=ix, - **self.kwargs + **self.kwargs, ) for ix in range(self.multiple) ], @@ -115,7 +115,7 @@ def fit(self, X, y=None): max_iter=self.max_iter, sample_posterior=True, random_state=ix, - **self.kwargs + **self.kwargs, ) ) msg = """Imputation transformer: {} imputers""".format(self.multiple) diff --git a/pyrolite/util/skl/pipeline.py b/pyrolite/util/skl/pipeline.py index 37a5e4a5..d0bf92d7 100644 --- a/pyrolite/util/skl/pipeline.py +++ b/pyrolite/util/skl/pipeline.py @@ -70,7 +70,9 @@ def fit_save_classifier( return clf -def classifier_performance_report(clf, X_test, y_test, classes=[], directory=".", name="clf"): +def classifier_performance_report( + clf, X_test, y_test, classes=[], directory=".", name="clf" +): """ Output a performance report for a classifier. Currently outputs the overall classification score, a confusion matrix and where relevant an indication of @@ -84,13 +86,13 @@ def classifier_performance_report(clf, X_test, y_test, classes=[], directory="." Input data for testing. y_test : :class:`numpy.ndarray` | :class:`pandas.Series` Labelled/target data for testing. - classes : list + classes : list Names of classes. directory : :class:`str` | :class:`pathlib.Path` Path to the save directory. name : :class:`str` Name of the classifier. - + Returns -------- clf : :class:`sklearn.base.BaseEstimator` @@ -140,7 +142,7 @@ def SVC_pipeline( n_jobs=4, verbose=10, cache_size=500, - **kwargs + **kwargs, ): """ A convenience function for constructing a Support Vector Classifier pipeline. diff --git a/pyrolite/util/spatial.py b/pyrolite/util/spatial.py index 1ce4151b..34e3cd24 100644 --- a/pyrolite/util/spatial.py +++ b/pyrolite/util/spatial.py @@ -1,6 +1,7 @@ """ Baisc spatial utility functions. """ + import itertools import numpy as np @@ -187,7 +188,11 @@ def great_circle_distance( ) ) - infeasible = estimated_matrix_size > (virtual_memory().total * max_memory_fraction) if virtual_memory is not None else False + infeasible = ( + estimated_matrix_size > (virtual_memory().total * max_memory_fraction) + if virtual_memory is not None + else False + ) if infeasible: logger.warn( @@ -264,7 +269,7 @@ def spatiotemporal_split( nan_lims=[np.nan, np.nan], # usebounds=False, # order=['minx', 'miny', 'maxx', 'maxy'], - **kwargs + **kwargs, ): """ Creates spatiotemporal grid using piecewise function and arbitrary diff --git a/pyrolite/util/synthetic.py b/pyrolite/util/synthetic.py index c5a95961..62849c38 100644 --- a/pyrolite/util/synthetic.py +++ b/pyrolite/util/synthetic.py @@ -1,6 +1,7 @@ """ Utility functions for creating synthetic (geochemical) data. """ + import numpy as np import pandas as pd diff --git a/test/geochem/geochem_alteration.py b/test/geochem/geochem_alteration.py index 8c8d083f..400d450f 100644 --- a/test/geochem/geochem_alteration.py +++ b/test/geochem/geochem_alteration.py @@ -66,4 +66,4 @@ def test_CCPI_default(self): if __name__ == "__main__": - unittest.main() \ No newline at end of file + unittest.main() diff --git a/test/util/plot/util_plot_export.py b/test/util/plot/util_plot_export.py index 75520167..23b991c7 100644 --- a/test/util/plot/util_plot_export.py +++ b/test/util/plot/util_plot_export.py @@ -57,7 +57,6 @@ def tearDown(self): class TestPath2CSV(unittest.TestCase): - def setUp(self): self.fig, self.ax = plt.subplots(1) self.ax.plot([0, 1, 2, 3], [0, 0, 0, 0]) diff --git a/test/util/plot/util_plot_interpolation.py b/test/util/plot/util_plot_interpolation.py index f8e06467..78e66c86 100644 --- a/test/util/plot/util_plot_interpolation.py +++ b/test/util/plot/util_plot_interpolation.py @@ -13,7 +13,6 @@ class TestInterpolatePath(unittest.TestCase): - def setUp(self): self.fig, self.ax = plt.subplots(1) self.ax.plot([0, 1, 2, 3, 0], [0, 0.1, 1, 2, 0]) # a closed path @@ -51,7 +50,6 @@ def test_resolution(self): class TestContourPaths(unittest.TestCase): - def setUp(self): self.fig, self.ax = plt.subplots(1) # this is the contour demo data from matplotlib, for refrence diff --git a/test/util/plot/util_plot_style.py b/test/util/plot/util_plot_style.py index d07cd781..e18d30c2 100644 --- a/test/util/plot/util_plot_style.py +++ b/test/util/plot/util_plot_style.py @@ -49,7 +49,6 @@ def test_default(self): class TestMappableFromValues(unittest.TestCase): - def setUp(self): self.fig, self.ax = plt.subplots(1) diff --git a/test/util/skl/util_skl_pipeline.py b/test/util/skl/util_skl_pipeline.py index 7415fe01..e13b38b5 100644 --- a/test/util/skl/util_skl_pipeline.py +++ b/test/util/skl/util_skl_pipeline.py @@ -54,7 +54,9 @@ def setUp(self): def test_default(self): self.classifier.fit(self.X, self.y) - classifier_performance_report(self.classifier, self.X, self.y, directory=self.dir) + classifier_performance_report( + self.classifier, self.X, self.y, directory=self.dir + ) def tearDown(self): remove_tempdir(self.dir) diff --git a/test/util/util_env.py b/test/util/util_env.py index 9441f1f4..42ce66b2 100644 --- a/test/util/util_env.py +++ b/test/util/util_env.py @@ -11,6 +11,7 @@ def setUp(self): def test_single_validator(self): def v(x): return x > 0 + expect = True self.assertTrue(validate_value(self.value, v) is expect) diff --git a/test/util/util_log.py b/test/util/util_log.py index 73dfd3b0..77c4ccc6 100644 --- a/test/util/util_log.py +++ b/test/util/util_log.py @@ -79,7 +79,6 @@ def test_set_level(self): class TestToLogger(unittest.TestCase): - def test_default(self): logger = Handle(__name__, level="DEBUG") diff --git a/test/util/util_text.py b/test/util/util_text.py index aa908a6f..f57431e4 100644 --- a/test/util/util_text.py +++ b/test/util/util_text.py @@ -249,7 +249,6 @@ def test_split_csv_rows(self): class TestSlugify(unittest.TestCase): - def test_default(self): self.assertEqual(slugify("a b"), "a-b") self.assertEqual(slugify("a@b"), "ab") @@ -258,7 +257,6 @@ def test_default(self): class TestInt2Alpha(unittest.TestCase): - def test_default(self): self.assertEqual(int_to_alpha(0), "a") self.assertEqual(int_to_alpha(26), "aa")