Skip to content

Commit 1b25497

Browse files
committed
Code lint updates
1 parent 6d8de16 commit 1b25497

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+577
-516
lines changed

spectral/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
Basic package setup and global imports.
33
'''
44

5+
# flake8: noqa
6+
57
from __future__ import absolute_import, division, print_function, unicode_literals
68

79
__version__ = '0.23.1'

spectral/algorithms/__init__.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
# flake8: noqa
2+
13
from __future__ import absolute_import, division, print_function, unicode_literals
24

35
from .algorithms import (mean_cov, covariance, principal_components, bdist,
4-
linear_discriminant, create_training_classes, ndvi,
5-
orthogonalize, transform_image, unmix, spectral_angles,
6-
calc_stats, cov_avg, msam, noise_from_diffs, mnf,
7-
GaussianStats, ppi, smacc)
6+
linear_discriminant, create_training_classes, ndvi,
7+
orthogonalize, transform_image, unmix, spectral_angles,
8+
calc_stats, cov_avg, msam, noise_from_diffs, mnf,
9+
GaussianStats, ppi, smacc)
810
from .classifiers import *
911
from .clustering import L1, L2, kmeans
1012
from .resampling import BandResampler

spectral/algorithms/algorithms.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from .spymath import matrix_sqrt
1616
from .transforms import LinearTransform
1717

18+
1819
class Iterator:
1920
'''
2021
Base class for iterators over pixels (spectra).
@@ -50,7 +51,6 @@ def get_num_bands(self):
5051

5152
def __iter__(self):
5253
(M, N) = self.image.shape[:2]
53-
count = 0
5454
for i in range(M):
5555
self.row = i
5656
for j in range(N):
@@ -86,6 +86,7 @@ def __iter__(self):
8686
(self.row, self.col) = (i, j)
8787
yield self.image[i, j].astype(self.image.dtype).squeeze()
8888

89+
8990
def iterator(image, mask=None, index=None):
9091
'''
9192
Returns an iterator over pixels in the image.
@@ -292,6 +293,7 @@ def cov_avg(image, mask, weighted=True):
292293
else:
293294
return np.mean([c.cov for c in classes], axis=0, dtype=np.float64)
294295

296+
295297
def covariance(*args):
296298
'''
297299
Returns the covariance of the set of vectors.
@@ -641,7 +643,6 @@ class covariances, mean vector, and a callable transform to convert data to
641643
Richards, J.A. & Jia, X. Remote Sensing Digital Image Analysis: An
642644
Introduction. (Springer: Berlin, 1999).
643645
'''
644-
C = len(classes) # Number of training sets
645646
rank = len(classes) - 1
646647

647648
classes.calc_stats()
@@ -677,13 +678,13 @@ class covariances, mean vector, and a callable transform to convert data to
677678

678679
return FisherLinearDiscriminant(vals.real, vecs.real, mean, cov_b, cov_w)
679680

681+
680682
# Alias for Linear Discriminant Analysis (LDA)
681683
lda = linear_discriminant
682684

683685

684686
def log_det(x):
685-
return sum(np.log([eigv for eigv in np.linalg.eigvals(x)
686-
if eigv > 0]))
687+
return sum(np.log([eigv for eigv in np.linalg.eigvals(x) if eigv > 0]))
687688

688689

689690
class GaussianStats(object):
@@ -933,7 +934,6 @@ def size(self):
933934
else:
934935
return np.sum(np.not_equal(self.mask, 0).ravel())
935936

936-
937937
def calc_stats(self):
938938
'''
939939
Calculates statistics for the class.
@@ -1050,13 +1050,13 @@ def calc_stats(self):
10501050
def save(self, filename, calc_stats=False):
10511051
for c in list(self.classes.values()):
10521052
if c.stats is None:
1053-
if calc_stats == False:
1053+
if calc_stats is False:
10541054
msg = 'Class statistics are missing from at least one ' \
10551055
'class and are required to save the training class ' \
10561056
'data. Call the `save` method with keyword ' \
10571057
'`calc_stats=True` if you want to compute them and ' \
10581058
'then save the class data.'
1059-
raise Exception (msg)
1059+
raise Exception(msg)
10601060
else:
10611061
c.calc_stats()
10621062
f = open(filename, 'wb')
@@ -1195,6 +1195,7 @@ def bdist(class1, class2):
11951195
terms = bdist_terms(class1, class2)
11961196
return terms[0] + terms[1]
11971197

