Skip to content

Commit

Permalink
Drop support for Python 2 (#2016)
Browse files Browse the repository at this point in the history
Upgrade Python syntax with pyupgrade --py3-plus
  • Loading branch information
hugovk authored and cdeil committed Jan 31, 2019
1 parent d621ad5 commit fdf4870
Show file tree
Hide file tree
Showing 23 changed files with 53 additions and 57 deletions.
1 change: 0 additions & 1 deletion dev/docker/commands.sh
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ export PATH=/home/travis/miniconda/bin:$PATH
conda update --yes conda
sudo apt-get update
if [[ $SETUP_CMD == build_docs* ]]; then sudo apt-get install graphviz texlive-latex-extra dvipng; fi
if [[ $TRAVIS_PYTHON_VERSION == 2.7 ]]; then export TRAVIS_PYTHON_VERSION=2.7.8; fi
conda create --yes -n test -c astropy-ci-extras python=$TRAVIS_PYTHON_VERSION
source activate test
export CONDA_INSTALL="conda install -c astropy-ci-extras --yes python=$TRAVIS_PYTHON_VERSION numpy=$NUMPY_VERSION"
Expand Down
2 changes: 1 addition & 1 deletion dev/sherpa/stats/sherpa_stats_compute_direct.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,5 @@ def calc_stat(data, model, staterror):
stat_error = stat_object.calc_staterror(0)
except ValueError:
stat_error = -999
print('%20s %20.10f' % (stat_name, stat_error))
print('{:>20} {:20.10f}'.format(stat_name, stat_error))
# stat_object.calc_staterror(data=2, model=12, staterror=2)
2 changes: 1 addition & 1 deletion dev/sherpa/stats/sherpa_stats_compute_via_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@
for stat_name in stat_names:
set_stat(stat_name)
stat_value = calc_stat()
print('%20s %20.10f' % (stat_name, stat_value))
print('{:>20} {:20.10f}'.format(stat_name, stat_value))
2 changes: 1 addition & 1 deletion docs/astro/source/plot_snr_brightness_evolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
for density in densities:
snr = SNR(n_ISM=density)
F = snr.luminosity_tev(t) / (4 * np.pi * Quantity(1, "kpc") ** 2)
plt.plot(t.value, F.to("cm-2 s-1").value, label="n_ISM = {0}".format(density.value))
plt.plot(t.value, F.to("cm-2 s-1").value, label="n_ISM = {}".format(density.value))
plt.vlines(snr.sedov_taylor_begin.to("yr").value, 1e-13, 1e-10, linestyle="--")
plt.vlines(snr.sedov_taylor_end.to("yr").value, 1e-13, 1e-10, linestyle="--")

Expand Down
2 changes: 1 addition & 1 deletion docs/astro/source/plot_snr_radius_evolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
for density in densities:
for linestyle, snr_model in zip(linestyles, snr_models):
snr = snr_model(n_ISM=density)
label = snr.__class__.__name__ + " (n_ISM = {0})".format(density.value)
label = snr.__class__.__name__ + " (n_ISM = {})".format(density.value)
x = t.value
y = snr.radius(t).to("pc").value
plt.plot(x, y, label=label, linestyle=linestyle)
Expand Down
13 changes: 5 additions & 8 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@
from gammapy.utils.docs import gammapy_sphinx_notebooks

# Get configuration information from setup.cfg
try:
from ConfigParser import ConfigParser
except ImportError:
from configparser import ConfigParser
from configparser import ConfigParser
conf = ConfigParser()
conf.read([os.path.join(os.path.dirname(__file__), "..", "setup.cfg")])
setup_cfg = dict(conf.items("metadata"))
Expand Down Expand Up @@ -112,7 +109,7 @@
# This does not *have* to match the package name, but typically does
project = setup_cfg["package_name"]
author = setup_cfg["author"]
copyright = "{0}, {1}".format(datetime.datetime.now().year, setup_cfg["author"])
copyright = "{}, {}".format(datetime.datetime.now().year, setup_cfg["author"])

# 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 @@ -179,7 +176,7 @@

# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "{0} v{1}".format(project, release)
html_title = "{} v{}".format(project, release)

# Output file base name for HTML help builder.
htmlhelp_basename = project + "doc"
Expand Down Expand Up @@ -213,14 +210,14 @@ def setup(app):
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
("index", project + ".tex", project + u" Documentation", author, "manual")
("index", project + ".tex", project + " Documentation", author, "manual")
]

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [("index", project.lower(), project + u" Documentation", [author], 1)]
man_pages = [("index", project.lower(), project + " Documentation", [author], 1)]

