Skip to content

Commit

Permalink
chore: Run pyupgrade on codebase (3.6+) (#1164)
Browse files Browse the repository at this point in the history
* Run pyupgrade --py36-plus on codebase
* Add pyupgrade to pre-commit hooks
* Add pre-commit.ci status badge to README
* Use f-strings over format() as much as possible
* Thanks to Anthony Sottile (@asottile) for pyupgrade and pre-commit.ci

Co-authored-by: Matthew Feickert <[email protected]>
  • Loading branch information
kratsg and matthewfeickert authored Nov 5, 2020
1 parent 81c9adb commit a3b34a5
Show file tree
Hide file tree
Showing 66 changed files with 289 additions and 433 deletions.
4 changes: 4 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ repos:
hooks:
- id: black
language_version: python3
- repo: https://github.com/asottile/pyupgrade
rev: v2.7.3
hooks:
- id: pyupgrade
6 changes: 5 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ pure-python fitting/limit-setting/interval estimation HistFactory-style
|GitHub Project| |DOI| |Scikit-HEP| |NSF Award Number|

|GitHub Actions Status: CI| |GitHub Actions Status: Docs| |GitHub Actions Status: Publish|
|Docker Automated| |Code Coverage| |Language grade: Python| |CodeFactor| |Code style: black|
|Docker Automated| |Code Coverage| |Language grade: Python| |CodeFactor|
|pre-commit.ci Status| |Code style: black|

|Docs| |Binder|

Expand Down Expand Up @@ -329,6 +330,9 @@ and grant `OAC-1450377 <https://www.nsf.gov/awardsearch/showAward?AWD_ID=1450377
:target: https://lgtm.com/projects/g/scikit-hep/pyhf/latest/files/
.. |CodeFactor| image:: https://www.codefactor.io/repository/github/scikit-hep/pyhf/badge
:target: https://www.codefactor.io/repository/github/scikit-hep/pyhf
.. |pre-commit.ci Status| image:: https://results.pre-commit.ci/badge/github/scikit-hep/pyhf/master.svg
:target: https://results.pre-commit.ci/latest/github/scikit-hep/pyhf/master
:alt: pre-commit.ci status
.. |Code style: black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
.. |Docs| image:: https://img.shields.io/badge/docs-master-blue.svg
Expand Down
2 changes: 1 addition & 1 deletion docs/babel.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Typically, ``prefix = 'FitConfig'`` and ``measurementName = 'NormalMeasurement'`
from configManager import configMgr
# ...
configMgr.analysisName = '3b_tag21.2.27-1_RW_ExpSyst_36100_multibin_bkg'
configMgr.histCacheFile = 'cache/{0:s}.root'.format(configMgr.analysisName)
configMgr.histCacheFile = f'cache/{configMgr.analysisName:s}.root'
# ...
fitConfig = configMgr.addFitConfig("Excl")
# ...
Expand Down
15 changes: 7 additions & 8 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# pyhf documentation build configuration file, created by
# sphinx-quickstart on Fri Feb 9 11:58:49 2018.
Expand Down Expand Up @@ -89,9 +88,9 @@ def setup(app):
master_doc = 'index'

# General information about the project.
project = u'pyhf'
copyright = u'2018, Lukas Heinrich, Matthew Feickert, Giordon Stark'
author = u'Lukas Heinrich, Matthew Feickert, Giordon Stark'
project = 'pyhf'
copyright = '2018, Lukas Heinrich, Matthew Feickert, Giordon Stark'
author = 'Lukas Heinrich, Matthew Feickert, Giordon Stark'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down Expand Up @@ -328,8 +327,8 @@ def setup(app):
(
master_doc,
'pyhf.tex',
u'pyhf Documentation',
u'Lukas Heinrich, Matthew Feickert, Giordon Stark',
'pyhf Documentation',
'Lukas Heinrich, Matthew Feickert, Giordon Stark',
'manual',
)
]
Expand Down Expand Up @@ -371,7 +370,7 @@ def setup(app):

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, 'pyhf', u'pyhf Documentation', [author], 1)]
man_pages = [(master_doc, 'pyhf', 'pyhf Documentation', [author], 1)]