1198+
11981199
bDistance = bdist
11991200

12001201

@@ -1364,6 +1365,7 @@ def spectral_angles(data, members):
13641365
dots = np.clip(dots / norms[:, :, np.newaxis], -1, 1)
13651366
return np.arccos(dots)
13661367

1368+
13671369
def msam(data, members):
13681370
'''Modified SAM scores according to Oshigami, et al [1]. Endmembers are
13691371
mean-subtracted prior to spectral angle calculation. Results are
@@ -1417,17 +1419,18 @@ def msam(data, members):
14171419

14181420
for i in range(M):
14191421
for j in range(N):
1420-
#Fisher z trafo type operation
1422+
# Fisher z trafo type operation
14211423
v = data[i, j] - np.mean(data[i, j])
14221424
v /= np.sqrt(v.dot(v))
14231425
v = np.clip(v, -1, 1)
14241426
for k in range(C):
14251427
# Calculate Mineral Index according to Oshigami et al.
14261428
# (Intnl. J. of Remote Sens. 2013)
14271429
a = np.clip(v.dot(m[k]), -1, 1)
1428-
angles[i,j,k]= 1.0 - np.arccos(a) / (math.pi / 2)
1430+
angles[i, j, k] = 1.0 - np.arccos(a) / (math.pi / 2)
14291431
return angles
14301432

1433+
14311434
def noise_from_diffs(X, direction='lowerright'):
14321435
'''Estimates noise statistcs by taking differences of adjacent pixels.
14331436
@@ -1469,6 +1472,7 @@ def noise_from_diffs(X, direction='lowerright'):
14691472
stats.cov /= 2.0
14701473
return stats
14711474

1475+
14721476
class MNFResult(object):
14731477
'''Result object returned by :func:`~spectral.algorithms.algorithms.mnf`.
14741478
@@ -1504,7 +1508,7 @@ def _num_from_kwargs(self, **kwargs):
15041508
raise Exception('Keyword not recognized.')
15051509
num = kwargs.get('num', None)
15061510
snr = kwargs.get('snr', None)
1507-
if num == snr == None:
1511+
if num == snr is None:
15081512
raise Exception('Must specify either `num` or `snr` keyword.')
15091513
if None not in (num, snr):
15101514
raise Exception('Can not specify both `num` and `snr` keywords.')
@@ -1563,8 +1567,8 @@ def get_denoising_transform(self, **kwargs):
15631567
V = self.napc.eigenvectors
15641568
Vr = np.array(V)
15651569
Vr[:, N:] = 0.
1566-
f = LinearTransform(self.noise.sqrt_cov.dot(Vr).dot(V.T) \
1567-
.dot(self.noise.sqrt_inv_cov),
1570+
f = LinearTransform(self.noise.sqrt_cov.dot(Vr).dot(V.T)
1571+
.dot(self.noise.sqrt_inv_cov),
15681572
pre=-self.signal.mean,
15691573
post=self.signal.mean)
15701574
return f
@@ -1626,6 +1630,7 @@ def num_with_snr(self, snr):
16261630
'''Returns the number of components with SNR >= `snr`.'''
16271631
return np.sum(self.napc.eigenvalues >= (snr + 1))
16281632

1633+
16291634
def mnf(signal, noise):
16301635
'''Computes Minimum Noise Fraction / Noise-Adjusted Principal Components.
16311636
@@ -1686,6 +1691,7 @@ def mnf(signal, noise):
16861691
napc = PrincipalComponents(L, V, wstats)
16871692
return MNFResult(signal, noise, napc)
16881693

1694+
16891695
def ppi(X, niters, threshold=0, centered=False, start=None, display=0,
16901696
**imshow_kwargs):
16911697
'''Returns pixel purity indices for an image.
@@ -1759,7 +1765,7 @@ def ppi(X, niters, threshold=0, centered=False, start=None, display=0,
17591765
'''
17601766
if display is not None:
17611767
if not isinstance(display, Integral) or isinstance(display, bool) or \
1762-
display < 0:
1768+
display < 0:
17631769
msg = '`display` argument must be a non-negative integer.'
17641770
raise ValueError(msg)
17651771

