Skip to content

Commit 698ca99

Browse files
committed
Replace warning with logging
1 parent 44acf9d commit 698ca99

File tree

4 files changed

+44
-12
lines changed

4 files changed

+44
-12
lines changed

optimizer/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""optimizer
22
A Python package that implements different type of Optimization Algorithm
33
"""
4-
from .util import FileManager, Randomizer
4+
from .util import FileManager, Randomizer, logger
55
from .optimizer import Optimizer
66
from .mopso import MOPSO
77
from .objective import Objective, ElementWiseObjective, BatchObjective

optimizer/mopso.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,7 @@
2222
import math
2323
import numpy as np
2424
import math
25-
import warnings
26-
from optimizer import Optimizer, FileManager, Randomizer
25+
from optimizer import Optimizer, FileManager, Randomizer, logger
2726
from numba import njit, jit
2827
import scipy.stats as stats
2928

@@ -202,7 +201,7 @@ def __init__(self,
202201
self.num_particles = num_particles
203202

204203
if len(lower_bounds) != len(upper_bounds):
205-
warnings.warn(f"Warning: lower_bounds and upper_bounds have different lengths."
204+
logger.warning(f"Warning: lower_bounds and upper_bounds have different lengths."
206205
f"The lowest length ({min(len(lower_bounds), len(upper_bounds))}) is taken.")
207206
self.num_params = min(len(lower_bounds), len(upper_bounds))
208207
self.lower_bounds = lower_bounds
@@ -219,7 +218,7 @@ def __init__(self,
219218
'spread', 'lower_bounds', 'upper_bounds', 'random', 'gaussian'}
220219

221220
if initial_particles_position == 'spread':
222-
warnings.warn(f"Initial distribution set to 'random'.")
221+
logger.warning(f"Initial distribution set to 'random'.")
223222
initial_particles_position = 'random'
224223
# self.spread_particles()
225224

@@ -297,9 +296,9 @@ def check_types(self):
297296
f"Upper bound {i} is not acceptable")
298297

299298
if lb_types != ub_types:
300-
warnings.warn(
299+
logger.warning(
301300
"Warning: lower_bounds and upper_bounds are of different types")
302-
warnings.warn("Keeping the least restrictive type")
301+
logger.warning("Keeping the least restrictive type")
303302
for i in range(self.num_params):
304303
if lb_types[i] == float or ub_types[i] == float:
305304
self.lower_bounds[i] = float(self.lower_bounds[i])
@@ -329,16 +328,21 @@ def insert_nodes(self, param_list, is_bool=False):
329328
return param_list
330329

331330
def get_nodes(self):
332-
all_nodes = [[self.lower_bounds[idx], self.upper_bounds[idx]]
333-
for idx in range(self.num_params)]
331+
332+
def ndcube(*args):
333+
return list(itertools.product(*map(lambda x: [x[0], x[1]], args)))
334+
335+
bounds = list(zip(self.lower_bounds, self.upper_bounds))
336+
all_nodes = ndcube(*bounds)
337+
print(len(all_nodes))
338+
exit()
334339
indices_with_bool = [idx for idx, node in enumerate(
335340
all_nodes) if any(isinstance(val, bool) for val in node)]
336341
all_nodes = [[2 if isinstance(val, bool) and val else 0 if isinstance(
337342
val, bool) and not val else val for val in node] for node in all_nodes]
338343

339344
if self.num_particles < self.num_params:
340-
warnings.warn(f"Warning: not enough particles, now you are running with {
341-
len(all_nodes[0])} particles")
345+
logger.warning(f"Warning: not enough particles, now you are running with {len(all_nodes[0])} particles")
342346

343347
particle_count = len(all_nodes[0])
344348
while particle_count < self.num_particles:

optimizer/util.py

+27
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,34 @@
11
import os
22
import json
33
import numpy as np
4+
import logging
45

6+
class CustomFormatter(logging.Formatter):
7+
8+
grey = "\x1b[38;20m"
9+
yellow = "\x1b[33;20m"
10+
red = "\x1b[31;20m"
11+
bold_red = "\x1b[31;1m"
12+
reset = "\x1b[0m"
13+
format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
14+
15+
FORMATS = {
16+
logging.DEBUG: grey + format + reset,
17+
logging.INFO: grey + format + reset,
18+
logging.WARNING: yellow + format + reset,
19+
logging.ERROR: red + format + reset,
20+
logging.CRITICAL: bold_red + format + reset
21+
}
22+
23+
def format(self, record):
24+
log_fmt = self.FORMATS.get(record.levelno)
25+
formatter = logging.Formatter(log_fmt)
26+
return formatter.format(record)
27+
28+
logger = logging.getLogger("Optimizer")
29+
handler = logging.StreamHandler()
30+
handler.setFormatter(CustomFormatter())
31+
logger.addHandler(handler)
532

633
class Randomizer:
734
rng = np.random.default_rng()

tests/zdt1.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import matplotlib.pyplot as plt
55
import matplotlib.animation as animation
66
import os
7-
7+
import logging
88

99
num_agents = 100
1010
num_iterations = 200
@@ -13,6 +13,7 @@
1313
lb = [0.] * num_params
1414
ub = [1.] * num_params
1515

16+
optimizer.logger.setLevel(logging.DEBUG)
1617

1718
def zdt1_objective1(x):
1819
return x[0]

0 commit comments

Comments
 (0)