Skip to content

Commit 190e03e

Browse files
committed
Added logging interface and migrated most print statements.
1 parent 3a586f0 commit 190e03e

File tree

15 files changed

+94
-80
lines changed

15 files changed

+94
-80
lines changed

spectral/algorithms/classifiers.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232

3333
from __future__ import division, print_function, unicode_literals
3434

35+
import logging
3536
import numpy
3637
import numpy as np
3738

@@ -137,17 +138,18 @@ def train(self, training_data):
137138
138139
Data for the training classes.
139140
'''
141+
logger = logging.getLogger('spectral')
140142
if not self.min_samples:
141143
# Set minimum number of samples to the number of bands in the image
142144
self.min_samples = training_data.nbands
143-
print('Setting min samples to', self.min_samples)
145+
logger.info('Setting min samples to %d', self.min_samples)
144146
self.classes = []
145147
for cl in training_data:
146148
if cl.size() >= self.min_samples:
147149
self.classes.append(cl)
148150
else:
149-
print(' Omitting class %3d : only %d samples present' % (
150-
cl.index, cl.size()))
151+
logger.warn('Omitting class %3d : only %d samples present',
152+
cl.index, cl.size())
151153
for cl in self.classes:
152154
if not hasattr(cl, 'stats') or not cl.stats_valid():
153155
cl.calc_stats()

spectral/algorithms/clustering.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,12 @@
3333

3434
from __future__ import division, print_function, unicode_literals
3535

36+
import logging
3637
import numpy
38+
from warnings import warn
39+
3740
from .classifiers import Classifier
3841

39-
from warnings import warn
4042

4143

4244
def L1(v1, v2):
@@ -164,6 +166,8 @@ def kmeans(image, nclusters=10, max_iterations=20, **kwargs):
164166
import spectral
165167
import numpy
166168

169+
logger = logging.getLogger('spectral')
170+
167171
if isinstance(image, numpy.ndarray):
168172
return kmeans_ndarray(*(image, nclusters, max_iterations), **kwargs)
169173

@@ -203,7 +207,7 @@ def kmeans(image, nclusters=10, max_iterations=20, **kwargs):
203207
nclusters clusters in the startCenters array.'
204208
centers = numpy.array(start_clusters)
205209
else:
206-
print('Initializing clusters along diagonal of N-dimensional bounding box.')
210+
logging.debug('Initializing clusters along diagonal of N-dimensional bounding box.')
207211
centers = numpy.empty((nclusters, nbands), float)
208212
boxMin = image[0, 0]
209213
boxMax = image[0, 0]
@@ -272,8 +276,8 @@ def kmeans(image, nclusters=10, max_iterations=20, **kwargs):
272276
print("KeyboardInterrupt: Returning clusters from previous iteration")
273277
return (old_clusters, old_centers)
274278

275-
print('kmeans terminated with', len(set(old_clusters.ravel())), \
276-
'clusters after', itnum - 1, 'iterations.', file=status)
279+
logger.info('kmeans terminated with %d clusters after %d iterations',
280+
len(set(old_clusters.ravel())), itnum - 1)
277281
return (old_clusters, centers)
278282

279283

@@ -344,11 +348,11 @@ def kmeans_ndarray(image, nclusters=10, max_iterations=20, **kwargs):
344348
import numpy as np
345349
from spectral.algorithms.spymath import has_nan, NaNValueError
346350

351+
logger = logging.getLogger('spectral')
352+
347353
if has_nan(image):
348354
raise NaNValueError('Image data contains NaN values.')
349355

350-
status = spectral._status
351-
352356
# defaults for kwargs
353357
start_clusters = None
354358
compare = None
@@ -384,7 +388,8 @@ def kmeans_ndarray(image, nclusters=10, max_iterations=20, **kwargs):
384388
nclusters clusters in the startCenters array.'
385389
centers = numpy.array(start_clusters)
386390
else:
387-
print('Initializing clusters along diagonal of N-dimensional bounding box.')
391+
logger.debug('Initializing clusters along diagonal of N-dimensional' \
392+
' bounding box.')
388393
boxMin = np.amin(image, 0)
389394
boxMax = np.amax(image, 0)
390395
delta = (boxMax - boxMin) / (nclusters - 1)
@@ -400,8 +405,6 @@ def kmeans_ndarray(image, nclusters=10, max_iterations=20, **kwargs):
400405
itnum = 1
401406
while (itnum <= max_iterations):
402407
try:
403-
status.display_percentage('Iteration %d...' % itnum)
404-
405408
# Assign all pixels
406409
for i in range(nclusters):
407410
diffs = np.subtract(image, centers[i], out=diffs)
@@ -423,16 +426,13 @@ def kmeans_ndarray(image, nclusters=10, max_iterations=20, **kwargs):
423426
iterations.append(clusters.reshape(nrows, ncols))
424427

425428
if compare and compare(old_clusters, clusters):
426-
status.end_percentage('done.')
427429
break
428430
else:
429431
nChanged = numpy.sum(clusters != old_clusters)
432+
logger.info('k-means iteration {} - {} pixels reassigned.' \
433+
.format(itnum, nChanged))
430434
if nChanged == 0:
431-
status.end_percentage('0 pixels reassigned.')
432435
break
433-
else:
434-
status.end_percentage('%d pixels reassigned.' \
435-
% (nChanged))
436436

437437
old_clusters[:] = clusters
438438
old_centers[:] = centers
@@ -442,7 +442,7 @@ def kmeans_ndarray(image, nclusters=10, max_iterations=20, **kwargs):
442442
print("KeyboardInterrupt: Returning clusters from previous iteration.")
443443
return (old_clusters.reshape(nrows, ncols), old_centers)
444444

445-
print('kmeans terminated with', len(set(old_clusters.ravel())), \
446-
'clusters after', itnum - 1, 'iterations.', file=status)
445+
logger.info('kmeans terminated with %d clusters after %d iterations.',
446+
len(set(old_clusters.ravel())), itnum - 1)
447447
return (old_clusters.reshape(nrows, ncols), centers)
448448

spectral/algorithms/resampling.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@
3434

3535
from __future__ import division, print_function, unicode_literals
3636

37+
import logging
38+
import numpy as np
39+
3740
def erf_local(x):
3841
import math
3942
# save the sign of x
@@ -106,7 +109,7 @@ def create_resampling_matrix(centers1, fwhm1, centers2, fwhm2):
106109
to another. Arguments are the band centers and full-width half maximum
107110
spectral response for the original and new band discretizations.
108111
'''
109-
import numpy
112+
logger = logging.getLogger('spectral')
110113