# If true, show URL addresses after external links.
#
Expand All @@ -387,7 +386,7 @@ def setup(app):
(
master_doc,
'pyhf',
u'pyhf Documentation',
'pyhf Documentation',
author,
'pyhf',
'One line description of project.',
Expand Down
2 changes: 0 additions & 2 deletions docs/exts/xref.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

from docutils import nodes

from sphinx.util import caption_ref_re
Expand Down
26 changes: 12 additions & 14 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
+ extras_require['minuit']
)
)
extras_require['contrib'] = sorted(set(['matplotlib', 'requests']))
extras_require['lint'] = sorted(set(['pyflakes', 'black']))
extras_require['contrib'] = sorted({'matplotlib', 'requests'})
extras_require['lint'] = sorted({'pyflakes', 'black'})

extras_require['test'] = sorted(
set(
Expand All @@ -47,18 +47,16 @@
)
)
extras_require['docs'] = sorted(
set(
[
'sphinx>=3.1.2',
'sphinxcontrib-bibtex',
'sphinx-click',
'sphinx_rtd_theme',
'nbsphinx',
'ipywidgets',
'sphinx-issues',
'sphinx-copybutton>0.2.9',
]
)
{
'sphinx>=3.1.2',
'sphinxcontrib-bibtex',
'sphinx-click',
'sphinx_rtd_theme',
'nbsphinx',
'ipywidgets',
'sphinx-issues',
'sphinx-copybutton>0.2.9',
}
)
extras_require['develop'] = sorted(
set(
Expand Down
4 changes: 2 additions & 2 deletions src/pyhf/cli/infer.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def fit(
else:
with open(output_file, "w+") as out_file:
json.dump(result, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
log.debug(f"Written to {output_file:s}")


@cli.command()
Expand Down Expand Up @@ -240,4 +240,4 @@ def cls(
else:
with open(output_file, 'w+') as out_file:
json.dump(result, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
log.debug(f"Written to {output_file:s}")
4 changes: 2 additions & 2 deletions src/pyhf/cli/patchset.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def extract(patchset, name, output_file, with_metadata):
if output_file:
with open(output_file, 'w+') as out_file:
json.dump(result, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
log.debug(f"Written to {output_file:s}")
else:
click.echo(json.dumps(result, indent=4, sort_keys=True))

Expand Down Expand Up @@ -93,7 +93,7 @@ def apply(background_only, patchset, name, output_file):
if output_file:
with open(output_file, 'w+') as out_file:
json.dump(patched_ws, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
log.debug(f"Written to {output_file:s}")
else:
click.echo(json.dumps(patched_ws, indent=4, sort_keys=True))

Expand Down
2 changes: 1 addition & 1 deletion src/pyhf/cli/rootio.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def xml2json(entrypoint_xml, basedir, output_file, track_progress):
else:
with open(output_file, 'w+') as out_file:
json.dump(spec, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
log.debug(f"Written to {output_file:s}")


@cli.command()
Expand Down
18 changes: 9 additions & 9 deletions src/pyhf/cli/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,34 +107,34 @@ def inspect(workspace, output_file, measurement):
fmtStr = '{{0: >{0:d}s}} {{1:s}}'.format(maxlen + len('Summary'))
click.echo(fmtStr.format(' Summary ', ''))
click.echo(fmtStr.format('-' * 18, ''))
fmtStr = '{{0: >{0:d}s}} {{1:s}}'.format(maxlen)
fmtStr = f'{{0: >{maxlen:d}s}} {{1:s}}'
for key in ['channels', 'samples', 'parameters', 'modifiers']:
click.echo(fmtStr.format(key, str(len(result[key]))))
click.echo()

fmtStr = '{{0: >{0:d}s}} {{1: ^5s}}'.format(maxlen)
fmtStr = f'{{0: >{maxlen:d}s}} {{1: ^5s}}'
click.echo(fmtStr.format('channels', 'nbins'))
click.echo(fmtStr.format('-' * 10, '-' * 5))
for channel, nbins in result['channels']:
click.echo(fmtStr.format(channel, str(nbins)))
click.echo()

fmtStr = '{{0: >{0:d}s}}'.format(maxlen)
fmtStr = f'{{0: >{maxlen:d}s}}'
click.echo(fmtStr.format('samples'))
click.echo(fmtStr.format('-' * 10))
for sample in result['samples']:
click.echo(fmtStr.format(sample))
click.echo()

# print parameters, constraints, modifiers
fmtStr = '{{0: >{0:d}s}} {{1: <22s}} {{2:s}}'.format(maxlen)
fmtStr = f'{{0: >{maxlen:d}s}} {{1: <22s}} {{2:s}}'
click.echo(fmtStr.format('parameters', 'constraint', 'modifiers'))
click.echo(fmtStr.format('-' * 10, '-' * 10, '-' * 10))
for parname, constraint, modtypes in result['systematics']:
click.echo(fmtStr.format(parname, constraint, ','.join(sorted(set(modtypes)))))
click.echo()

fmtStr = '{{0: >{0:d}s}} {{1: ^22s}} {{2:s}}'.format(maxlen)
fmtStr = f'{{0: >{maxlen:d}s}} {{1: ^22s}} {{2:s}}'
click.echo(fmtStr.format('measurement', 'poi', 'parameters'))
click.echo(fmtStr.format('-' * 10, '-' * 10, '-' * 10))
for measurement_name, measurement_poi, measurement_parameters in result[
Expand All @@ -156,7 +156,7 @@ def inspect(workspace, output_file, measurement):
if output_file:
with open(output_file, 'w+') as out_file:
json.dump(result, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
log.debug(f"Written to {output_file:s}")


@cli.command()
Expand Down Expand Up @@ -202,7 +202,7 @@ def prune(
else:
with open(output_file, 'w+') as out_file:
json.dump(pruned_ws, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
log.debug(f"Written to {output_file:s}")


@cli.command()
Expand Down Expand Up @@ -265,7 +265,7 @@ def rename(workspace, output_file, channel, sample, modifier, measurement):
else:
with open(output_file, 'w+') as out_file:
json.dump(renamed_ws, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
log.debug(f"Written to {output_file:s}")


@cli.command()
Expand Down Expand Up @@ -311,7 +311,7 @@ def combine(workspace_one, workspace_two, join, output_file, merge_channels):
else:
with open(output_file, 'w+') as out_file:
json.dump(combined_ws, out_file, indent=4, sort_keys=True)
log.debug("Written to {0:s}".format(output_file))
log.debug(f"Written to {output_file:s}")


@cli.command()
Expand Down
4 changes: 2 additions & 2 deletions src/pyhf/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from .parameters import ParamViewer


class gaussian_constraint_combined(object):
class gaussian_constraint_combined:
def __init__(self, pdfconfig, batch_size=None):
self.batch_size = batch_size
# iterate over all constraints order doesn't matter....
Expand Down Expand Up @@ -136,7 +136,7 @@ def logpdf(self, auxdata, pars):
return pdf.log_prob(normal_data)


class poisson_constraint_combined(object):
class poisson_constraint_combined:
def __init__(self, pdfconfig, batch_size=None):
self.batch_size = batch_size
# iterate over all constraints order doesn't matter....
Expand Down
6 changes: 3 additions & 3 deletions src/pyhf/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from functools import wraps

__events = {}
__disabled_events = set([])
__disabled_events = set()


def noop(*args, **kwargs):
Expand Down Expand Up @@ -74,9 +74,9 @@ def register(event):
def _register(func):
@wraps(func)
def register_wrapper(*args, **kwargs):
trigger("{0:s}::before".format(event))()
trigger(f"{event:s}::before")()
result = func(*args, **kwargs)
trigger("{0:s}::after".format(event))()
trigger(f"{event:s}::after")()
return result

return register_wrapper
Expand Down
4 changes: 2 additions & 2 deletions src/pyhf/exceptions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ def __init__(self, ValidationError, schema=None):
self.path = ''
for item in ValidationError.path:
if isinstance(item, int):
self.path += '[{}]'.format(item)
self.path += f'[{item}]'
else:
self.path += '.{}'.format(item)
self.path += f'.{item}'
self.path = self.path.lstrip('.')
self.instance = ValidationError.instance
message = f"{ValidationError.message}.\n\tPath: {self.path}\n\tInstance: {self.instance} Schema: {self.schema}"
Expand Down
12 changes: 6 additions & 6 deletions src/pyhf/infer/calculators.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def generate_asimov_data(asimov_mu, data, pdf, init_pars, par_bounds, fixed_para
return pdf.expected_data(bestfit_nuisance_asimov)


class AsymptoticTestStatDistribution(object):
class AsymptoticTestStatDistribution:
r"""
The distribution the test statistic in the asymptotic case.
Expand Down Expand Up @@ -96,7 +96,7 @@ def cdf(self, value):
"""
tensorlib, _ = get_backend()
return tensorlib.normal_cdf((value - self.shift))
return tensorlib.normal_cdf(value - self.shift)

def pvalue(self, value):
r"""
Expand Down Expand Up @@ -149,7 +149,7 @@ def expected_value(self, nsigma):
return self.shift + nsigma


class AsymptoticCalculator(object):
class AsymptoticCalculator:
"""The Asymptotic Calculator."""

def __init__(
Expand Down Expand Up @@ -192,7 +192,7 @@ def __init__(
self.sqrtqmuA_v = None

def distributions(self, poi_test):
"""
r"""
Probability distributions of the test statistic, as defined in
:math:`\S` 3 of :xref:`arXiv:1007.1727` under the Wald approximation,
under the signal + background and background-only hypotheses.
Expand Down Expand Up @@ -304,7 +304,7 @@ def _false_case():
return teststat


class EmpiricalDistribution(object):
class EmpiricalDistribution:
"""
The empirical distribution of the test statistic.
Expand Down Expand Up @@ -441,7 +441,7 @@ def expected_value(self, nsigma):
)


class ToyCalculator(object):
class ToyCalculator:
"""The Toy-based Calculator."""

def __init__(
Expand Down
4 changes: 2 additions & 2 deletions src/pyhf/interpolators/code0.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
log = logging.getLogger(__name__)


class code0(object):
class code0:
r"""
The piecewise-linear interpolation strategy.
Expand Down Expand Up @@ -84,7 +84,7 @@ def __call__(self, alphasets):
return tensorlib.where(masks, alphas_times_deltas_up, alphas_times_deltas_dn)


class _slow_code0(object):
class _slow_code0:
def summand(self, down, nom, up, alpha):
delta_up = up - nom
delta_down = nom - down
Expand Down
4 changes: 2 additions & 2 deletions src/pyhf/interpolators/code1.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
log = logging.getLogger(__name__)


class code1(object):
class code1:
r"""
The piecewise-exponential interpolation strategy.
Expand Down Expand Up @@ -100,7 +100,7 @@ def __call__(self, alphasets):
return tensorlib.power(bases, exponents)


class _slow_code1(object):
class _slow_code1:
def product(self, down, nom, up, alpha):
delta_up = up / nom
delta_down = down / nom
Expand Down
Loading

0 comments on commit a3b34a5

Please sign in to comment.