Skip to content

Commit

Permalink
🩹 Patch: SImple fix to reduce complexity on the solver, and let the R…
Browse files Browse the repository at this point in the history
…ust files in charge of handling the timeout
  • Loading branch information
ricardoleal20 committed Aug 15, 2024
1 parent fd52e18 commit 8d26bc2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 38 deletions.
11 changes: 7 additions & 4 deletions pymath_compute/methods/opt_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
STATUS = Literal["OPTIMAL", "FEASIBLE", "UNFEASIBLE", "NOT_EXECUTED"]


async def _gradient_descent( # pylint: disable=R0913
def _gradient_descent( # pylint: disable=R0913
variables: list[Variable],
constraints: list["Constraint"],
objective: Callable[[dict[str, float]], float],
Expand All @@ -25,6 +25,7 @@ async def _gradient_descent( # pylint: disable=R0913
learning_rate: float = 0.001,
iterations: int = 1000,
tol: float = 1e-6,
**_kwargs
) -> STATUS:
"""Gradient Descent implementation
Expand Down Expand Up @@ -61,7 +62,8 @@ async def _gradient_descent( # pylint: disable=R0913
tol
)

async def _brute_force(

def _brute_force(
variables: list[Variable],
constraints: list["Constraint"],
objective: Variable,
Expand All @@ -72,15 +74,16 @@ async def _brute_force(
return brute_force(engine_vars, constraints, objective)


async def _simulated_annealing(
def _simulated_annealing(
variables: list[Variable],
constraints: list["Constraint"],
objective: Variable,
**inputs,
) -> STATUS:
"""Implementation of the Rust method Simulated Annealing"""
# Create the list of engine var
engine_vars = [v._eng_var for v in variables] # pylint: disable=W0212
return simulated_annealing(engine_vars, constraints, objective)
return simulated_annealing(engine_vars, constraints, objective, **inputs)

# ===================== #
# Define the ENUM class #
Expand Down
44 changes: 10 additions & 34 deletions pymath_compute/solvers/opt_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@
- OptSolver: Class for solving optimization problems.
- OptSolverConfig: Configuration for the solver method
"""
import asyncio
import time
from functools import partial
from typing import (
Literal, Callable, TypedDict,
Awaitable, Any, Union,
Any, Union,
overload
)
# Local imports
Expand Down Expand Up @@ -47,8 +46,7 @@ class OptSolverConfig(_Config, total=False):


class OptSolver:
"""
Class OptSolver for solving optimization problems.
"""Class OptSolver for solving optimization problems.
Attributes:
- status: Status of the solver.
Expand Down Expand Up @@ -292,48 +290,26 @@ def __solve_problem(self) -> None:
# Get the initial time of exec
start_time = time.time()
# Get the status
try:
self._status = asyncio.run(
self.__execute_with_timeout_async(
self._config["solver_method"].value,
self._config["solver_time"]
)
)
except TimeoutError:
self._status = "FEASIBLE"
except Exception as e: # pylint: disable=W0718
print("Error executing the algorithm:", e)
self._status = "UNFEASIBLE"
self._status = self.__method_executer()
print(
f"Solver ending with status {self._status}" +
f" in {round(time.time() - start_time, 3)}s."
)

# ========================================== #
# Async executer #
# Method executed #
# ========================================== #
async def __execute_with_timeout_async(
self,
function: Callable[..., Awaitable[STATUS]],
timeout: float
) -> STATUS:
"""Execute the optimization function using a timeout"""
def __method_executer(self) -> STATUS:
"""..."""
method = self._config["solver_method"].value
# Define their inputs
inputs = {
"variables": self._vars,
"objective": self._objective,
"constraints": self._constraints
}
for key, config in self._config.items():
if key not in ["solver_method", "solver_time"]:
if key != "solver_method":
inputs[key] = config
try:
return await asyncio.wait_for(
function(**inputs),
timeout
)
except asyncio.TimeoutError:
raise TimeoutError( # pylint: disable=W0707
"Function execution timed out")
except Exception as e:
raise e
# Call the method and return the status
return method(**inputs)

0 comments on commit 8d26bc2

Please sign in to comment.