Skip to content

Commit

Permalink
old changes, to be checked when PR
Browse files Browse the repository at this point in the history
  • Loading branch information
g-poveda committed Sep 8, 2023
1 parent 589f893 commit 4b52f65
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 32 deletions.
2 changes: 1 addition & 1 deletion discrete_optimization/coloring/solvers/greedy_coloring.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def solve(self, **kwargs: Any) -> ResultStorage:
greedy_strategy: NXGreedyColoringMethod = kwargs.get(
"strategy", NXGreedyColoringMethod.best
)
strategy_name = greedy_strategy.name
strategy_name = greedy_strategy.value
if strategy_name == "best":
strategies_to_test = strategies
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import logging
from enum import Enum
from typing import Optional

Expand Down Expand Up @@ -60,6 +61,8 @@
PostProMSRCPSP,
)

logging.basicConfig(level=logging.INFO)


class ConstraintHandlerType(Enum):
MIX_SUBPROBLEMS = 0
Expand Down
75 changes: 74 additions & 1 deletion discrete_optimization/generic_tools/cp_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
from abc import abstractmethod
from datetime import timedelta
from enum import Enum
from typing import Any, Dict, Optional, Union
from time import perf_counter_ns
from typing import Any, Dict, List, Optional, Union

from minizinc import Instance, Result, Status

Expand Down Expand Up @@ -202,11 +203,61 @@ def get_status_solver(self) -> Union[StatusSolver, None]:
return self.status_solver


class MinizincLoggingStorage:
def __init__(
self,
nano_sec_start_init: int = None,
nano_sec_end_init: int = None,
nano_sec_launch_solve: int = None,
nano_sec_end_solve: int = None,
):
self.nano_sec_start_init = nano_sec_start_init
self.nano_sec_end_init = nano_sec_end_init
self.nano_sec_launch_solve = nano_sec_launch_solve
self.nano_sec_end_solve = nano_sec_end_solve
self.datas = {}


class ObjectOutputMinizinc:
objective: int
__output_item: Optional[str] = None

def __init__(self, objective, _output_item, **kwargs):
self.objective = objective
self.dict = kwargs
logger.info(f"One solution {self.objective}")
logger.info(f"Output {_output_item}")

def check(self) -> bool:
return True


class ObjectOutputMinizincStoreTime:
objective: int
time_ns: int
__output_item: Optional[str] = None

def __init__(self, objective, _output_item, **kwargs):
self.objective = objective
self.dict = kwargs
self.time_ns = perf_counter_ns()
logger.info(f"One solution {self.objective}")
logger.info(f"Output {_output_item}")
logger.info(f"Storing the time.")

def check(self) -> bool:
return True


class MinizincCPSolver(CPSolver):
"""CP solver wrapping a minizinc solver."""

instance: Optional[Instance] = None
silent_solve_error: bool = False
logging_statistic: bool = True
custom_output_type: bool = False
minizinc_logging_storage: Optional[MinizincLoggingStorage] = None

"""If True and `solve` should raise an error, a warning is raised instead and an empty ResultStorage returned."""

