Skip to content

Commit

Permalink
Merge pull request #49 from PaulHancock/dev-codacy
Browse files Browse the repository at this point in the history
dev-codacy
  • Loading branch information
PaulHancock committed Jan 15, 2018
2 parents b80e70f + 5434ce4 commit 391a5ca
Show file tree
Hide file tree
Showing 18 changed files with 58 additions and 67 deletions.
2 changes: 1 addition & 1 deletion AegeanTools/BANE.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def sigmaclip(arr, lo, hi, reps=3):

std = np.std(clipped)
mean = np.mean(clipped)
for i in range(int(reps)):
for _ in range(int(reps)):
clipped = clipped[np.where(clipped > mean-std*lo)]
clipped = clipped[np.where(clipped < mean+std*hi)]
pstd = std
Expand Down
7 changes: 2 additions & 5 deletions AegeanTools/MIMAS.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@
"""
MIMAS - The Multi-resolution Image Mask for Aegean Software
Created: Paul Hancock, Oct 2014
TODO: Write an in/out reader for MOC formats described by
http://arxiv.org/abs/1505.02937
"""

import logging
Expand Down Expand Up @@ -174,9 +171,9 @@ def mask_file(regionfile, infile, outfile, negate=False):
:func:`AegeanTools.MIMAS.mask_plane`
"""
# Check that the input file is accessible and then open it
assert os.path.exists(infile), "Cannot locate fits file {0}".format(infile)
if not os.path.exists(infile): raise AssertionError("Cannot locate fits file {0}".format(infile))
im = pyfits.open(infile)
assert os.path.exists(regionfile), "Cannot locate region file {0}".format(regionfile)
if not os.path.exists(regionfile): raise AssertionError("Cannot locate region file {0}".format(regionfile))
region = cPickle.load(open(regionfile, 'rb'))
try:
wcs = pywcs.WCS(im[0].header, naxis=2)
Expand Down
7 changes: 2 additions & 5 deletions AegeanTools/catalogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
__date__ = "2016-07-26"

# Standard imports
import sys
import os
import numpy as np
import re
Expand All @@ -21,9 +20,7 @@
from .models import OutputSource, classify_catalog

# input/output table formats
import astropy
from astropy.table.table import Table
from astropy.table import Column
from astropy.io import ascii
from astropy.io import fits
from astropy.io.votable import from_table, parse_single_table
Expand Down Expand Up @@ -62,7 +59,7 @@ def check_table_formats(files):
cont = True
formats = get_table_formats()
for t in files.split(','):
name, ext = os.path.splitext(t)
_, ext = os.path.splitext(t)
ext = ext[1:].lower()
if ext not in formats:
cont = False
Expand Down Expand Up @@ -336,7 +333,7 @@ def table_to_source_list(table, src_type=OutputSource):
# copy the value to our object
val = row[param]
# hack around float32's broken-ness
if type(val) == np.float32:
if isinstance(val, np.float32):
val = np.float64(val)
setattr(src, param, val)
# save this object to our list of sources
Expand Down
11 changes: 6 additions & 5 deletions AegeanTools/fits_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def __init__(self, filename=None, hdu_index=0, beam=None, slice=None):
self.bscale = self._header["BSCALE"]
else:
self.bscale = 1

self.filename = filename
# fix possible problems with miriad generated fits files % HT John Morgan.
try:
Expand Down Expand Up @@ -242,7 +242,8 @@ def set_pixels(self, pixels):
-------
None
"""
assert pixels.shape == self._pixels.shape, "Shape mismatch between pixels supplied {0} and existing image pixels {1}".format(pixels.shape,self._pixels.shape)
if not (pixels.shape == self._pixels.shape):
raise AssertionError("Shape mismatch between pixels supplied {0} and existing image pixels {1}".format(pixels.shape,self._pixels.shape))
self._pixels = pixels
# reset this so that it is calculated next time the function is called
self._rms = None
Expand Down Expand Up @@ -319,7 +320,7 @@ def sky2pix(self, skypos):
"""
skybox = [skypos, skypos]
pixbox = self.wcs.all_world2pix(skybox, 1)
return [float(pixbox[0][0]), float(pixbox[0][1])]
return [float(pixbox[0][0]), float(pixbox[0][1])]


class Beam(object):
Expand All @@ -328,8 +329,8 @@ class Beam(object):
Properties are a,b,pa. No assumptions are made as to the units, but both a and b have to be >0.
"""
def __init__(self, a, b, pa, pixa=None, pixb=None):
assert a > 0, "major axis must be >0"
assert b > 0, "minor axis must be >0"
if not (a > 0): raise AssertionError("major axis must be >0")
if not (b > 0): raise AssertionError("minor axis must be >0")
self.a = a
self.b = b
self.pa = pa
Expand Down
26 changes: 13 additions & 13 deletions AegeanTools/fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ def hessian(pars, x, y):

