Skip to content

Commit df873cd

Browse files
committed
Modify use of logging
1 parent 503604d commit df873cd

File tree

10 files changed

+145
-125
lines changed

10 files changed

+145
-125
lines changed

src/py_eddy_tracker/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,13 @@ def parse_args(self, *args, **kwargs):
8080
# set up logging to CONSOLE
8181
console = logging.StreamHandler()
8282
console.setFormatter(ColoredFormatter(self.FORMAT_LOG))
83+
logger = logging.getLogger('pet')
8384
# add the handler to the root logger
84-
logging.getLogger('').addHandler(console)
85+
logger.addHandler(console)
8586
# Parsing
8687
opts = super(EddyParser, self).parse_args(*args, **kwargs)
8788
# set current level
88-
logging.getLogger().setLevel(getattr(logging, opts.logging_level.upper()))
89+
logger.setLevel(getattr(logging, opts.logging_level.upper()))
8990
return opts
9091

9192

src/py_eddy_tracker/dataset/grid.py

Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
from ..generic import distance, interp2d_geo, fit_circle, uniform_resample
2525
from ..poly import poly_contain_poly, winding_number_grid_in_poly
2626

27+
logger = logging.getLogger("pet")
28+
2729

2830
def raw_resample(datas, fixed_size):
2931
nb_value = datas.shape[0]
@@ -97,8 +99,8 @@ def _fit_circle_path(vertice):
9799
d_lon = lons.max() - lons.min()
98100
d_lat = lats.max() - lats.min()
99101
if d_lon < 1e-7 and d_lat < 1e-7:
100-
# logging.warning('An edge is only define in one position')
101-
# logging.debug('%d coordinates %s,%s', len(lons),lons,
102+
# logger.warning('An edge is only define in one position')
103+
# logger.debug('%d coordinates %s,%s', len(lons),lons,
102104
# lats)
103105
return 0, -90, nan, nan
104106
centlon_e, centlat_e, eddy_radius_e, aerr = fit_circle(c_x, c_y)
@@ -226,7 +228,7 @@ def __init__(self, filename, x_name, y_name, centered=None):
226228
self.vars = dict()
227229
self.interpolators = dict()
228230
if centered is None:
229-
logging.warning('We assume the position of grid is the center'
231+
logger.warning('We assume the position of grid is the center'
230232
' corner for %s', filename)
231233
self.load_general_features()
232234
self.load()
@@ -244,7 +246,7 @@ def is_centered(self):
244246
def load_general_features(self):
245247
"""Load attrs
246248
"""
247-
logging.debug('Load general feature from %(filename)s', dict(filename=self.filename))
249+
logger.debug('Load general feature from %(filename)s', dict(filename=self.filename))
248250
with Dataset(self.filename) as h:
249251
# Load generals
250252
self.dimensions = {i: len(v) for i, v in h.dimensions.items()}
@@ -314,7 +316,7 @@ def load(self):
314316
self.vars[y_name] = h.variables[y_name][:]
315317

316318
if self.is_centered:
317-
logging.info('Grid center')
319+
logger.info('Grid center')
318320
self.x_c = self.vars[x_name]
319321
self.y_c = self.vars[y_name]
320322

@@ -386,7 +388,7 @@ def grid(self, varname):
386388
if varname not in self.vars:
387389
coordinates_dims = list(self.x_dim)
388390
coordinates_dims.extend(list(self.y_dim))
389-
logging.debug('Load %(varname)s from %(filename)s', dict(varname=varname, filename=self.filename))
391+
logger.debug('Load %(varname)s from %(filename)s', dict(varname=varname, filename=self.filename))
390392
with Dataset(self.filename) as h:
391393
dims = h.variables[varname].dimensions
392394
sl = [slice(None) if dim in coordinates_dims else 0 for dim in dims]
@@ -406,7 +408,7 @@ def grid_tiles(self, varname, slice_x, slice_y):
406408
"""
407409
coordinates_dims = list(self.x_dim)
408410
coordinates_dims.extend(list(self.y_dim))
409-
logging.debug('Extract %(varname)s from %(filename)s with slice(x:%(slice_x)s,y:%(slice_y)s)',
411+
logger.debug('Extract %(varname)s from %(filename)s with slice(x:%(slice_x)s,y:%(slice_y)s)',
410412
dict(varname=varname, filename=self.filename, slice_y=slice_y, slice_x=slice_x))
411413
with Dataset(self.filename) as h:
412414
dims = h.variables[varname].dimensions
@@ -474,7 +476,7 @@ def eddy_identification(self, grid_height, uname, vname, date, step=0.005, shape
474476
in_h_unit = units.parse_expression(h_units)
475477
if in_h_unit is not None:
476478
factor, _ = in_h_unit.to('m').to_tuple()
477-
logging.info('We will apply on step a factor to be coherent with grid : %f', 1 / factor)
479+
logger.info('We will apply on step a factor to be coherent with grid : %f', 1 / factor)
478480
step /= factor
479481
if precision is not None:
480482
precision /= factor
@@ -491,7 +493,7 @@ def eddy_identification(self, grid_height, uname, vname, date, step=0.005, shape
491493
z_min_p, z_max_p = percentile(data_tmp, epsilon), percentile(data_tmp, 100 - epsilon)
492494
d_zp = z_max_p - z_min_p
493495
if d_z / d_zp > 2:
494-
logging.warning('Maybe some extrema are present zmin %f (m) and zmax %f (m) will be replace by %f and %f',
496+
logger.warning('Maybe some extrema are present zmin %f (m) and zmax %f (m) will be replace by %f and %f',
495497
z_min, z_max, z_min_p, z_max_p)
496498
z_min, z_max = z_min_p, z_max_p
497499

@@ -523,7 +525,7 @@ def eddy_identification(self, grid_height, uname, vname, date, step=0.005, shape
523525
if nb_paths == 0:
524526
continue
525527
cvalues = self.contours.cvalues[corrected_coll_index]
526-
logging.debug('doing collection %s, contour value %.4f, %d paths',
528+
logger.debug('doing collection %s, contour value %.4f, %d paths',
527529
corrected_coll_index, cvalues, nb_paths)
528530

529531
# Loop over individual c_s contours (i.e., every eddy in field)
@@ -626,7 +628,7 @@ def eddy_identification(self, grid_height, uname, vname, date, step=0.005, shape
626628
properties.obs['contour_lon_s'], properties.obs['contour_lat_s'] = uniform_resample(
627629
speed_contour.lon, speed_contour.lat, fixed_size=array_sampling)
628630
if aerr > 99.9 or aerr_s > 99.9:
629-
logging.warning('Strange shape at this step! shape_error : %f, %f', aerr, aerr_s)
631+
logger.warning('Strange shape at this step! shape_error : %f, %f', aerr, aerr_s)
630632

631633
eddies.append(properties)
632634
# To reserve definitively the area
@@ -781,13 +783,13 @@ def compute_pixel_path(self, x0, y0, x1, y1):
781783
pass
782784

783785
def init_pos_interpolator(self):
784-
logging.debug('Create a KdTree could be long ...')
786+
logger.debug('Create a KdTree could be long ...')
785787
self.index_interp = cKDTree(
786788
uniform_resample_stack((
787789
self.x_c.reshape(-1),
788790
self.y_c.reshape(-1)
789791
)))
790-
logging.debug('... OK')
792+
logger.debug('... OK')
791793

792794
def _low_filter(self, grid_name, x_cut, y_cut, factor=40.):
793795
data = self.grid(grid_name)
@@ -922,7 +924,7 @@ def kernel_lanczos(self, lat, wave_length, order=1):
922924
# wave_length in km
923925
# order must be int
924926
if order < 1:
925-
logging.warning('order must be superior to 0')
927+
logger.warning('order must be superior to 0')
926928
order = ceil(order).astype(int)
927929
# Estimate size of kernel
928930
step_y_km = self.ystep * distance(0, 0, 0, 1) / 1000
@@ -951,14 +953,14 @@ def kernel_bessel(self, lat, wave_length, order=1):
951953
# wave_length in km
952954
# order must be int
953955
if order < 1:
954-
logging.warning('order must be superior to 0')
956+
logger.warning('order must be superior to 0')
955957
order = ceil(order).astype(int)
956958
# Estimate size of kernel
957959
step_y_km = self.ystep * distance(0, 0, 0, 1) / 1000
958960
step_x_km = self.xstep * distance(0, lat, 1, lat) / 1000
959961
min_wave_length = max(step_x_km * 2, step_y_km * 2)
960962
if wave_length < min_wave_length:
961-
logging.error('Wave_length to short for resolution, must be > %d km', ceil(min_wave_length))
963+
logger.error('Wave_length to short for resolution, must be > %d km', ceil(min_wave_length))
962964
raise Exception()
963965
# half size will be multiply with by order
964966
half_x_pt, half_y_pt = ceil(wave_length / step_x_km).astype(int), ceil(wave_length / step_y_km).astype(int)
@@ -992,7 +994,7 @@ def _low_filter(self, grid_name, x_cut, y_cut):
992994
"""low filtering
993995
"""
994996
i_x, i_y = x_cut * 0.125 / self.xstep, y_cut * 0.125 / self.xstep
995-
logging.info(
997+
logger.info(
996998
'Filtering with this wave : (%s, %s) converted in pixel (%s, %s)',
997999
x_cut, y_cut, i_x, i_y
9981000
)
@@ -1005,7 +1007,7 @@ def _low_filter(self, grid_name, x_cut, y_cut):
10051007

10061008
def convolve_filter_with_dynamic_kernel(self, grid, kernel_func, lat_max=85, extend=False, **kwargs_func):
10071009
if (abs(self.y_c) > lat_max).any():
1008-
logging.warning('No filtering above %f degrees of latitude', lat_max)
1010+
logger.warning('No filtering above %f degrees of latitude', lat_max)
10091011
if isinstance(grid, str):
10101012
data = self.grid(grid).copy()
10111013
else:
@@ -1016,7 +1018,7 @@ def convolve_filter_with_dynamic_kernel(self, grid, kernel_func, lat_max=85, ext
10161018
nb_lines = self.y_c.shape[0]
10171019
dt = list()
10181020

1019-
debug_active = logging.getLogger().getEffectiveLevel() == logging.DEBUG
1021+
debug_active = logger.getLogger().getEffectiveLevel() == logging.DEBUG
10201022

10211023
for i, lat in enumerate(self.y_c):
10221024
if abs(lat) > lat_max or data[:, i].mask.all():
@@ -1087,11 +1089,11 @@ def bessel_band_filter(self, grid_name, wave_length_inf, wave_length_sup, **kwar
10871089
self.vars[grid_name] -= data_out
10881090

10891091
def bessel_high_filter(self, grid_name, wave_length, order=1, lat_max=85):
1090-
logging.debug('Run filtering with wave of %(wave_length)s km and order of %(order)s ...',
1092+
logger.debug('Run filtering with wave of %(wave_length)s km and order of %(order)s ...',
10911093
dict(wave_length=wave_length, order=order))
10921094
data_out = self.convolve_filter_with_dynamic_kernel(
10931095
grid_name, self.kernel_bessel, lat_max=lat_max, wave_length=wave_length, order=order)
1094-
logging.debug('Filtering done')
1096+
logger.debug('Filtering done')
10951097
self.vars[grid_name] -= data_out
10961098

10971099
def bessel_low_filter(self, grid_name, wave_length, order=1, lat_max=85):
@@ -1120,7 +1122,7 @@ def spectrum_lonlat(self, grid_name, area=None, ref=None, **kwargs):
11201122
continue
11211123
pws.append(pw)
11221124
if nb_invalid:
1123-
logging.warning('%d/%d columns invalid', nb_invalid, i + 1)
1125+
logger.warning('%d/%d columns invalid', nb_invalid, i + 1)
11241126
lat_content = 1 / f, array(pws).mean(axis=0)
11251127

11261128
# Lon spectrum
@@ -1142,7 +1144,7 @@ def spectrum_lonlat(self, grid_name, area=None, ref=None, **kwargs):
11421144
fs.append(f)
11431145
pws.append(pw)
11441146
if nb_invalid:
1145-
logging.warning('%d/%d lines invalid', nb_invalid, i + 1)
1147+
logger.warning('%d/%d lines invalid', nb_invalid, i + 1)
11461148
f_interp = linspace(f_min, f_max, f.shape[0])
11471149
pw_m = array(
11481150
[interp1d(f, pw, fill_value=0., bounds_error=False)(f_interp) for f, pw in zip(fs, pws)]).mean(axis=0)
@@ -1187,7 +1189,7 @@ def compute_finite_difference(self, data, schema=1, mode='reflect', vertical=Fal
11871189

11881190
def compute_stencil(self, data, stencil_halfwidth=4, mode='reflect', vertical=False):
11891191
stencil_halfwidth = max(min(int(stencil_halfwidth), 4), 1)
1190-
logging.debug('Stencil half width apply : %d', stencil_halfwidth)
1192+
logger.debug('Stencil half width apply : %d', stencil_halfwidth)
11911193
# output
11921194
grad = None
11931195

@@ -1279,7 +1281,7 @@ def add_uv_lagerloef(self, grid_height, uname='u', vname='v', schema=15):
12791281
def add_uv(self, grid_height, uname='u', vname='v', stencil_halfwidth=4):
12801282
"""Compute a u and v grid
12811283
"""
1282-
logging.info('Add u/v variable with stencil method')
1284+
logger.info('Add u/v variable with stencil method')
12831285
data = self.grid(grid_height)
12841286
h_dict = self.variables_description[grid_height]
12851287
for variable in (uname, vname):

src/py_eddy_tracker/eddy_feature.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
from numba import njit, types as numba_types
3333
from .poly import winding_number_poly
3434

35+
logger = logging.getLogger("pet")
36+
3537

3638
class Amplitude(object):
3739
"""
@@ -104,7 +106,7 @@ def all_pixels_below_h0(self, level):
104106
# After we use grid.data because index are in contour and we check before than no pixel are hide
105107
nb = len(lmi_i)
106108
if nb == 0:
107-
logging.warning('No extrema found in contour in level %f', level)
109+
logger.warning('No extrema found in contour in level %f', level)
108110
return False
109111
elif nb == 1:
110112
i, j = lmi_i[0], lmi_j[0]
@@ -135,7 +137,7 @@ def all_pixels_above_h0(self, level):
135137
self.mle, -1)
136138
nb = len(lmi_i)
137139
if nb == 0:
138-
logging.warning('No extrema found in contour in level %f', level)
140+
logger.warning('No extrema found in contour in level %f', level)
139141
return False
140142
elif nb == 1:
141143
i, j = lmi_i[0], lmi_j[0]
@@ -332,28 +334,28 @@ def find_wrapcut_path_and_join(self, x0, x1):
332334
paths_out.extend(paths_left)
333335
paths_out.extend(paths_right)
334336
collection._paths = paths_out
335-
logging.info('%d contours close over the bounds', poly_solve)
337+
logger.info('%d contours close over the bounds', poly_solve)
336338