# -- Options for the edit_on_github extension ----------------------------------------

Expand Down
2 changes: 1 addition & 1 deletion gammapy/astro/population/spatial.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class CaseBattacharya1998(Fittable1DModel):
evolved = True

def __init__(self, amplitude=1.0, alpha=2, beta=3.53, **kwargs):
super(CaseBattacharya1998, self).__init__(
super().__init__(
amplitude=amplitude, alpha=alpha, beta=beta, **kwargs
)

Expand Down
4 changes: 2 additions & 2 deletions gammapy/catalog/fermi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1019,7 +1019,7 @@ def is_source_class(self, source_class):
elif source_class == "all":
category = set(cats["extra-galactic"] + cats["galactic"])
elif source_class in np.unique(source_class_info):
category = set([source_class])
category = {source_class}
else:
raise ValueError("Invalid source_class: {!r}".format(source_class))

Expand Down Expand Up @@ -1190,7 +1190,7 @@ def is_source_class(self, source_class):
elif source_class == "all":
category = set(cats["extra-galactic"] + cats["galactic"])
elif source_class in np.unique(source_class_info):
category = set([source_class])
category = {source_class}
else:
raise ValueError("Invalid source_class: {!r}".format(source_class))

Expand Down
4 changes: 2 additions & 2 deletions gammapy/catalog/gammacat.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,12 +634,12 @@ def __eq__(self, other):
@property
def unique_source_ids(self):
"""Sorted list of unique source IDs (list of int)."""
return sorted(set([resource.source_id for resource in self.resources]))
return sorted({resource.source_id for resource in self.resources})

@property
def unique_reference_ids(self):
"""Sorted list of unique source IDs (list of str)."""
return sorted(set([resource.reference_id for resource in self.resources]))
return sorted({resource.reference_id for resource in self.resources})

@property
def global_ids(self):
Expand Down
2 changes: 1 addition & 1 deletion gammapy/catalog/tests/test_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,4 @@ def test_register(source_catalogs):

def test_source_catalogs(source_catalogs):
"""Test the global registry instance"""
assert set(["3fgl", "2fhl"]).issubset(source_catalogs.catalog_names)
assert {"3fgl", "2fhl"}.issubset(source_catalogs.catalog_names)
18 changes: 9 additions & 9 deletions gammapy/catalog/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,15 @@ def _ra_iau_format_scalar(ra, digits):
ra_s = ra.hms[2]

if digits == 2: # format: HH
ra_str = "{0:02d}".format(ra_h)
ra_str = "{:02d}".format(ra_h)
elif digits == 3: # format: HHh
ra_str = "{0:03d}".format(int(10 * ra.hour))
ra_str = "{:03d}".format(int(10 * ra.hour))
elif digits == 4: # format: HHMM
ra_str = "{0:02d}{1:02d}".format(ra_h, ra_m)
ra_str = "{:02d}{:02d}".format(ra_h, ra_m)
elif digits == 5: # format : HHMM.m
ra_str = "{0:02d}{1:02d}.{2:01d}".format(ra_h, ra_m, int(ra_s / 6))
ra_str = "{:02d}{:02d}.{:01d}".format(ra_h, ra_m, int(ra_s / 6))
elif digits == 6: # format: HHMMSS
ra_str = "{0:02d}{1:02d}{2:02d}".format(ra_h, ra_m, int(ra_s))
ra_str = "{:02d}{:02d}{:02d}".format(ra_h, ra_m, int(ra_s))
else: # format: HHMMSS.s
SS = int(ra_s)
s_digits = digits - 6
Expand Down Expand Up @@ -245,13 +245,13 @@ def skycoord_from_table(table):
except AttributeError:
keys = table.keys()

if set(["RAJ2000", "DEJ2000"]).issubset(keys):
if {"RAJ2000", "DEJ2000"}.issubset(keys):
lon, lat, frame = "RAJ2000", "DEJ2000", "icrs"
elif set(["RA", "DEC"]).issubset(keys):
elif {"RA", "DEC"}.issubset(keys):
lon, lat, frame = "RA", "DEC", "icrs"
elif set(["GLON", "GLAT"]).issubset(keys):
elif {"GLON", "GLAT"}.issubset(keys):
lon, lat, frame = "GLON", "GLAT", "galactic"
elif set(["glon", "glat"]).issubset(keys):
elif {"glon", "glat"}.issubset(keys):
lon, lat, frame = "glon", "glat", "galactic"
else:
raise KeyError("No column GLON / GLAT or RA / DEC or RAJ2000 / DEJ2000 found.")
Expand Down
18 changes: 9 additions & 9 deletions gammapy/detect/cwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,17 +125,17 @@ def _transform(self, data):
"""
total_background = data._model + data._background + data._approx
excess = data._counts - total_background
log.debug("Excess sum: {0:.4f}".format(excess.sum()))
log.debug("Excess max: {0:.4f}".format(excess.max()))
log.debug("Excess sum: {:.4f}".format(excess.sum()))
log.debug("Excess max: {:.4f}".format(excess.max()))

log.debug("Computing transform and error")
for idx_scale, kern in self.kernels.kern_base.items():
data._transform_3d[idx_scale] = fftconvolve(excess, kern, mode="same")
data._error[idx_scale] = np.sqrt(
fftconvolve(total_background, kern ** 2, mode="same")
)
log.debug("Error sum: {0:.4f}".format(data._error.sum()))
log.debug("Error max: {0:.4f}".format(data._error.max()))
log.debug("Error sum: {:.4f}".format(data._error.sum()))
log.debug("Error max: {:.4f}".format(data._error.max()))

log.debug("Computing approx and approx_bkg")
data._approx = fftconvolve(
Expand All @@ -146,8 +146,8 @@ def _transform(self, data):
data._approx_bkg = fftconvolve(
data._background, self.kernels.kern_approx, mode="same"
)
log.debug("Approximate sum: {0:.4f}".format(data._approx.sum()))
log.debug("Approximate background sum: {0:.4f}".format(data._approx_bkg.sum()))
log.debug("Approximate sum: {:.4f}".format(data._approx.sum()))
log.debug("Approximate background sum: {:.4f}".format(data._approx_bkg.sum()))

def _compute_support(self, data):
"""Compute the multiresolution support with hard sigma clipping.
Expand Down Expand Up @@ -253,9 +253,9 @@ def _is_converged(self, data):
log.debug("Check the convergence")
residual = data._counts - (data._model + data._approx)
variance = residual.var()
log.info("Residual sum: {0:.4f}".format(residual.sum()))
log.info("Residual max: {0:.4f}".format(residual.max()))
log.info("Residual variance: {0:.4f}".format(residual.var()))
log.info("Residual sum: {:.4f}".format(residual.sum()))
log.info("Residual max: {:.4f}".format(residual.max()))
log.info("Residual variance: {:.4f}".format(residual.var()))

if self.previous_variance is None:
self.previous_variance = variance
Expand Down
2 changes: 1 addition & 1 deletion gammapy/irf/energy_dispersion.py
Original file line number Diff line number Diff line change
Expand Up @@ -942,7 +942,7 @@ def plot_migration(self, ax=None, offset=None, e_true=None, migra=None, **kwargs
for ener in e_true:
for off in offset:
disp = self.data.evaluate(offset=off, e_true=ener, migra=migra)
label = "offset = {0:.1f}\nenergy = {1:.1f}".format(off, ener)
label = "offset = {:.1f}\nenergy = {:.1f}".format(off, ener)
ax.plot(migra, disp, label=label, **kwargs)

ax.set_xlabel(r"$E_\mathrm{{Reco}} / E_\mathrm{{True}}$")
Expand Down
4 changes: 2 additions & 2 deletions gammapy/irf/psf_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ def plot_containment(
self._plot_safe_energy_range(ax)

if add_cbar:
label = "Containment radius R{0:.0f} ({1})" "".format(
label = "Containment radius R{:.0f} ({})" "".format(
100 * fraction, containment.unit
)
ax.figure.colorbar(caxes, ax=ax, label=label)
Expand All @@ -424,7 +424,7 @@ def _plot_safe_energy_range(self, ax):
omin = self.offset.value.min()
omax = self.offset.value.max()
ax.hlines(y=esafe.value, xmin=omin, xmax=omax)
label = "Safe energy threshold: {0:3.2f}".format(esafe)
label = "Safe energy threshold: {:3.2f}".format(esafe)
ax.text(x=0.1, y=0.9 * esafe.value, s=label, va="top")

def peek(self, figsize=(15, 5)):
Expand Down
12 changes: 6 additions & 6 deletions gammapy/irf/psf_gauss.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def plot_containment(
self._plot_safe_energy_range(ax)

if add_cbar:
label = "Containment radius R{0:.0f} ({1})".format(
label = "Containment radius R{:.0f} ({})".format(
100 * fraction, containment.unit
)
ax.figure.colorbar(caxes, ax=ax, label=label)
Expand All @@ -324,7 +324,7 @@ def _plot_safe_energy_range(self, ax):
omin = self.offset.value.min()
omax = self.offset.value.max()
ax.hlines(y=esafe.value, xmin=omin, xmax=omax)
label = "Safe energy threshold: {0:3.2f}".format(esafe)
label = "Safe energy threshold: {:3.2f}".format(esafe)
ax.text(x=0.1, y=0.9 * esafe.value, s=label, va="top")

def plot_containment_vs_energy(
Expand Down Expand Up @@ -397,17 +397,17 @@ def info(
ss += array_stats_str(self.theta.to("deg"), "Theta")
ss += array_stats_str(self.energy_hi, "Energy hi")
ss += array_stats_str(self.energy_lo, "Energy lo")
ss += "Safe energy threshold lo: {0:6.3f}\n".format(self.energy_thresh_lo)
ss += "Safe energy threshold hi: {0:6.3f}\n".format(self.energy_thresh_hi)
ss += "Safe energy threshold lo: {:6.3f}\n".format(self.energy_thresh_lo)
ss += "Safe energy threshold hi: {:6.3f}\n".format(self.energy_thresh_hi)

for fraction in fractions:
containment = self.containment_radius(energies, thetas, fraction)
for i, energy in enumerate(energies):
for j, theta in enumerate(thetas):
radius = containment[j, i]
ss += (
"{0:2.0f}% containment radius at theta = {1} and "
"E = {2:4.1f}: {3:5.8f}\n"
"{:2.0f}% containment radius at theta = {} and "
"E = {:4.1f}: {:5.8f}\n"
"".format(100 * fraction, theta, energy, radius)
)
return ss
Expand Down
2 changes: 1 addition & 1 deletion gammapy/spectrum/energy_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def __init__(

@classmethod
def from_dict(cls, data):
data = dict((_, data[_]) for _ in cls.fields)
data = {_: data[_] for _ in cls.fields}
return cls(**data)

@property
Expand Down
2 changes: 1 addition & 1 deletion gammapy/spectrum/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def __str__(self):
s += "--------------- \n"
s += "Model: {} \n".format(self.model)
if self.statval is not None:
s += "\nStatistic: {0:.3f} ({1})".format(self.statval, self.statname)
s += "\nStatistic: {:.3f} ({})".format(self.statval, self.statname)
if self.fit_range is not None:
s += "\nFit Range: {}".format(self.fit_range)
s += "\n"
Expand Down
2 changes: 1 addition & 1 deletion gammapy/stats/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __str__(self):
self.background,
self.excess,
]
return "\n".join(["%s = %s" % (k, v) for (k, v) in zip(keys, values)])
return "\n".join(["{} = {}".format(k, v) for (k, v) in zip(keys, values)])


def make_stats(
Expand Down
6 changes: 3 additions & 3 deletions gammapy/stats/tests/test_feldman_cousins.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ def test_numerical_confidence_interval_values():
x_bins = np.linspace(-n_sigma * sigma, n_sigma * sigma, n_bins_x, endpoint=True)
mu_bins = np.linspace(mu_min, mu_max, mu_max / step_width_mu + 1, endpoint=True)

distribution_dict = dict(
(mu, [scipy.stats.norm.rvs(loc=mu, scale=sigma, size=5000)]) for mu in mu_bins
)
distribution_dict = {
mu: [scipy.stats.norm.rvs(loc=mu, scale=sigma, size=5000)] for mu in mu_bins
}

acceptance_intervals = fc_construct_acceptance_intervals(
distribution_dict, x_bins, cl
Expand Down
2 changes: 1 addition & 1 deletion gammapy/time/lightcurve.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def plot(self, ax=None, time_format="mjd", flux_unit="cm-2 s-1", **kwargs):

ax.errorbar(x=x, y=y, xerr=xerr, yerr=yerr, uplims=is_ul, **kwargs)
ax.set_xlabel("Time ({})".format(time_format.upper()))
ax.set_ylabel("Flux ({0:FITS})".format(u.Unit(flux_unit)))
ax.set_ylabel("Flux ({:FITS})".format(u.Unit(flux_unit)))
if time_format == "iso":
ax.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d %H:%M:%S"))
plt.setp(
Expand Down
2 changes: 1 addition & 1 deletion gammapy/utils/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def array_stats_str(x, label=""):

ss = ""
if label:
ss += "{0:15s}: ".format(label)
ss += "{:15s}: ".format(label)

min = x.min()
max = x.max()
Expand Down
2 changes: 1 addition & 1 deletion gammapy/utils/energy.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def equal_log_spacing(cls, emin, emax, nbins, unit=None):
unit : `~astropy.units.UnitBase`, str, None
Energy unit
"""
return super(EnergyBounds, cls).equal_log_spacing(emin, emax, nbins + 1, unit)
return super().equal_log_spacing(emin, emax, nbins + 1, unit)

@classmethod
def from_ebounds(cls, hdu):
Expand Down
4 changes: 2 additions & 2 deletions gammapy/utils/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def _unquantify_allclose_arguments(actual, desired, rtol, atol):
desired = desired.to(actual.unit)
except u.UnitsError:
raise u.UnitsError(
"Units for 'desired' ({0}) and 'actual' ({1}) "
"Units for 'desired' ({}) and 'actual' ({}) "
"are not convertible".format(desired.unit, actual.unit)
)

Expand All @@ -187,7 +187,7 @@ def _unquantify_allclose_arguments(actual, desired, rtol, atol):
atol = atol.to(actual.unit)
except u.UnitsError:
raise u.UnitsError(
"Units for 'atol' ({0}) and 'actual' ({1}) "
"Units for 'atol' ({}) and 'actual' ({}) "
"are not convertible".format(atol.unit, actual.unit)
)

Expand Down

0 comments on commit fdf4870

Please sign in to comment.