Skip to content

Commit

Permalink
Replace warning with logging
Browse files Browse the repository at this point in the history
  • Loading branch information
rsreds committed Apr 4, 2024
1 parent 44acf9d commit 698ca99
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 12 deletions.
2 changes: 1 addition & 1 deletion optimizer/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""optimizer
A Python package that implements different type of Optimization Algorithm
"""
from .util import FileManager, Randomizer
from .util import FileManager, Randomizer, logger
from .optimizer import Optimizer
from .mopso import MOPSO
from .objective import Objective, ElementWiseObjective, BatchObjective
24 changes: 14 additions & 10 deletions optimizer/mopso.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@
import math
import numpy as np
import math
import warnings
from optimizer import Optimizer, FileManager, Randomizer
from optimizer import Optimizer, FileManager, Randomizer, logger
from numba import njit, jit
import scipy.stats as stats

Expand Down Expand Up @@ -202,7 +201,7 @@ def __init__(self,
self.num_particles = num_particles

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

if initial_particles_position == 'spread':
warnings.warn(f"Initial distribution set to 'random'.")
logger.warning(f"Initial distribution set to 'random'.")
initial_particles_position = 'random'
# self.spread_particles()

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

if lb_types != ub_types:
warnings.warn(
logger.warning(
"Warning: lower_bounds and upper_bounds are of different types")
warnings.warn("Keeping the least restrictive type")
logger.warning("Keeping the least restrictive type")
for i in range(self.num_params):
if lb_types[i] == float or ub_types[i] == float:
self.lower_bounds[i] = float(self.lower_bounds[i])
Expand Down Expand Up @@ -329,16 +328,21 @@ def insert_nodes(self, param_list, is_bool=False):
return param_list

def get_nodes(self):
all_nodes = [[self.lower_bounds[idx], self.upper_bounds[idx]]
for idx in range(self.num_params)]

def ndcube(*args):
return list(itertools.product(*map(lambda x: [x[0], x[1]], args)))

bounds = list(zip(self.lower_bounds, self.upper_bounds))
all_nodes = ndcube(*bounds)
print(len(all_nodes))
exit()
indices_with_bool = [idx for idx, node in enumerate(
all_nodes) if any(isinstance(val, bool) for val in node)]
all_nodes = [[2 if isinstance(val, bool) and val else 0 if isinstance(
val, bool) and not val else val for val in node] for node in all_nodes]

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

particle_count = len(all_nodes[0])
while particle_count < self.num_particles:
Expand Down
27 changes: 27 additions & 0 deletions optimizer/util.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,34 @@
import os
import json
import numpy as np
import logging

class CustomFormatter(logging.Formatter):

grey = "\x1b[38;20m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"

FORMATS = {
logging.DEBUG: grey + format + reset,
logging.INFO: grey + format + reset,
logging.WARNING: yellow + format + reset,
logging.ERROR: red + format + reset,
logging.CRITICAL: bold_red + format + reset
}

def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)

logger = logging.getLogger("Optimizer")
handler = logging.StreamHandler()
handler.setFormatter(CustomFormatter())
logger.addHandler(handler)

class Randomizer:
rng = np.random.default_rng()
Expand Down
3 changes: 2 additions & 1 deletion tests/zdt1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import os

import logging

num_agents = 100
num_iterations = 200
Expand All @@ -13,6 +13,7 @@
lb = [0.] * num_params
ub = [1.] * num_params

optimizer.logger.setLevel(logging.DEBUG)

def zdt1_objective1(x):
return x[0]
Expand Down

0 comments on commit 698ca99

Please sign in to comment.