337339
def __init__(self, x, y, z, levels, wrap_x=False, keep_unclose=False):
338340
"""
339341
c_i : index to contours
340342
l_i : index to levels
341343
"""
342-
logging.info('Start computing iso lines')
344+
logger.info('Start computing iso lines')
343345
fig = Figure()
344346
ax = fig.add_subplot(111)
345347
if wrap_x:
346-
logging.debug('wrapping activate to compute contour')
348+
logger.debug('wrapping activate to compute contour')
347349
x = concatenate((x, x[:1] + 360))
348350
z = ma.concatenate((z, z[:1]))
349-
logging.debug('X shape : %s', x.shape)
350-
logging.debug('Y shape : %s', y.shape)
351-
logging.debug('Z shape : %s', z.shape)
352-
logging.info('Start computing iso lines with %d levels from %f to %f ...', len(levels), levels[0], levels[-1])
351+
logger.debug('X shape : %s', x.shape)
352+
logger.debug('Y shape : %s', y.shape)
353+
logger.debug('Z shape : %s', z.shape)
354+
logger.info('Start computing iso lines with %d levels from %f to %f ...', len(levels), levels[0], levels[-1])
353355
self.contours = ax.contour(x, y, z.T, levels, cmap='rainbow')
354356
if wrap_x:
355357
self.find_wrapcut_path_and_join(x[0], x[-1])
356-
logging.info('Finish computing iso lines')
358+
logger.info('Finish computing iso lines')
357359

358360
nb_level = 0
359361
nb_contour = 0
@@ -403,7 +405,7 @@ def __init__(self, x, y, z, levels, wrap_x=False, keep_unclose=False):
403405
contour.used = False
404406
nb_contour += 1
405407
nb_pt += contour.vertices.shape[0]
406-
logging.info('Repair %d closed contours and %d almost closed contours / %d contours', closed_contours,
408+
logger.info('Repair %d closed contours and %d almost closed contours / %d contours', closed_contours,
407409
almost_closed_contours, nb_contour)
408410
# Type for coordinates
409411
coord_dtype = contour.vertices.dtype

0 commit comments

Comments
 (0)