111114
sqrt_8log2 = 2.3548200450309493
112115

@@ -117,7 +120,7 @@ def create_resampling_matrix(centers1, fwhm1, centers2, fwhm2):
117120
bounds2 = [[centers2[i] - fwhm2[i] / 2.0, centers2[i] + fwhm2[i] /
118121
2.0] for i in range(N2)]
119122

120-
M = numpy.zeros([N2, N1])
123+
M = np.zeros([N2, N1])
121124

122125
jStart = 0
123126
nan = float('nan')
@@ -130,7 +133,7 @@ def create_resampling_matrix(centers1, fwhm1, centers2, fwhm2):
130133
j += 1
131134

132135
if j == N1:
133-
print(('No overlap for target band %d (%f / %f)' % (
136+
logger.info(('No overlap for target band %d (%f / %f)' % (
134137
i, centers2[i], fwhm2[i])))
135138
M[i, 0] = nan
136139
continue
@@ -146,8 +149,8 @@ def create_resampling_matrix(centers1, fwhm1, centers2, fwhm2):
146149
# Put NaN in first element of any row that doesn't produce a band in
147150
# the new schema.
148151
if len(matches) == 0:
149-
print(('No overlap for target band %d (%f / %f)' % (
150-
i, centers2[i], fwhm2[i])))
152+
logger.info('No overlap for target band %d (%f / %f)',
153+
i, centers2[i], fwhm2[i])
151154
M[i, 0] = nan
152155
continue
153156

@@ -157,7 +160,7 @@ def create_resampling_matrix(centers1, fwhm1, centers2, fwhm2):
157160
# case can be handled.
158161

159162
overlaps = [overlap(bounds1[k], bounds2[i]) for k in matches]
160-
contribs = numpy.zeros(len(matches))
163+
contribs = np.zeros(len(matches))
161164
A = 0.
162165
for k in range(len(matches)):
163166
#endNorms = [normal(centers2[i], stdev, x) for x in overlaps[k]]
@@ -262,5 +265,4 @@ def __call__(self, spectrum):
262265
263266
Any target bands that do not have at lease one overlapping source band
264267
will contain `float('nan')` as the resampled band value.'''
265-
import numpy
266-
return numpy.dot(self.matrix, spectrum)
268+
return np.dot(self.matrix, spectrum)

spectral/database/aster.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -426,10 +426,10 @@ def get_signature(self, spectrumID):
426426
sig.sample_name = results[0][0]
427427
sig.sample_id = results[0][1]
428428
x = array.array(arraytypecode)
429-
x.fromstring(results[0][2])
429+
frombytes(x, results[0][2])
430430
sig.x = list(x)
431431
y = array.array(arraytypecode)
432-
y.fromstring(results[0][3])
432+
frombytes(y, results[0][3])
433433
sig.y = list(y)
434434
return sig
435435

spectral/database/ecostress.py

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
from __future__ import division, print_function, unicode_literals
3333

3434
import itertools
35+
import logging
3536

3637
from spectral.utilities.python23 import IS_PYTHON3
3738
from .aster import AsterDatabase, Signature
@@ -47,6 +48,7 @@
4748
def read_ecostress_file(filename):
4849
'''Reads an ECOSTRESS v1 spectrum file.'''
4950

51+
logger = logging.getLogger('spectral')
5052
lines = open_file(filename).readlines()
5153
if not IS_PYTHON3:
5254
lines = [line.decode('iso-8859-1') for line in lines]
@@ -63,7 +65,7 @@ def read_ecostress_file(filename):
6365
try:
6466
s.sample[pair[0].lower()] = pair[1]
6567
except:
66-
print('line {}: {}'.format(i, lines[i]))
68+
logger.error('Failed to parse line: {}: {}'.format(i, lines[i]))
6769
raise
6870

6971
# Read measurment metadata
@@ -84,21 +86,23 @@ def read_ecostress_file(filename):
8486

8587
# Try to handle invalid values on signature lines
8688
if nItems == 1:
87-
print('single item (%s) on signature line, %s' \
88-
% (pair[0], filename))
89+
logger.info('Skipping single item (%s) on signature line for %s',
90+
pair[0], filename)
8991
continue
9092
elif nItems > 2:
91-
print('more than 2 values on signature line,', filename)
93+
logger.info('Skipping more than 2 values on signature line for %s',
94+
filename)
9295
continue
9396
try:
9497
x = float(pair[0])
9598
except:
96-
print('corrupt signature line,', filename)
99+
logger.info('Corrupt signature line in file %s', filename)
97100
if x == 0:
98-
# print 'Zero wavelength value', filename
101+
logger.info('Skipping zero wavelength value in file %s', filename)
99102
continue
100103
elif x < 0:
101-
print('Negative wavelength value,', filename)
104+
logger.info('Skipping negative wavelength value in file %s',
105+
filename)
102106
continue
103107

104108
pairs.append(pair)
@@ -173,6 +177,7 @@ def _import_files(self, data_dir, ignore=None):
173177
import numpy
174178
import os
175179

180+
logger = logging.getLogger('spectral')
176181
if not os.path.isdir(data_dir):
177182
raise Exception('Error: Invalid directory name specified.')
178183
if ignore is not None:
@@ -193,7 +198,7 @@ class Sig:
193198
if f in filesToIgnore:
194199
numIgnored += 1
195200
continue
196-
print('Importing %s.' % f)
201+
logger.info('Importing ECOSTRESS file %s.', f)
197202
numFiles += 1
198203
sig = self.read_file(f)
199204
s = sig.sample
@@ -233,13 +238,14 @@ class Sig:
233238
m['x units'], yUnit, m['first x value'],
234239
m['last x value'], sig.x, sig.y)
235240
if numFiles == 0:
236-
print('No data files were found in directory "%s".' \
237-
% data_dir)
241+
logger.warning('No ECOSTRESS data files were found in "%s".',
242+
data_dir)
238243
else:
239-
print('Processed %d files.' % numFiles)
244+
logger.info('Processed %d ECOSTRESS files.', numFiles)
240245
if numIgnored > 0:
241-
print('Ignored the following %d bad files:' % (numIgnored))
246+
msg = 'Ignored the following %d bad files:' % (numIgnored)
242247
for f in filesToIgnore:
243-
print('\t' + f)
248+
msg += '\n\t' + f
249+
logger.info(msg)
244250

245251
return sigs

spectral/graphics/rasterwindow.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11

22
from __future__ import division, print_function, unicode_literals
33

4+
import logging
45
import wx
56
from spectral.graphics.graphics import SpyWindow
67

8+
logger = logging.getLogger('spectral')
79

810
class RasterWindow(wx.Frame, SpyWindow):
911
'''
@@ -44,7 +46,7 @@ def paint(self, dc):
4446
def left_double_click(self, evt):
4547
from spectral import settings
4648
if "data source" in self.kwargs:
47-
print('(%d,%d)' % (evt.GetY(), evt.GetX()))
49+
logger.info('{}'.format((evt.GetY(), evt.GetX()))
4850
settings.plotter.plot(self.kwargs["data source"]
4951
[evt.GetY(), evt.GetX()],
5052
source=self.kwargs["data source"])

spectral/graphics/spywxpythonthread.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,12 @@
4040
DEFAULT_X_SIZE = 600
4141
DEFAULT_Y_SIZE = 600
4242

43+
import logging
4344
from wx import *
4445
#from Numeric import *
4546
from spectral.graphics import *
4647

48+
logger = logging.getLogger('spectral')
4749

4850
#---------------------------------------------------------------------------
4951
#wxEVT_VIEW_IMAGE = wxID_HIGHEST + 1
@@ -130,7 +132,7 @@ def paint(self, dc):
130132
dc.EndDrawing()
131133

132134
def left_double_click(self, evt):
133-
print((evt.m_y, evt.m_x))
135+
logger.debug('LEFT DOUBLE-CLICK at {}'.format((evt.m_y, evt.m_x)))
134136
from spectral import settings
135137
if "data source" in self.kwargs:
136138
settings.plotter.plot(self.kwargs["data source"][evt.m_y, evt.m_x],

spectral/io/aviris.py

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,6 @@
3434

3535
from __future__ import division, print_function, unicode_literals
3636

37-
from warnings import warn
38-
39-
4037
def open(file, band_file=None):
4138
'''
4239
Returns a SpyFile object for an AVIRIS image file.
@@ -89,19 +86,7 @@ class Params:
8986

9087
if band_file:
9188
img.bands = read_aviris_bands(find_file_path(band_file))
92-
else:
93-
# Let user know if band cal files are available
94-
fileDir = os.path.split(p.filename)[0]
95-
calFiles = glob.glob(fileDir + '/*.spc')
96-
if len(calFiles) > 0:
97-
print('\nThe following band calibration files are located in ' \
98-
'the same directory as the opened AVIRIS file:\n')
99-
for f in calFiles:
100-
print(" " + os.path.split(f)[1])
101-
print('\nTo associate a band calibration file with an AVIRIS ' \
102-
'data file, re-open the AVIRIS file with the following ' \
103-
'syntax:\n')
104-
print(' >>> img = aviris.open(fileName, calFileName)\n')
89+
10590
return img
10691

10792

0 commit comments

Comments
 (0)