def solve(
Expand All @@ -222,6 +273,16 @@ def solve(
)
limit_time_s = parameters_cp.time_limit
intermediate_solutions = parameters_cp.intermediate_solution
if self.logging_statistic:
self.instance.output_type = ObjectOutputMinizincStoreTime
self.custom_output_type = True
nano_sec_launch_solve = perf_counter_ns()
if self.minizinc_logging_storage is None:
self.minizinc_logging_storage = MinizincLoggingStorage()
if self.minizinc_logging_storage is not None:
self.minizinc_logging_storage.nano_sec_launch_solve = (
nano_sec_launch_solve
)
if self.silent_solve_error:
try:
result = self.instance.solve(
Expand All @@ -248,8 +309,20 @@ def solve(
free_search=parameters_cp.free_search,
optimisation_level=parameters_cp.optimisation_level,
)
if self.logging_statistic:
nano_sec_end_solve = perf_counter_ns()
if self.minizinc_logging_storage is not None:
self.minizinc_logging_storage.nano_sec_end_solve = nano_sec_end_solve
logger.info("Solving finished")
logger.debug(result.status)
logger.debug(result.statistics)
self.status_solver = map_mzn_status_to_do_status[result.status]
if self.logging_statistic:
if self.minizinc_logging_storage is not None:
brut_res: List[ObjectOutputMinizincStoreTime] = (
result if intermediate_solutions else [result]
)
self.minizinc_logging_storage.datas["sols"] = [
(x.time_ns, x.objective) for x in brut_res
]
return self.retrieve_solutions(result=result, parameters_cp=parameters_cp)
24 changes: 14 additions & 10 deletions discrete_optimization/rcpsp/solver/cp_solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from discrete_optimization.generic_tools.cp_tools import (
CPSolverName,
MinizincCPSolver,
ObjectOutputMinizincStoreTime,
ParametersCP,
SignEnum,
map_cp_solver_name,
Expand Down Expand Up @@ -182,6 +183,9 @@ def init_model(self, **args):
if custom_output_type:
model.output_type = RCPSPSolCP
self.custom_output_type = True
if self.logging_statistic:
model.output_type = ObjectOutputMinizincStoreTime
self.custom_output_type = True
solver = Solver.lookup(map_cp_solver_name[self.cp_solver_name])
instance = Instance(solver, model)
self.keys_in_instance = []
Expand Down Expand Up @@ -352,12 +356,12 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP) -> ResultStora
starts = []
if intermediate_solutions:
for i in range(len(result)):
if isinstance(result[i], RCPSPSolCP):
if self.custom_output_type:
starts.append(result[i].dict["s"])
else:
starts.append(result[i, "s"])
else:
if isinstance(result, RCPSPSolCP):
if self.custom_output_type:
starts.append(result.dict["s"])
else:
starts = [result["s"]]
Expand Down Expand Up @@ -671,14 +675,14 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP):
mruns = []
if intermediate_solutions:
for i in range(len(result)):
if isinstance(result[i], RCPSPSolCP):
if self.custom_output_type:
starts.append(result[i].dict["start"])
mruns.append(result[i].dict["mrun"])
else:
starts.append(result[i, "start"])
mruns.append(result[i, "mrun"])
else:
if isinstance(result, RCPSPSolCP):
if self.custom_output_type:
starts.append(result.dict["start"])
mruns.append(result.dict["mrun"])
else:
Expand Down Expand Up @@ -864,14 +868,14 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP):
mruns = []
if intermediate_solutions:
for i in range(len(result)):
if isinstance(result[i], RCPSPSolCP):
if self.custom_output_type:
starts.append(result[i].dict["start"])
mruns.append(result[i].dict["mrun"])
else:
starts.append(result[i, "start"])
mruns.append(result[i, "mrun"])
else:
if isinstance(result, RCPSPSolCP):
if self.custom_output_type:
starts.append(result.dict["start"])
mruns.append(result.dict["mrun"])
else:
Expand Down Expand Up @@ -1173,7 +1177,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP) -> ResultStora
index_best = 0
if intermediate_solutions:
for i in range(len(result)):
if isinstance(result[i], RCPSPSolCP):
if self.custom_output_type:
starts.append(result[i].dict["s"])
starts_preemptive.append(result[i].dict["s_preemptive"])
duration_preemptive.append(result[i].dict["d_preemptive"])
Expand All @@ -1186,7 +1190,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP) -> ResultStora
modes.append(result[i, "mrun"])
objectives_cp.append(result[i, "objective"])
else:
if isinstance(result, RCPSPSolCP):
if self.custom_output_type:
starts.append(result.dict["s"])
starts_preemptive.append(result.dict["s_preemptive"])
duration_preemptive.append(result.dict["d_preemptive"])
Expand Down Expand Up @@ -1612,7 +1616,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP) -> ResultStora
index_best = 0
if intermediate_solutions:
for i in range(len(result)):
if isinstance(result[i], RCPSPSolCP):
if self.custom_output_type:
starts.append(result[i].dict["s"])
starts_preemptive.append(result[i].dict["s_preemptive"])
duration_preemptive.append(result[i].dict["d_preemptive"])
Expand All @@ -1624,7 +1628,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP) -> ResultStora
objectives_cp.append(result[i, "objective"])

