-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(api): add possibility to run study simulations (#35)
- Loading branch information
Showing
9 changed files
with
432 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
# Copyright (c) 2024, RTE (https://www.rte-france.com) | ||
# | ||
# See AUTHORS.txt | ||
# | ||
# This Source Code Form is subject to the terms of the Mozilla Public | ||
# License, v. 2.0. If a copy of the MPL was not distributed with this | ||
# file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
# | ||
# SPDX-License-Identifier: MPL-2.0 | ||
# | ||
# This file is part of the Antares project. | ||
|
||
from enum import Enum | ||
from typing import Any, Optional | ||
|
||
from pydantic import BaseModel, Field | ||
|
||
|
||
class Solver(Enum): | ||
COIN = "coin" | ||
XPRESS = "xpress" | ||
SIRIUS = "sirius" | ||
|
||
|
||
class AntaresSimulationParameters(BaseModel): | ||
solver: Solver = Solver.SIRIUS | ||
nb_cpu: Optional[int] = None | ||
unzip_output: bool = Field(alias="auto_unzip", default=True) | ||
output_suffix: Optional[str] = None | ||
presolve: bool = False | ||
|
||
@property | ||
def other_options(self) -> str: | ||
options = [] | ||
if self.presolve: | ||
options.append("presolve") | ||
if self.solver != Solver.SIRIUS: | ||
options.append(self.solver.name) | ||
return " ".join(options) | ||
|
||
def to_api(self) -> dict[str, Any]: | ||
data = self.model_dump(by_alias=True) | ||
if self.other_options: | ||
data["other_options"] = self.other_options | ||
data.pop("solver", None) | ||
data.pop("presolve", None) | ||
return data | ||
|
||
|
||
class JobStatus(Enum): | ||
PENDING = "pending" | ||
RUNNING = "running" | ||
SUCCESS = "success" | ||
FAILED = "failed" | ||
|
||
@staticmethod | ||
def from_str(input: str) -> "JobStatus": | ||
return JobStatus.__getitem__(input.upper()) | ||
|
||
|
||
class Job(BaseModel): | ||
job_id: str | ||
status: JobStatus | ||
output_id: Optional[str] = None | ||
parameters: AntaresSimulationParameters |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
# Copyright (c) 2024, RTE (https://www.rte-france.com) | ||
# | ||
# See AUTHORS.txt | ||
# | ||
# This Source Code Form is subject to the terms of the Mozilla Public | ||
# License, v. 2.0. If a copy of the MPL was not distributed with this | ||
# file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
# | ||
# SPDX-License-Identifier: MPL-2.0 | ||
# | ||
# This file is part of the Antares project. | ||
import time | ||
|
||
from typing import Any, Optional | ||
|
||
from antares.api_conf.api_conf import APIconf | ||
from antares.api_conf.request_wrapper import RequestWrapper | ||
from antares.exceptions.exceptions import ( | ||
AntaresSimulationRunningError, | ||
AntaresSimulationUnzipError, | ||
APIError, | ||
SimulationFailedError, | ||
SimulationTimeOutError, | ||
TaskFailedError, | ||
TaskTimeOutError, | ||
) | ||
from antares.model.simulation import AntaresSimulationParameters, Job, JobStatus | ||
from antares.service.base_services import BaseRunService | ||
|
||
|
||
class RunApiService(BaseRunService): | ||
def __init__(self, config: APIconf, study_id: str): | ||
super().__init__() | ||
self.config = config | ||
self.study_id = study_id | ||
self._base_url = f"{self.config.get_host()}/api/v1" | ||
self._wrapper = RequestWrapper(self.config.set_up_api_conf()) | ||
|
||
def run_antares_simulation(self, parameters: Optional[AntaresSimulationParameters] = None) -> Job: | ||
url = f"{self._base_url}/launcher/run/{self.study_id}" | ||
try: | ||
if parameters is not None: | ||
payload = parameters.to_api() | ||
response = self._wrapper.post(url, json=payload) | ||
else: | ||
parameters = AntaresSimulationParameters() | ||
response = self._wrapper.post(url) | ||
job_id = response.json()["job_id"] | ||
return self._get_job_from_id(job_id, parameters) | ||
except APIError as e: | ||
raise AntaresSimulationRunningError(self.study_id, e.message) from e | ||
|
||
def _get_job_from_id(self, job_id: str, parameters: AntaresSimulationParameters) -> Job: | ||
url = f"{self._base_url}/launcher/jobs/{job_id}" | ||
response = self._wrapper.get(url) | ||
job_info = response.json() | ||
status = JobStatus.from_str(job_info["status"]) | ||
output_id = job_info.get("output_id") | ||
return Job(job_id=job_id, status=status, parameters=parameters, output_id=output_id) | ||
|
||
def wait_job_completion(self, job: Job, time_out: int) -> None: | ||
start_time = time.time() | ||
repeat_interval = 5 | ||
if job.status == JobStatus.SUCCESS: | ||
self._update_job(job) | ||
|
||
while job.status in (JobStatus.RUNNING, JobStatus.PENDING): | ||
if time.time() - start_time > time_out: | ||
raise SimulationTimeOutError(job.job_id, time_out) | ||
time.sleep(repeat_interval) | ||
self._update_job(job) | ||
|
||
if job.status == JobStatus.FAILED or not job.output_id: | ||
raise SimulationFailedError(self.study_id, job.job_id) | ||
|
||
if job.parameters.unzip_output: | ||
try: | ||
self._wait_unzip_output(self.study_id, job, time_out) | ||
except AntaresSimulationUnzipError as e: | ||
raise SimulationFailedError(self.study_id, job.job_id) from e | ||
|
||
return None | ||
|
||
def _update_job(self, job: Job) -> None: | ||
updated_job = self._get_job_from_id(job.job_id, job.parameters) | ||
job.status = updated_job.status | ||
job.output_id = updated_job.output_id | ||
|
||
def _wait_unzip_output(self, ref_id: str, job: Job, time_out: int) -> None: | ||
url = f"{self._base_url}/tasks" | ||
repeat_interval = 2 | ||
payload = {"type": ["UNARCHIVE"], "ref_id": ref_id} | ||
try: | ||
response = self._wrapper.post(url, json=payload) | ||
tasks = response.json() | ||
task_id = self._get_unarchiving_task_id(job, tasks) | ||
self._wait_task_completion(task_id, repeat_interval, time_out) | ||
except (APIError, TaskFailedError) as e: | ||
raise AntaresSimulationUnzipError(self.study_id, job.job_id, e.message) from e | ||
|
||
def _get_unarchiving_task_id(self, job: Job, tasks: list[dict[str, Any]]) -> str: | ||
for task in tasks: | ||
task_name = task["name"] | ||
output_id = task_name.split("/")[-1].split(" ")[0] | ||
if output_id == job.output_id: | ||
return task["id"] | ||
raise AntaresSimulationUnzipError(self.study_id, job.job_id, "Could not find task for unarchiving job") | ||
|
||
def _wait_task_completion(self, task_id: str, repeat_interval: int, time_out: int) -> None: | ||
url = f"{self._base_url}/tasks/{task_id}" | ||
|
||
start_time = time.time() | ||
task_result = None | ||
while not task_result: | ||
if time.time() - start_time > time_out: | ||
raise TaskTimeOutError(task_id, time_out) | ||
response = self._wrapper.get(url) | ||
task = response.json() | ||
task_result = task["result"] | ||
time.sleep(repeat_interval) | ||
|
||
if not task_result["success"]: | ||
raise TaskFailedError(task_id) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
# Copyright (c) 2024, RTE (https://www.rte-france.com) | ||
# | ||
# See AUTHORS.txt | ||
# | ||
# This Source Code Form is subject to the terms of the Mozilla Public | ||
# License, v. 2.0. If a copy of the MPL was not distributed with this | ||
# file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
# | ||
# SPDX-License-Identifier: MPL-2.0 | ||
# | ||
# This file is part of the Antares project. | ||
from typing import Any, Optional | ||
|
||
from antares.config.local_configuration import LocalConfiguration | ||
from antares.model.simulation import AntaresSimulationParameters, Job | ||
from antares.service.base_services import BaseRunService | ||
|
||
|
||
class RunLocalService(BaseRunService): | ||
def __init__(self, config: LocalConfiguration, study_name: str, **kwargs: Any) -> None: | ||
super().__init__(**kwargs) | ||
self.config = config | ||
self.study_name = study_name | ||
|
||
def run_antares_simulation(self, parameters: Optional[AntaresSimulationParameters] = None) -> Job: | ||
raise NotImplementedError | ||
|
||
def wait_job_completion(self, job: Job, time_out: int) -> None: | ||
raise NotImplementedError |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.