if yo_var:
# H(amp,yo)/G = 1.0*(-sx**2*((x - xo)*sin(t) + (-y + yo)*cos(t))*cos(t) + sy**2*((x - xo)*cos(t) + (y - yo)*sin(t))*sin(t))/(amp*sx**2*sy**2)
hmat[j][k] = -(xsin - ycos)*cost/sy2 + (xcos + ysin)*sint/sx2
hmat[j][k] = -(xsin - ycos)*cost/sy2 + (xcos + ysin)*sint/sx2
hmat[j][k] *= model/amp
k += 1

Expand Down Expand Up @@ -1077,7 +1077,7 @@ def new_errors(source, model, wcshelper): # pragma: no cover
(a, b), e = np.linalg.eig(mat)
pa = np.degrees(np.arctan2(*e[0]))
# transform this ellipse into sky coordinates
ra, dec, major, minor, pa = wcshelper.pix2sky_ellipse([xo, yo], a, b, pa)
_, dec, major, minor, pa = wcshelper.pix2sky_ellipse([xo, yo], a, b, pa)

# now determine the radius of the ellipse along the ra/dec directions.
source.err_ra = major*minor / np.hypot(major*np.sin(np.radians(pa)), minor*np.cos(np.radians(pa)))
Expand Down Expand Up @@ -1255,15 +1255,15 @@ def covar_errors(params, data, errs, B, C=None):
J = lmfit_jacobian(params, mask[0], mask[1], errs=errs)
covar = np.transpose(J).dot(inv(C)).dot(J)
onesigma = np.sqrt(np.diag(inv(covar)))
except (np.linalg.linalg.LinAlgError, ValueError) as e:
except (np.linalg.linalg.LinAlgError, ValueError) as _:
C = None

if C is None:
try:
J = lmfit_jacobian(params, mask[0], mask[1], B=B, errs=errs)
covar = np.transpose(J).dot(J)
onesigma = np.sqrt(np.diag(inv(covar)))
except (np.linalg.linalg.LinAlgError, ValueError) as e:
except (np.linalg.linalg.LinAlgError, ValueError) as _:
onesigma = [-2] * len(mask[0])

for i in range(params['components'].value):
Expand Down Expand Up @@ -1357,18 +1357,18 @@ def test_hessian_plots():
kwargs = {"interpolation": "nearest", 'aspect': 1, 'vmin': -1, 'vmax': 1}
fig, ax = pyplot.subplots(6, 6, squeeze=True, sharex=True, sharey=True, figsize=(5, 6))
Hemp = emp_hessian(model, x, y)
vars = ['amp', 'xo', 'yo', 'sx', 'sy', 'theta']
params = ['amp', 'xo', 'yo', 'sx', 'sy', 'theta']
for i, row in enumerate(ax):
for j, ax in enumerate(row):
im = Hemp[i, j, :, :]
# im[np.where(abs(im) < 1e-5)] = 0
# print vars[i],vars[j], np.amax(im)
# print params[i],params[j], np.amax(im)
im /= np.amax(im)
ax.imshow(im, **kwargs)
if j == 0:
ax.set_ylabel(vars[i])
ax.set_ylabel(params[i])
if i == 5:
ax.set_xlabel(vars[j])
ax.set_xlabel(params[j])
clx(ax)
fig.suptitle('Empirical Hessian')