else:
if isinstance(result, RCPSPSolCP):
if self.custom_output_type:
starts.append(result.dict["s"])
starts_preemptive.append(result.dict["s_preemptive"])
duration_preemptive.append(result.dict["d_preemptive"])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -582,9 +582,8 @@ def sgs_fast_ms_preemptive(
reached_t is not None
and preemptive_tag[act_id] == 1
and (
True
or reached_t + 1 - current_min_time
>= duration_array[act_id, modes_array[act_id]] / 8
reached_t + 1 - current_min_time
>= duration_array[act_id, modes_array[act_id]] / 5
or reached_end
)
):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP):
# array[ACT,RESOURCE,SKILL] of var bool: contrib; % skill contribution assignment
if intermediate_solutions:
for i in range(len(result)):
if isinstance(result[i], MS_RCPSPSolCP):
if self.custom_output_type:
starts += [result[i].dict["start"]]
mruns += [[1] * len(self.rcpsp_model.tasks_list)]
units_used += [result[i].dict["assign"]]
Expand All @@ -363,7 +363,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP):
units_used += [result[i, "assign"]]
objectives_cp += [result[i, "objective"]]
else:
if isinstance(result, MS_RCPSPSolCP):
if self.custom_output_type:
starts += [result.dict["start"]]
mruns += [[1] * len(self.rcpsp_model.tasks_list)]
units_used += [result.dict["unit_used"]]
Expand All @@ -387,7 +387,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP):
for task in range(len(unit_used)):
task_id = self.rcpsp_model.tasks_list[task]
if unit_used[task][w] == 1:
if isinstance(result[index_solution], MS_RCPSPSolCP):
if self.custom_output_type:
if "contrib" in result[index_solution].dict:
intersection = [
skills_list[i]
Expand Down
26 changes: 12 additions & 14 deletions discrete_optimization/rcpsp_multiskill/solvers/cp_solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,18 +175,16 @@ class MS_RCPSPSolCP:
def __init__(self, objective, _output_item, **kwargs):
self.objective = objective
self.dict = kwargs
logger.debug(f"One solution {self.objective}")
logger.info(f"One solution {self.objective}")
if "nb_preemption_subtasks" in self.dict:
logger.debug(
("nb_preemption_subtasks", self.dict["nb_preemption_subtasks"])
)
logger.info(("nb_preemption_subtasks", self.dict["nb_preemption_subtasks"]))
if "nb_small_tasks" in self.dict:
logger.debug(("nb_small_tasks", self.dict["nb_small_tasks"]))
logger.info(("nb_small_tasks", self.dict["nb_small_tasks"]))
if "res_load" in self.dict:
logger.debug(("res_load ", self.dict["res_load"]))
logger.info(("res_load ", self.dict["res_load"]))
keys = [k for k in self.dict if "penalty" in k]
logger.debug("".join([str(k) + " : " + str(self.dict[k]) + "\n" for k in keys]))
logger.debug(_output_item)
logger.info("".join([str(k) + " : " + str(self.dict[k]) + "\n" for k in keys]))
logger.info(_output_item)

def check(self) -> bool:
return True
Expand Down Expand Up @@ -669,7 +667,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP):
index_best = 0
if intermediate_solutions:
for i in range(len(result)):
if isinstance(result[i], MS_RCPSPSolCP):
if self.custom_output_type:
starts += [result[i].dict["start"]]
mruns += [result[i].dict["mrun"]]
units_used += [result[i].dict["unit_used"]]
Expand All @@ -680,7 +678,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP):
units_used += [result[i, "unit_used"]]
objectives_cp += [result[i, "objective"]]
else:
if isinstance(result, MS_RCPSPSolCP):
if self.custom_output_type:
starts += [result.dict["start"]]
mruns += [result.dict["mrun"]]
units_used += [result.dict["unit_used"]]
Expand All @@ -705,7 +703,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP):
task_id = self.rcpsp_model.tasks_list[task]
if unit_used[w][task] == 1:
if (
isinstance(result[index_solution], MS_RCPSPSolCP)
self.custom_output_type
and "contrib" in result[index_solution].dict
): # model="ms_no_multitasking"
intersection = [
Expand Down Expand Up @@ -1199,7 +1197,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP) -> ResultStora
index_best = 0
if intermediate_solutions:
for i in range(len(result)):
if isinstance(result[i], MS_RCPSPSolCP):
if self.custom_output_type:
starts += [result[i].dict["s"]]
starts_preemptive += [result[i].dict["s_preemptive"]]
duration_preemptive += [result[i].dict["d_preemptive"]]
Expand All @@ -1216,7 +1214,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP) -> ResultStora
units_used_preemptive += [result[i, "unit_used_preemptive"]]
objectives_cp += [result[i, "objective"]]
else:
if isinstance(result, MS_RCPSPSolCP):
if self.custom_output_type:
starts += [result.dict["s"]]
starts_preemptive += [result.dict["s_preemptive"]]
duration_preemptive += [result.dict["d_preemptive"]]
Expand All @@ -1228,7 +1226,7 @@ def retrieve_solutions(self, result, parameters_cp: ParametersCP) -> ResultStora
starts = [result["s"]]
starts_preemptive = [result["s_preemptive"]]
duration_preemptive = [result["d_preemptive"]]
mruns += [result.dict["mrun"]]
mruns += [result["mrun"]]
units_used += [result["unit_used"]]
units_used_preemptive += [result["unit_used_preemptive"]]
objectives_cp += [result["objective"]]
Expand Down

0 comments on commit 4b52f65

Please sign in to comment.