Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python 2 / 3 compatibility with a single codebase #109

Merged
merged 4 commits into from Apr 28, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions gammapy/background/ring.py
Expand Up @@ -36,11 +36,11 @@ def __init__(self, r_in, r_out, pixscale=0.01):
def info(self):
"""Print some basic parameter info."""
print('RingBgMaker parameters:')
print('r_in: %g pix = %g deg'.format(
print('r_in: {0} pix = {1} deg'.format(
(self.r_in, self.r_in * self.pixscale)))
print('r_out: %g pix = %g deg'.format(
print('r_out: {0} pix = {1} deg'.format(
(self.r_out, self.r_out * self.pixscale)))
print('pixscale: %g deg/pix'.format(self.pixscale))
print('pixscale: {0} deg/pix'.format(self.pixscale))
print()

def correlate(self, image):
Expand Down
2 changes: 1 addition & 1 deletion gammapy/detect/cwt.py
Expand Up @@ -117,7 +117,7 @@ def do_transform(self):
from scipy.signal import fftconvolve
total_background = self.model + self.background + self.approx
excess = self.image - total_background
for key, kern in self.kernbase.iteritems(): # works for python < 3
for key, kern in self.kernbase.items():
self.transform[key] = fftconvolve(excess, kern, mode='same')
self.error[key] = np.sqrt(fftconvolve(total_background, kern ** 2, mode='same'))

Expand Down
2 changes: 1 addition & 1 deletion gammapy/image/utils.py
Expand Up @@ -646,7 +646,7 @@ def make_header(nxpix=100, nypix=100, binsz=0.1, xref=0, yref=0,
elif coordsys == 'GAL':
ctype1, ctype2 = 'GLON-', 'GLAT-'
else:
raise Exception('Unsupported coordsys: %s' % proj)
raise Exception('Unsupported coordsys: {0}'.format(proj))

pars = {'NAXIS': 2, 'NAXIS1': nxpix, 'NAXIS2': nypix,
'CTYPE1': ctype1 + proj,
Expand Down
2 changes: 1 addition & 1 deletion gammapy/morphology/gauss.py
Expand Up @@ -300,7 +300,7 @@ def gaussian_sum_moments(F, sigma, x, y, cov_matrix, shift=0.5):
parameter_list = uncertainties.correlated_values(values, cov_matrix)

# Reorder parameters by splitting into 4-tuples
parameters = zip(*[iter(parameter_list)] * 4)
parameters = list(zip(*[iter(parameter_list)] * 4))

def zero_moment(parameters):
"""0th moment of the sum of Gaussian components."""
Expand Down
15 changes: 8 additions & 7 deletions gammapy/morphology/psf.py
Expand Up @@ -182,8 +182,8 @@ def dpdtheta2(self, theta2):
theta2 = np.asarray(theta2, 'f')
total = np.zeros_like(theta2)
for ii in range(1, self.n_gauss() + 1):
A = self.pars['A_%d' % ii]
sigma = self.pars['sigma_%d' % ii]
A = self.pars['A_{0}'.format(ii)]
sigma = self.pars['sigma_{0}'.format(ii)]
total += A * exp(-theta2 / (2 * sigma ** 2))
return self.pars['scale'] * total

Expand All @@ -210,11 +210,11 @@ def to_sherpa(self, binsz):
# scale = self.pars['scale']
for ii in range(1, self.n_gauss() + 1):
d = {}
A = self.pars['A_%d' % ii]
sigma = self.pars['sigma_%d' % ii]
A = self.pars['A_{0}'.format(ii)]
sigma = self.pars['sigma_{0}'.format(ii)]
d['ampl'] = A
d['fwhm'] = sigma_to_fwhm * sigma / binsz
name = 'psf%d' % ii
name = 'psf{0}'.format(ii)
pars[name] = d
return pars

Expand All @@ -228,7 +228,7 @@ def to_file(self, filename, binsz, fmt='json'):
elif fmt == 'ascii':
fh = open(filename, 'w')
for name, value in self.pars.items():
fh.write('%s %s\n' % (name, value))
fh.write('{0} {1}\n'.format(name, value))
fh.close()

def to_MultiGauss2D(self, normalize=True):
Expand All @@ -239,7 +239,8 @@ def to_MultiGauss2D(self, normalize=True):
represents the amplitude at 0."""
sigmas, norms = [], []
for ii in range(1, self.n_gauss() + 1):
A, sigma = self.pars['A_%d' % ii], self.pars['sigma_%d' % ii]
A = self.pars['A_{0}'.format(ii)]
sigma = self.pars['sigma_{0}'.format(ii)]
norm = self.pars['scale'] * 2 * A * sigma ** 2
sigmas.append(sigma)
norms.append(norm)
Expand Down
6 changes: 3 additions & 3 deletions gammapy/morphology/tests/test_psf.py
Expand Up @@ -74,9 +74,9 @@ def test_GC(self):

def test_multi_gauss_psf_kernel():

psf_data = {u'psf1': {u'ampl': 1, u'fwhm': 2.5496814916215014},
u'psf2': {u'ampl': 0.062025099992752075, u'fwhm': 11.149272133127273},
u'psf3': {u'ampl': 0.47460201382637024, u'fwhm': 5.164014607542117}}
psf_data = {'psf1': {'ampl': 1, 'fwhm': 2.5496814916215014},
'psf2': {'ampl': 0.062025099992752075, 'fwhm': 11.149272133127273},
'psf3': {'ampl': 0.47460201382637024, 'fwhm': 5.164014607542117}}
psf_kernel = multi_gauss_psf_kernel(psf_data, x_size=51)

assert_allclose(psf_kernel.array[25, 25], 0.05047558713797154)
Expand Down
16 changes: 2 additions & 14 deletions gammapy/morphology/tests/test_theta.py
Expand Up @@ -74,17 +74,5 @@ def _test_ModelThetaCalculator():
par_names = ['angle', 'containment']
par_refs = [ana_angle, ana_containment]
par_checks = [num_angle, num_containment]
compare_results(par_names, par_refs, par_checks)


def compare_results(names, refs, checks):
print('%10s %10s %10s %10s'
''.format('name ref check rel_diff'.split()))
for name, ref, check in zip(names, refs, checks):
abs_diff = check - ref
rel_diff = 100 * abs_diff / ref
print('%10s %10.3g %10.3g %10.3f'
''.format(name, ref, check, rel_diff))

if __name__ == '__main__':
unittest.main()

# TODO: add asserts
4 changes: 2 additions & 2 deletions gammapy/morphology/utils.py
Expand Up @@ -8,7 +8,7 @@

def _name(ii):
"""Use this to make the model name for source number `ii`."""
return 'gauss2d.source_%02d' % ii
return 'gauss2d.source_{0:02d}'.format(ii)


def _set(name, par, val):
Expand Down Expand Up @@ -73,7 +73,7 @@ def write_ascii(pars, filename):
"""Write to ASCII"""
fh = open(filename, 'w')
for par in pars:
fh.write('%s %s %s\n' % (par.modelname, par.name, par.val))
fh.write('{0} {1} {2}\n'.format(par.modelname, par.name, par.val))


def write_all(filename='results.json'):
Expand Down
2 changes: 1 addition & 1 deletion gammapy/spectrum/crab.py
Expand Up @@ -87,7 +87,7 @@ def crab_flux(energy=1, reference=CRAB_DEFAULT_REFERENCE):
flux = 10 ** log_flux
return Unit('erg').to('TeV') * flux / energy ** 2
else:
raise ValueError('Unknown reference: %s' % reference)
raise ValueError('Unknown reference: {0}'.format(reference))


def crab_integral_flux(energy_min=1, energy_max=1e4, reference=CRAB_DEFAULT_REFERENCE):
Expand Down
30 changes: 15 additions & 15 deletions gammapy/spectrum/fitter.py
Expand Up @@ -77,23 +77,23 @@ def __str__(self):
npoints = len(self.chi)
npar = len(self.popt)
ndof = npoints - npar
s = 'sym_fit: %s\n' % self.sym
s += 'npar: %s\n' % npar
s += 'npoints: %s\n' % npoints
s += 'ndof: %s\n' % ndof
s += 'chi2: %s\n' % self.chi2()
s += 'chi2/ndof: %s\n' % (self.chi2() / ndof)
s += 'popt:\n%s\n' % self.popt
s += 'pcov:\n%s\n' % self.pcov
s = 'sym_fit: {0}\n'.format(self.sym)
s += 'npar: {0}\n'.format(npar)
s += 'npoints: {0}\n'.format(npoints)
s += 'ndof: {0}\n'.format(ndof)
s += 'chi2: {0}\n'.format(self.chi2())
s += 'chi2/ndof: {0}\n'.format(self.chi2() / ndof)
s += 'popt:\n{0}\n'.format(self.popt)
s += 'pcov:\n{0}\n'.format(self.pcov)
for i in range(len(self.popt)):
s += ('Parameter %d: %15g +/- %15g\n'
% (i, self.popt[i], np.sqrt(self.pcov[i, i])))
s += 'status: %s\n' % self.status
s += 'nfev: %s\n' % self.infodict['nfev']
s += 'chi:\n%s\n' % self.chi
fmt = 'Parameter {0}: {1:15g} +/- {2:15g}\n'
s += (fmt.format(i, self.popt[i], np.sqrt(self.pcov[i, i])))
s += 'status: {0}\n'.format(self.status)
s += 'nfev: {0}\n'.format(self.infodict['nfev'])
s += 'chi:\n{0}\n'.format(self.chi)

# s += 'infodict:\n%s\n' % self.infodict
# s += 'mesg: \n%s' % self.mesg
# s += 'infodict:\n{0}\n'.format(self.infodict)
# s += 'mesg: \n{0}'.format(self.mesg)
except AttributeError:
s = 'Not fitted.'
return s
Expand Down
4 changes: 2 additions & 2 deletions gammapy/spectrum/flux_point.py
Expand Up @@ -36,10 +36,10 @@ def __init__(self, model=None,
model = PowerLaw()
self.model = model
if not xmethod in self.xmethods:
raise('Unknown xmethod: %s' % xmethod)
raise ValueError('Unknown xmethod: {0}'.format(xmethod))
self.xmethod = xmethod
if not ymethod in self.ymethods:
raise('Unknown ymethod: %s' % ymethod)
raise ValueError('Unknown ymethod: {0}'.format(ymethod))
self.ymethod = ymethod

def calc_xy(self, yint, xmin, xmax):
Expand Down
8 changes: 4 additions & 4 deletions gammapy/spectrum/models.py
Expand Up @@ -150,14 +150,14 @@ class AnalyticModel(Model):
"""Spectrum represented by an analytic function."""

def __str__(self):
s = '%s\n' % self.__class__.__name__
s = '{0}\n'.format(self.__class__.__name__)
for par in self.pars:
if par.vary:
err = '+/- %.3e' % par.stderr
err = '+/- {0:.3e}'.format(par.stderr)
else:
err = ' (fixed)'
s += ('%20s = %.3e %s\n' %
(par.name, par.value, err))
fmt = '{0:20s} = {1:.3e} {2}\n'
s += (fmt.format(par.name, par.value, err))
return s

def error(self, E):
Expand Down
8 changes: 4 additions & 4 deletions gammapy/spectrum/sed.py
Expand Up @@ -34,15 +34,15 @@ def plot(self, model=True, points=True, butterfly=True):
def plot_model(self):
import matplotlib.pyplot as plt
if self.model is None:
logging.warning('%s: No model available.' % self.name)
logging.warning('{0}: No model available.'.format(self.name))
return
x, y = self.model.points(power=2)
plt.plot(x * MeV_to_GeV, y * MeV_to_erg, label=self.name)

def plot_points(self, color='black', markerfacecolor='black'):
import matplotlib.pyplot as plt
if self.points is None:
logging.warning('%s: No points available.' % self.name)
logging.warning('{0}: No points available.'.format(self.name))
return
# @note We plot each point individually because anyway
# upper limits have to be plotted differently which I
Expand Down Expand Up @@ -104,13 +104,13 @@ def plot(self, filename='sed.png', xlim=(8e-2, 2e5), ylim=(1e-14, 1e-8)):
plt.ylabel(r'E$^2$ dF/DE (erg cm$^{-2}$ s$^{-1}$)')
plt.xlabel('Energy (GeV)')
plt.loglog()
logging.info('Plotting %s components in SED' % len(self))
logging.info('Plotting {0} components in SED'.format(len(self)))
for component in self:
component.plot()
plt.xlim(xlim)
plt.ylim(ylim)
plt.legend()
logging.info('Writing %s' % filename)
logging.info('Writing {0}'.format(filename))
plt.savefig(filename)

def add_component(self, catalog_format, catalog_name,
Expand Down
3 changes: 1 addition & 2 deletions gammapy/spectrum/tests/test_powerlaw.py
Expand Up @@ -144,12 +144,11 @@ def test_SED_error(I=1., e1=1, e2=10):
e = gmean([e1, e2])
f = I / (e2 - e1)
e2f = e ** 2 * f # @note: e ** 2 = e1 * e2 here.
print('%10s %10s %10s' % ('Index', 'SED', 'Flux'))
for Index in np.arange(1.5, 3.5, 0.5):
f_correct = powerlaw.power_law_flux(I, Index, e, e1, e2)
e2f_correct = e ** 2 * f_correct
# We compute ratios, which corresponds to differences
# on a log scale
SED = e2f / e2f_correct
Flux = f / f_correct
print('%10.1f %10.2f %10.2f' % (Index, SED, Flux))
# TODO: assert results
6 changes: 3 additions & 3 deletions gammapy/stats/poisson.py
Expand Up @@ -223,7 +223,7 @@ def significance(n_observed, mu_background, method='lima'):
elif method == 'direct':
return _significance_direct(n_observed, mu_background)
else:
raise Exception('Invalid method: %s' % method)
raise ValueError('Invalid method: {0}'.format(method))


def _significance_simple(n_observed, mu_background):
Expand Down Expand Up @@ -322,7 +322,7 @@ def significance_on_off(n_on, n_off, alpha, method='lima',
else:
return _significance_direct_on_off(n_on, n_off, alpha)
else:
raise Exception('Invalid method: %s' % method)
raise ValueError('Invalid method: {0}'.format(method))


def _significance_simple_on_off(n_on, n_off, alpha):
Expand Down Expand Up @@ -428,7 +428,7 @@ def sensitivity(mu_background, significance, quantity='excess', method='lima'):
elif method == 'lima':
return _sensitivity_lima(mu_background, significance)
else:
raise Exception('Invalid method: %s' % method)
raise ValueError('Invalid method: {0}'.format(method))


def _sensitivity_simple(mu_background, significance):
Expand Down
4 changes: 2 additions & 2 deletions gammapy/stats/tests/test_fit_statistics.py
Expand Up @@ -6,8 +6,8 @@


def print_info(label, data):
print('*** %s ***' % label)
print('Sum: %g' % data.sum())
print('*** {0} ***'.format(label))
print('Sum: {0:g}'.format(data.sum()))
print(data)


Expand Down
12 changes: 2 additions & 10 deletions gammapy/utils/distributions/general_random.py
@@ -1,5 +1,6 @@
from __future__ import print_function, division
import numpy as np
from astropy.extern.six.moves import range

__all__ = ['GeneralRandom']

Expand Down Expand Up @@ -62,7 +63,7 @@ def __init__(self, pdf, min_range, max_range,
self.inversecdf = np.empty(ninversecdf)
self.inversecdf[0] = self.x[0]
cdf_idx = 0
for n in xrange(1, self.ninversecdf):
for n in range(1, self.ninversecdf):
while self.cdf[cdf_idx] < y[n] and cdf_idx < ninversecdf:
cdf_idx += 1
self.inversecdf[n] = self.x[cdf_idx - 1] + \
Expand Down Expand Up @@ -90,15 +91,6 @@ def draw(self, N=1000):
x = self.inversecdf[idx] + (idx_f - idx) * self.delta_inversecdf[idx]
return x

def info(self):
"""Print the internal state"""
print('%15s:' % 'x', self.x)
print('%15s:' % 'pdf', self.pdf)
print('%15s:' % 'cdf', self.cdf)
print('%15s:' % 'ninversecdf', self.ninversecdf)
print('%15s:' % 'inversecdf', self.inversecdf)
print('%15s:' % 'delta_inversecdf', self.delta_inversecdf)

def make_plots(self, N=1e5):
"""Plot the pdf, cdf and inversecdf
and a random distribution of sample size N.
Expand Down
4 changes: 2 additions & 2 deletions gammapy/utils/pyfact.py
Expand Up @@ -1299,7 +1299,7 @@ def get_evl(file_name) :
}
outfile_base_name = unique_base_file_name(outfile_base_name, outfile_data.keys())

for ext, data in outfile_data.iteritems() :
for ext, data in outfile_data.items() :
image_to_primaryhdu(data, rarange, decrange, author='PyFACT pfmap',
object_=object_, telescope=telescope).writeto(outfile_base_name + ext)

Expand All @@ -1318,7 +1318,7 @@ def get_evl(file_name) :
}
outfile_base_name = unique_base_file_name(outfile_base_name, outfile_data.keys())

for ext, data in outfile_data.iteritems() :
for ext, data in outfile_data.items() :
image_to_primaryhdu(data, rarange, decrange, author='PyFACT pfmap',
object_=object_, telescope=telescope).writeto(outfile_base_name + ext)

Expand Down
4 changes: 2 additions & 2 deletions gammapy/utils/region.py
Expand Up @@ -25,7 +25,7 @@ def write(x=0, y=0, radius=1, system='galactic',
for key, val in attrs.items():
if isinstance(val, str): # and ' ' in val:
val = '{{%s}}' % val
string += ' %s=%s' % (key, val)
string += ' {0}={1}'.format(key, val)
string += '\n'
return string.format(**locals())

Expand Down Expand Up @@ -131,6 +131,6 @@ def _region_string(shape, pars, attrs, system='galactic'):
for key, val in attrs.items():
if isinstance(val, str): # and ' ' in val:
val = '{{%s}}' % val
string += ' %s=%s' % (key, val)
string += ' {0}={1}'.format(key, val)
string += '\n'
return string.format(**locals())
2 changes: 1 addition & 1 deletion gammapy/utils/root/tests/test_convert.py
Expand Up @@ -70,5 +70,5 @@ def test_TH2_to_FITS():
from pprint import pprint
pprint(f.header2classic())
filename = 'TH2_to_FITS.fits'
print('Writing %s' % filename)
print('Writing {0}'.format(filename))
f.writetofits(filename, clobber=True)
2 changes: 1 addition & 1 deletion setup.py
Expand Up @@ -122,5 +122,5 @@
],
cmdclass=cmdclassd,
zip_safe=False,
use_2to3=True
use_2to3=False
)