Expand All @@ -1379,13 +1379,13 @@ def test_hessian_plots():
for j, ax in enumerate(row):
im = Hana[i, j, :, :]
# im[np.where(abs(im) < 1e-5)] = 0
# print vars[i],vars[j], np.amax(im)
# print params[i],params[j], np.amax(im)
im /= np.amax(im)
ax.imshow(im, **kwargs)
if j == 0:
ax.set_ylabel(vars[i])
ax.set_ylabel(params[i])
if i == 5:
ax.set_xlabel(vars[j])
ax.set_xlabel(params[j])
clx(ax)
fig.suptitle('Analytical Hessian')

Expand All @@ -1400,9 +1400,9 @@ def test_hessian_plots():
im2 /= np.amax(im2)
ax.imshow(im1-im2, **kwargs)
if j == 0:
ax.set_ylabel(vars[i])
ax.set_ylabel(params[i])
if i == 5:
ax.set_xlabel(vars[j])
ax.set_xlabel(params[j])
clx(ax)
fig.suptitle('Difference')
pyplot.show()
Expand Down
2 changes: 1 addition & 1 deletion AegeanTools/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def _sanitise(self):
Convert attributes of type npumpy.float32 to numpy.float64 so that they will print properly.
"""
for k in self.__dict__:
if type(self.__dict__[k]) in [np.float32]: # np.float32 has a broken __str__ method
if isinstance(self.__dict__[k], np.float32): # np.float32 has a broken __str__ method
self.__dict__[k] = np.float64(self.__dict__[k])

def __str__(self):
Expand Down
6 changes: 3 additions & 3 deletions AegeanTools/msq2.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def find_start_point(self):
Find the first location in our array that is not empty
"""
for i, row in enumerate(self.data):
for j, col in enumerate(row):
for j, _ in enumerate(row):
if self.data[i, j] != 0: # or not np.isfinite(self.data[i,j]):
return i, j

Expand Down Expand Up @@ -213,7 +213,7 @@ def do_march_all(self):
"""
# copy the data since we are going to be modifying it
data_copy = copy(self.data)

# iterate through finding an island, creating a perimeter,
# and then blanking the island
perimeters = []
Expand All @@ -225,6 +225,6 @@ def do_march_all(self):
self._blank_within(perim)
p = self.find_start_point()

# restore the data
# restore the data
self.data = data_copy
return perimeters
11 changes: 5 additions & 6 deletions AegeanTools/regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def add_poly(self, positions, depth=None):
depth : int
The deepth at which the polygon will be inserted.
"""
assert len(positions) >= 3, "A minimum of three coordinate pairs are required"
if not (len(positions) >= 3): raise AssertionError("A minimum of three coordinate pairs are required")

if depth is None or depth > self.maxdepth:
depth = self.maxdepth
Expand All @@ -109,7 +109,6 @@ def add_pixels(self, pix, depth):
if depth not in self.pixeldict:
self.pixeldict[depth] = set()
self.pixeldict[depth].update(set(pix))
pass