@@ -1941,7 +1947,7 @@ def smacc(spectra, min_endmembers=None, max_residual_norm=float('Inf')):
19411947
residual_norms[:] = np.sqrt(np.einsum('ij,ij->i', R, R))
19421948
current_max_residual_norm = np.max(residual_norms)
19431949
print('Found {0} endmembers, current max residual norm is {1:.4f}\r'
1944-
.format(len(q), current_max_residual_norm), end='')
1950+
.format(len(q), current_max_residual_norm), end='')
19451951

19461952
# Correction as suggested in the SMACC paper.
19471953
for k, s in enumerate(q):

spectral/algorithms/classifiers.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@
88
import math
99
import numpy as np
1010

11-
from warnings import warn
12-
1311
import spectral as spy
1412
from .algorithms import GaussianStats, ImageIterator
1513
from .detectors import RX
@@ -18,6 +16,7 @@
1816
__all__ = ('GaussianClassifier', 'MahalanobisDistanceClassifier',
1917
'PerceptronClassifier')
2018

19+
2120
class Classifier(object):
2221
'''
2322
Base class for Classifiers. Child classes must implement the
@@ -149,9 +148,9 @@ def classify_spectrum(self, x):
149148
for (i, cl) in enumerate(self.classes):
150149
delta = (x - cl.stats.mean)
151150
scores[i] = math.log(cl.class_prob) - 0.5 * cl.stats.log_det_cov \
152-
- 0.5 * delta.dot(cl.stats.inv_cov).dot(delta)
151+
- 0.5 * delta.dot(cl.stats.inv_cov).dot(delta)
153152
return self.classes[np.argmax(scores)].index
154-
153+
155154
def classify_image(self, image):
156155
'''Classifies an entire image, returning a classification map.
157156
@@ -301,7 +300,7 @@ class PerceptronClassifier(Perceptron, SupervisedClassifier):
301300
>>> classes = create_training_classes(xdata, gt)
302301
>>> nfeatures = xdata.shape[-1]
303302
>>> nclasses = len(classes)
304-
>>>
303+
>>>
305304
>>> p = PerceptronClassifier([nfeatures, 20, 8, nclasses])
306305
>>> p.train(classes, 20, clip=0., accuracy=100., batch=1,
307306
>>> momentum=0.3, rate=0.3)
@@ -407,8 +406,8 @@ class in `training_data`. If this argument is not provided,
407406
if class_data[i].shape[0] > samples_per_class:
408407
class_data[i] = class_data[i][:samples_per_class]
409408
X = np.vstack(class_data)
410-
y = np.hstack([np.ones(c.shape[0], dtype=np.int16) * i for \
411-
(i, c) in enumerate(class_data)])
409+
y = np.hstack([np.ones(c.shape[0], dtype=np.int16) * i for
410+
(i, c) in enumerate(class_data)])
412411
Y = np.eye(np.max(y) + 1, dtype=np.int16)[y]
413412

414413
if 'stdout' in kwargs:
@@ -441,4 +440,3 @@ def classify_spectrum(self, x):
441440

442441
def classify(self, X, **kwargs):
443442
return Classifier.classify(self, X, **kwargs)
444-

spectral/algorithms/clustering.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@
88
import numpy as np
99

1010
import spectral as spy
11-
from .classifiers import Classifier
1211
from ..utilities.errors import has_nan, NaNValueError
1312

13+
1414
def L1(v1, v2):
1515
'Returns L1 distance between 2 rank-1 arrays.'
1616
return np.sum(abs((v1 - v2)))
@@ -360,4 +360,3 @@ def kmeans_ndarray(image, nclusters=10, max_iterations=20, **kwargs):
360360
logger.info('kmeans terminated with %d clusters after %d iterations.',
361361
len(set(old_clusters.ravel())), itnum - 1)
362362
return (old_clusters.reshape(nrows, ncols), centers)
363-

spectral/algorithms/continuum.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,8 @@
2424

2525
from __future__ import absolute_import, division, print_function, unicode_literals
2626

27-
import logging
2827
import numpy as np
2928

30-
import spectral as spy
31-
from ..utilities.errors import has_nan, NaNValueError
32-
3329

3430
def _segment_concave_region(spectrum, bands, indices, ind_fill, ibegin, iend):
3531
# Here we don't search for local maxima w.r.t. line that connects ends of this region.

0 commit comments

Comments
 (0)