def get_area(self, degrees=True):
"""
Expand Down Expand Up @@ -259,7 +258,7 @@ def without(self, other):
"""
# work only on the lowest level
# TODO: Allow this to be done for regions with different depths.
assert self.maxdepth == other.maxdepth, "Regions must have the same maxdepth"
if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth")
self._demote_all()
opd = set(other.get_demoted())
self.pixeldict[self.maxdepth].difference_update(opd)
Expand All @@ -279,7 +278,7 @@ def intersect(self, other):
"""
# work only on the lowest level
# TODO: Allow this to be done for regions with different depths.
assert self.maxdepth == other.maxdepth, "Regions must have the same maxdepth"
if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth")
self._demote_all()
opd = set(other.get_demoted())
self.pixeldict[self.maxdepth].intersection_update(opd)
Expand All @@ -299,7 +298,7 @@ def symmetric_difference(self, other):
"""
# work only on the lowest level
# TODO: Allow this to be done for regions with different depths.
assert self.maxdepth == other.maxdepth, "Regions must have the same maxdepth"
if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth")
self._demote_all()
opd = set(other.get_demoted())
self.pixeldict[self.maxdepth].symmetric_difference_update(opd)
Expand Down Expand Up @@ -420,7 +419,7 @@ def sky2ang(sky):
"""
try:
theta_phi = sky.copy()
except AttributeError as e:
except AttributeError as _:
theta_phi = np.array(sky)
theta_phi[:, [1, 0]] = theta_phi[:, [0, 1]]
theta_phi[:, 0] = np.pi/2 - theta_phi[:, 0]
Expand Down
6 changes: 3 additions & 3 deletions AegeanTools/source_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -1466,7 +1466,7 @@ def find_sources_in_image(self, filename, hdu_index=0, outfile=None, rms=None, m
# Tell numpy to be quiet
np.seterr(invalid='ignore')
if cores is not None:
assert (cores >= 1), "cores must be one or more"
if not (cores >= 1): raise AssertionError("cores must be one or more")

self.load_globals(filename, hdu_index=hdu_index, bkgin=bkgin, rmsin=rmsin, beam=beam, rms=rms, cores=cores,
verb=True, mask=mask, lat=lat, psf=imgpsf, blank=blank, docov=docov, slice=slice)
Expand Down Expand Up @@ -1732,7 +1732,7 @@ def priorized_fit_islands(self, filename, catalogue, hdu_index=0, outfile=None,

components = 0
for source in sources:
if type(source) == OutputSource:
if isinstance(source, OutputSource):
components += 1
if outfile:
print(str(source), file=outfile)
Expand Down Expand Up @@ -1885,7 +1885,7 @@ def check_cores(cores):
cores = 1
else:
try:
temp = queue.manage(pprocess.MakeReusable(fix_shape))
_ = queue.manage(pprocess.MakeReusable(fix_shape))
except:
cores = 1
return cores
Expand Down
1 change: 0 additions & 1 deletion AegeanTools/wcs_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from .fits_image import Beam, get_beam, get_pixinfo

# the glory of astropy
import astropy
import astropy.wcs as pywcs
from astropy.io import fits

Expand Down
2 changes: 0 additions & 2 deletions tests/test_BANE.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
from __future__ import print_function

from AegeanTools import BANE
from AegeanTools import fits_interp
from astropy.io import fits
import numpy as np
import os

Expand Down
4 changes: 2 additions & 2 deletions tests/test_cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from AegeanTools import cluster
from AegeanTools.models import SimpleSource
from copy import deepcopy, copy
from copy import deepcopy
import math
import numpy as np

Expand Down Expand Up @@ -65,7 +65,7 @@ def test_regroup():
# this should throw an attribute error
try:
cluster.regroup([1], eps=1)
except AttributeError as e:
except AttributeError as _:
pass

# this should result in 51 groups
Expand Down
10 changes: 5 additions & 5 deletions tests/test_fits_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,25 +64,25 @@ def test_get_beam():
def test_fix_aips_header():
header = fits.getheader('tests/test_files/1904-66_SIN.fits')
# test when this function is not needed
newhead = fi.fix_aips_header(header)
_ = fi.fix_aips_header(header)

# test when beam params are not present, but there is no aips history
del header['BMAJ'], header['BMIN'], header['BPA']
newhead = fi.fix_aips_header(header)
_ = fi.fix_aips_header(header)

# test with some aips history
header['HISTORY'] = 'AIPS CLEAN BMAJ= 1.2500E-02 BMIN= 1.2500E-02 BPA= 0.00'
newhead = fi.fix_aips_header(header)
_ = fi.fix_aips_header(header)


def test_init():
filename = 'tests/test_files/1904-66_SIN.fits'
# normal invocation
im = fi.FitsImage(filename)
_ = fi.FitsImage(filename)

# call with an already opened hdu instead of a file name
hdu = fits.open(filename)
im = fi.FitsImage(hdu)
_ = fi.FitsImage(hdu)

# set bzero/bscale
hdu[0].header['BZERO'] = 1
Expand Down

0 comments on commit 391a5ca

Please sign in to comment.