taipy.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import pathlib
  12. import shutil
  13. from datetime import datetime
  14. from typing import Any, Callable, Dict, List, Optional, Set, Union, overload
  15. from taipy.config.common.scope import Scope
  16. from taipy.logger._taipy_logger import _TaipyLogger
  17. from ._entity._entity import _Entity
  18. from ._version._version_manager_factory import _VersionManagerFactory
  19. from .common._check_instance import (
  20. _is_cycle,
  21. _is_data_node,
  22. _is_job,
  23. _is_scenario,
  24. _is_sequence,
  25. _is_submission,
  26. _is_task,
  27. )
  28. from .common._warnings import _warn_no_core_service
  29. from .config.data_node_config import DataNodeConfig
  30. from .config.scenario_config import ScenarioConfig
  31. from .cycle._cycle_manager_factory import _CycleManagerFactory
  32. from .cycle.cycle import Cycle
  33. from .cycle.cycle_id import CycleId
  34. from .data._data_manager_factory import _DataManagerFactory
  35. from .data.data_node import DataNode
  36. from .data.data_node_id import DataNodeId
  37. from .exceptions.exceptions import (
  38. DataNodeConfigIsNotGlobal,
  39. ModelNotFound,
  40. NonExistingVersion,
  41. VersionIsNotProductionVersion,
  42. )
  43. from .job._job_manager_factory import _JobManagerFactory
  44. from .job.job import Job
  45. from .job.job_id import JobId
  46. from .scenario._scenario_manager_factory import _ScenarioManagerFactory
  47. from .scenario.scenario import Scenario
  48. from .scenario.scenario_id import ScenarioId
  49. from .sequence._sequence_manager_factory import _SequenceManagerFactory
  50. from .sequence.sequence import Sequence
  51. from .sequence.sequence_id import SequenceId
  52. from .submission._submission_manager_factory import _SubmissionManagerFactory
  53. from .submission.submission import Submission, SubmissionId
  54. from .task._task_manager_factory import _TaskManagerFactory
  55. from .task.task import Task
  56. from .task.task_id import TaskId
  57. __logger = _TaipyLogger._get_logger()
  58. def set(entity: Union[DataNode, Task, Sequence, Scenario, Cycle]):
  59. """Save or update an entity.
  60. This function allows you to save or update an entity in Taipy.
  61. Parameters:
  62. entity (Union[DataNode^, Task^, Sequence^, Scenario^, Cycle^]): The
  63. entity to save or update.
  64. """
  65. if _is_cycle(entity):
  66. return _CycleManagerFactory._build_manager()._set(entity)
  67. if _is_scenario(entity):
  68. return _ScenarioManagerFactory._build_manager()._set(entity)
  69. if _is_sequence(entity):
  70. return _SequenceManagerFactory._build_manager()._set(entity)
  71. if _is_task(entity):
  72. return _TaskManagerFactory._build_manager()._set(entity)
  73. if _is_data_node(entity):
  74. return _DataManagerFactory._build_manager()._set(entity)
  75. def is_submittable(entity: Union[Scenario, ScenarioId, Sequence, SequenceId, Task, TaskId]) -> bool:
  76. """Indicate if an entity can be submitted.
  77. This function checks if the given entity can be submitted for execution.
  78. Returns:
  79. True if the given entity can be submitted. False otherwise.
  80. """
  81. if _is_scenario(entity):
  82. return _ScenarioManagerFactory._build_manager()._is_submittable(entity)
  83. if _is_sequence(entity):
  84. return _SequenceManagerFactory._build_manager()._is_submittable(entity)
  85. if _is_task(entity):
  86. return _TaskManagerFactory._build_manager()._is_submittable(entity)
  87. return False
  88. def is_editable(
  89. entity: Union[
  90. DataNode,
  91. Task,
  92. Job,
  93. Sequence,
  94. Scenario,
  95. Cycle,
  96. Submission,
  97. DataNodeId,
  98. TaskId,
  99. JobId,
  100. SequenceId,
  101. ScenarioId,
  102. CycleId,
  103. SubmissionId,
  104. ],
  105. ) -> bool:
  106. """Indicate if an entity can be edited.
  107. This function checks if the given entity can be edited.
  108. Returns:
  109. True if the given entity can be edited. False otherwise.
  110. """
  111. if _is_cycle(entity):
  112. return _CycleManagerFactory._build_manager()._is_editable(entity)
  113. if _is_scenario(entity):
  114. return _ScenarioManagerFactory._build_manager()._is_editable(entity)
  115. if _is_sequence(entity):
  116. return _SequenceManagerFactory._build_manager()._is_editable(entity)
  117. if _is_task(entity):
  118. return _TaskManagerFactory._build_manager()._is_editable(entity)
  119. if _is_job(entity):
  120. return _JobManagerFactory._build_manager()._is_editable(entity)
  121. if _is_data_node(entity):
  122. return _DataManagerFactory._build_manager()._is_editable(entity)
  123. if _is_submission(entity):
  124. return _SubmissionManagerFactory._build_manager()._is_editable(entity)
  125. return False
  126. def is_readable(
  127. entity: Union[
  128. DataNode,
  129. Task,
  130. Job,
  131. Sequence,
  132. Scenario,
  133. Cycle,
  134. Submission,
  135. DataNodeId,
  136. TaskId,
  137. JobId,
  138. SequenceId,
  139. ScenarioId,
  140. CycleId,
  141. SubmissionId,
  142. ],
  143. ) -> bool:
  144. """Indicate if an entity can be read.
  145. This function checks if the given entity can be read.
  146. Returns:
  147. True if the given entity can be read. False otherwise.
  148. """
  149. if _is_cycle(entity):
  150. return _CycleManagerFactory._build_manager()._is_readable(entity)
  151. if _is_scenario(entity):
  152. return _ScenarioManagerFactory._build_manager()._is_readable(entity)
  153. if _is_sequence(entity):
  154. return _SequenceManagerFactory._build_manager()._is_readable(entity)
  155. if _is_task(entity):
  156. return _TaskManagerFactory._build_manager()._is_readable(entity)
  157. if _is_job(entity):
  158. return _JobManagerFactory._build_manager()._is_readable(entity)
  159. if _is_data_node(entity):
  160. return _DataManagerFactory._build_manager()._is_readable(entity)
  161. if _is_submission(entity):
  162. return _SubmissionManagerFactory._build_manager()._is_readable(entity)
  163. return False
  164. @_warn_no_core_service()
  165. def submit(
  166. entity: Union[Scenario, Sequence, Task],
  167. force: bool = False,
  168. wait: bool = False,
  169. timeout: Optional[Union[float, int]] = None,
  170. ) -> Optional[Union[Job, List[Job]]]:
  171. """Submit a scenario, sequence or task entity for execution.
  172. This function submits the given entity for execution and returns the created job(s).
  173. If the entity is a sequence or a scenario, all the tasks of the entity are
  174. submitted for execution.
  175. Parameters:
  176. entity (Union[Scenario^, Sequence^, Task^]): The scenario, sequence or task to submit.
  177. force (bool): If True, the execution is forced even if for skippable tasks.
  178. wait (bool): Wait for the orchestrated jobs created from the submission to be finished
  179. in asynchronous mode.
  180. timeout (Union[float, int]): The optional maximum number of seconds to wait
  181. for the jobs to be finished before returning.
  182. Returns:
  183. The created `Job^` or a collection of the created `Job^` depends on the submitted entity.
  184. - If a `Scenario^` or a `Sequence^` is provided, it will return a list of `Job^`.
  185. - If a `Task^` is provided, it will return the created `Job^`.
  186. """
  187. if _is_scenario(entity):
  188. return _ScenarioManagerFactory._build_manager()._submit(entity, force=force, wait=wait, timeout=timeout)
  189. if _is_sequence(entity):
  190. return _SequenceManagerFactory._build_manager()._submit(entity, force=force, wait=wait, timeout=timeout)
  191. if _is_task(entity):
  192. return _TaskManagerFactory._build_manager()._submit(entity, force=force, wait=wait, timeout=timeout)
  193. return None
  194. @overload
  195. def exists(entity_id: TaskId) -> bool:
  196. ...
  197. @overload
  198. def exists(entity_id: DataNodeId) -> bool:
  199. ...
  200. @overload
  201. def exists(entity_id: SequenceId) -> bool:
  202. ...
  203. @overload
  204. def exists(entity_id: ScenarioId) -> bool:
  205. ...
  206. @overload
  207. def exists(entity_id: CycleId) -> bool:
  208. ...
  209. @overload
  210. def exists(entity_id: JobId) -> bool:
  211. ...
  212. @overload
  213. def exists(entity_id: SubmissionId) -> bool:
  214. ...
  215. @overload
  216. def exists(entity_id: str) -> bool:
  217. ...
  218. def exists(entity_id: Union[TaskId, DataNodeId, SequenceId, ScenarioId, JobId, CycleId, SubmissionId, str]) -> bool:
  219. """Check if an entity with the specified identifier exists.
  220. This function checks if an entity with the given identifier exists.
  221. It supports various types of entity identifiers, including `TaskId^`,
  222. `DataNodeId^`, `SequenceId^`, `ScenarioId^`, `JobId^`, `CycleId^`, `SubmissionId^`, and string
  223. representations.
  224. Parameters:
  225. entity_id (Union[DataNodeId^, TaskId^, SequenceId^, ScenarioId^, JobId^, CycleId^]): The
  226. identifier of the entity to check for existence.
  227. Returns:
  228. True if the given entity exists. False otherwise.
  229. Raises:
  230. ModelNotFound: If the entity's type cannot be determined.
  231. Note:
  232. The function performs checks for various entity types
  233. (`Job^`, `Cycle^`, `Scenario^`, `Sequence^`, `Task^`, `DataNode^`)
  234. based on their respective identifier prefixes.
  235. """
  236. if _is_job(entity_id):
  237. return _JobManagerFactory._build_manager()._exists(JobId(entity_id))
  238. if _is_cycle(entity_id):
  239. return _CycleManagerFactory._build_manager()._exists(CycleId(entity_id))
  240. if _is_scenario(entity_id):
  241. return _ScenarioManagerFactory._build_manager()._exists(ScenarioId(entity_id))
  242. if _is_sequence(entity_id):
  243. return _SequenceManagerFactory._build_manager()._exists(SequenceId(entity_id))
  244. if _is_task(entity_id):
  245. return _TaskManagerFactory._build_manager()._exists(TaskId(entity_id))
  246. if _is_data_node(entity_id):
  247. return _DataManagerFactory._build_manager()._exists(DataNodeId(entity_id))
  248. if _is_submission(entity_id):
  249. return _SubmissionManagerFactory._build_manager()._exists(SubmissionId(entity_id))
  250. raise ModelNotFound("NOT_DETERMINED", entity_id)
  251. @overload
  252. def get(entity_id: TaskId) -> Task:
  253. ...
  254. @overload
  255. def get(entity_id: DataNodeId) -> DataNode:
  256. ...
  257. @overload
  258. def get(entity_id: SequenceId) -> Sequence:
  259. ...
  260. @overload
  261. def get(entity_id: ScenarioId) -> Scenario:
  262. ...
  263. @overload
  264. def get(entity_id: CycleId) -> Cycle:
  265. ...
  266. @overload
  267. def get(entity_id: JobId) -> Job:
  268. ...
  269. @overload
  270. def get(entity_id: SubmissionId) -> Submission:
  271. ...
  272. @overload
  273. def get(entity_id: str) -> Union[Task, DataNode, Sequence, Scenario, Job, Cycle, Submission]:
  274. ...
  275. def get(
  276. entity_id: Union[TaskId, DataNodeId, SequenceId, ScenarioId, JobId, CycleId, SubmissionId, str],
  277. ) -> Union[Task, DataNode, Sequence, Scenario, Job, Cycle, Submission]:
  278. """Retrieve an entity by its unique identifier.
  279. This function allows you to retrieve an entity by specifying its identifier.
  280. The identifier must match the pattern of one of the supported entity types:
  281. Task^, DataNode^, Sequence^, Job^, Cycle^, Submission^, or Scenario^.
  282. Parameters:
  283. entity_id (Union[TaskId, DataNodeId, SequenceId, ScenarioId, JobId, CycleId, str]):
  284. The identifier of the entity to retrieve.<br/>
  285. It should conform to the identifier pattern of one of the entities (`Task^`, `DataNode^`,
  286. `Sequence^`, `Job^`, `Cycle^` or `Scenario^`).
  287. Returns:
  288. The entity that corresponds to the provided identifier. Returns None if no matching entity is found.
  289. Raises:
  290. ModelNotFound^: If the provided *entity_id* does not match any known entity pattern.
  291. """
  292. if _is_job(entity_id):
  293. return _JobManagerFactory._build_manager()._get(JobId(entity_id))
  294. if _is_cycle(entity_id):
  295. return _CycleManagerFactory._build_manager()._get(CycleId(entity_id))
  296. if _is_scenario(entity_id):
  297. return _ScenarioManagerFactory._build_manager()._get(ScenarioId(entity_id))
  298. if _is_sequence(entity_id):
  299. return _SequenceManagerFactory._build_manager()._get(SequenceId(entity_id))
  300. if _is_task(entity_id):
  301. return _TaskManagerFactory._build_manager()._get(TaskId(entity_id))
  302. if _is_data_node(entity_id):
  303. return _DataManagerFactory._build_manager()._get(DataNodeId(entity_id))
  304. if _is_submission(entity_id):
  305. return _SubmissionManagerFactory._build_manager()._get(SubmissionId(entity_id))
  306. raise ModelNotFound("NOT_DETERMINED", entity_id)
  307. def get_tasks() -> List[Task]:
  308. """Retrieve a list of all existing tasks.
  309. This function returns a list of all tasks that currently exist.
  310. Returns:
  311. A list containing all the tasks.
  312. """
  313. return _TaskManagerFactory._build_manager()._get_all()
  314. def is_deletable(entity: Union[Scenario, Job, Submission, ScenarioId, JobId, SubmissionId]) -> bool:
  315. """Check if a `Scenario^`, a `Job^` or a `Submission^` can be deleted.
  316. This function determines whether a scenario or a job can be safely
  317. deleted without causing conflicts or issues.
  318. Parameters:
  319. entity (Union[Scenario, Job, Submission, ScenarioId, JobId, SubmissionId]): The scenario,
  320. job or submission to check.
  321. Returns:
  322. True if the given scenario, job or submission can be deleted. False otherwise.
  323. """
  324. if _is_job(entity):
  325. return _JobManagerFactory._build_manager()._is_deletable(entity)
  326. if _is_scenario(entity):
  327. return _ScenarioManagerFactory._build_manager()._is_deletable(entity)
  328. if _is_submission(entity):
  329. return _SubmissionManagerFactory._build_manager()._is_deletable(entity)
  330. return True
  331. def delete(entity_id: Union[TaskId, DataNodeId, SequenceId, ScenarioId, JobId, CycleId, SubmissionId]):
  332. """Delete an entity and its nested entities.
  333. This function deletes the specified entity and recursively deletes all its nested entities.
  334. The behavior varies depending on the type of entity provided:
  335. - If a `CycleId` is provided, the nested scenarios, tasks, data nodes, and jobs are deleted.
  336. - If a `ScenarioId` is provided, the nested sequences, tasks, data nodes, submissions and jobs are deleted.
  337. If the scenario is primary, it can only be deleted if it is the only scenario in the cycle.
  338. In that case, its cycle is also deleted. Use the `is_deletable()^` function to check if
  339. the scenario can be deleted.
  340. - If a `SequenceId` is provided, the related jobs are deleted.
  341. - If a `TaskId` is provided, the related data nodes, and jobs are deleted.
  342. - If a `DataNodeId` is provided, the data node is deleted.
  343. - If a `SubmissionId^` is provided, the related jobs are deleted.
  344. The submission can only be deleted if the execution has been finished.
  345. - If a `JobId^` is provided, the job entity can only be deleted if the execution has been finished.
  346. Parameters:
  347. entity_id (Union[TaskId, DataNodeId, SequenceId, ScenarioId, SubmissionId, JobId, CycleId]):
  348. The identifier of the entity to delete.
  349. Raises:
  350. ModelNotFound: No entity corresponds to the specified *entity_id*.
  351. """
  352. if _is_job(entity_id):
  353. job_manager = _JobManagerFactory._build_manager()
  354. return job_manager._delete(job_manager._get(JobId(entity_id)))
  355. if _is_cycle(entity_id):
  356. return _CycleManagerFactory._build_manager()._hard_delete(CycleId(entity_id))
  357. if _is_scenario(entity_id):
  358. return _ScenarioManagerFactory._build_manager()._hard_delete(ScenarioId(entity_id))
  359. if _is_sequence(entity_id):
  360. return _SequenceManagerFactory._build_manager()._hard_delete(SequenceId(entity_id))
  361. if _is_task(entity_id):
  362. return _TaskManagerFactory._build_manager()._hard_delete(TaskId(entity_id))
  363. if _is_data_node(entity_id):
  364. return _DataManagerFactory._build_manager()._delete(DataNodeId(entity_id))
  365. if _is_submission(entity_id):
  366. return _SubmissionManagerFactory._build_manager()._hard_delete(SubmissionId(entity_id))
  367. raise ModelNotFound("NOT_DETERMINED", entity_id)
  368. def get_scenarios(cycle: Optional[Cycle] = None, tag: Optional[str] = None) -> List[Scenario]:
  369. """Retrieve a list of existing scenarios filtered by cycle or tag.
  370. This function allows you to retrieve a list of scenarios based on optional
  371. filtering criteria. If both a _cycle_ and a _tag_ are provided, the returned
  372. list contains scenarios that belong to the specified _cycle_ **and** also
  373. have the specified _tag_.
  374. Parameters:
  375. cycle (Optional[Cycle^]): The optional `Cycle^` to filter scenarios by.
  376. tag (Optional[str]): The optional tag to filter scenarios by.
  377. Returns:
  378. The list of scenarios filtered by cycle or tag. If no filtering criteria
  379. are provided, this method returns all existing scenarios.
  380. """
  381. scenario_manager = _ScenarioManagerFactory._build_manager()
  382. if not cycle and not tag:
  383. return scenario_manager._get_all()
  384. if cycle and not tag:
  385. return scenario_manager._get_all_by_cycle(cycle)
  386. if not cycle and tag:
  387. return scenario_manager._get_all_by_tag(tag)
  388. if cycle and tag:
  389. cycles_scenarios = scenario_manager._get_all_by_cycle(cycle)
  390. return [scenario for scenario in cycles_scenarios if scenario.has_tag(tag)]
  391. return []
  392. def get_primary(cycle: Cycle) -> Optional[Scenario]:
  393. """Retrieve the primary scenario associated with a cycle.
  394. Parameters:
  395. cycle (Cycle^): The cycle for which to retrieve the primary scenario.
  396. Returns:
  397. The primary scenario of the given _cycle_. If the cycle has no
  398. primary scenario, this method returns None.
  399. """
  400. return _ScenarioManagerFactory._build_manager()._get_primary(cycle)
  401. def get_primary_scenarios() -> List[Scenario]:
  402. """Retrieve a list of all primary scenarios.
  403. Returns:
  404. A list containing all primary scenarios.
  405. """
  406. return _ScenarioManagerFactory._build_manager()._get_primary_scenarios()
  407. def is_promotable(scenario: Union[Scenario, ScenarioId]) -> bool:
  408. """Determine if a scenario can be promoted to become a primary scenario.
  409. This function checks whether the given scenario is eligible to be promoted
  410. as a primary scenario.
  411. Parameters:
  412. scenario (Union[Scenario, ScenarioId]): The scenario to be evaluated for promotability.
  413. Returns:
  414. True if the given scenario can be promoted to be a primary scenario. False otherwise.
  415. """
  416. return _ScenarioManagerFactory._build_manager()._is_promotable_to_primary(scenario)
  417. def set_primary(scenario: Scenario):
  418. """Promote a scenario as the primary scenario of its cycle.
  419. This function promotes the given scenario as the primary scenario of its associated cycle.
  420. If the cycle already has a primary scenario, that scenario is demoted and is
  421. no longer considered the primary scenario for its cycle.
  422. Parameters:
  423. scenario (Scenario^): The scenario to promote as the new _primary_ scenario.
  424. """
  425. return _ScenarioManagerFactory._build_manager()._set_primary(scenario)
  426. def tag(scenario: Scenario, tag: str):
  427. """Add a tag to a scenario.
  428. This function adds a user-defined tag to the specified scenario. If another scenario
  429. within the same cycle already has the same tag applied, the previous scenario is untagged.
  430. Parameters:
  431. scenario (Scenario^): The scenario to which the tag will be added.
  432. tag (str): The tag to apply to the scenario.
  433. """
  434. return _ScenarioManagerFactory._build_manager()._tag(scenario, tag)
  435. def untag(scenario: Scenario, tag: str):
  436. """Remove a tag from a scenario.
  437. This function removes a specified tag from the given scenario. If the scenario does
  438. not have the specified tag, it has no effect.
  439. Parameters:
  440. scenario (Scenario^): The scenario from which the tag will be removed.
  441. tag (str): The tag to remove from the scenario.
  442. """
  443. return _ScenarioManagerFactory._build_manager()._untag(scenario, tag)
  444. def compare_scenarios(*scenarios: Scenario, data_node_config_id: Optional[str] = None) -> Dict[str, Any]:
  445. """Compare the data nodes of several scenarios.
  446. You can specify which data node config identifier should the comparison be performed
  447. on.
  448. Parameters:
  449. *scenarios (*Scenario^): The list of the scenarios to compare.
  450. data_node_config_id (Optional[str]): The config identifier of the DataNode to perform
  451. the comparison on. <br/>
  452. If _data_node_config_id_ is not provided, the scenarios are
  453. compared on all defined comparators.<br/>
  454. Returns:
  455. The comparison results. The key is the data node config identifier used for
  456. comparison.
  457. Raises:
  458. InsufficientScenarioToCompare^: Raised when only one or no scenario for comparison
  459. is provided.
  460. NonExistingComparator^: Raised when the scenario comparator does not exist.
  461. DifferentScenarioConfigs^: Raised when the provided scenarios do not share the
  462. same scenario config.
  463. NonExistingScenarioConfig^: Raised when the scenario config of the provided
  464. scenarios could not be found.
  465. """
  466. return _ScenarioManagerFactory._build_manager()._compare(*scenarios, data_node_config_id=data_node_config_id)
  467. def subscribe_scenario(
  468. callback: Callable[[Scenario, Job], None],
  469. params: Optional[List[Any]] = None,
  470. scenario: Optional[Scenario] = None,
  471. ):
  472. """Subscribe a function to be called on job status change.
  473. The subscription is applied to all jobs created for the execution of _scenario_.
  474. If no scenario is provided, the subscription applies to all scenarios.
  475. Parameters:
  476. callback (Callable[[Scenario^, Job^], None]): The function to be called on
  477. status change.
  478. params (Optional[List[Any]]): The parameters to be passed to the _callback_.
  479. scenario (Optional[Scenario^]): The scenario to which the callback is applied.
  480. If None, the subscription is registered for all scenarios.
  481. Note:
  482. Notifications are applied only for jobs created **after** this subscription.
  483. """
  484. params = [] if params is None else params
  485. return _ScenarioManagerFactory._build_manager()._subscribe(callback, params, scenario)
  486. def unsubscribe_scenario(
  487. callback: Callable[[Scenario, Job], None], params: Optional[List[Any]] = None, scenario: Optional[Scenario] = None
  488. ):
  489. """Unsubscribe a function that is called when the status of a `Job^` changes.
  490. If no scenario is provided, the subscription is removed for all scenarios.
  491. Parameters:
  492. callback (Callable[[Scenario^, Job^], None]): The function to unsubscribe from.
  493. params (Optional[List[Any]]): The parameters to be passed to the callback.
  494. scenario (Optional[Scenario]): The scenario to unsubscribe from. If None, it
  495. applies to all scenarios.
  496. Note:
  497. The callback function will continue to be called for ongoing jobs.
  498. """
  499. return _ScenarioManagerFactory._build_manager()._unsubscribe(callback, params, scenario)
  500. def subscribe_sequence(
  501. callback: Callable[[Sequence, Job], None], params: Optional[List[Any]] = None, sequence: Optional[Sequence] = None
  502. ):
  503. """Subscribe a function to be called on job status change.
  504. The subscription is applied to all jobs created for the execution of _sequence_.
  505. Parameters:
  506. callback (Callable[[Sequence^, Job^], None]): The callable function to be called on
  507. status change.
  508. params (Optional[List[Any]]): The parameters to be passed to the _callback_.
  509. sequence (Optional[Sequence^]): The sequence to subscribe on. If None, the subscription
  510. is applied to all sequences.
  511. Note:
  512. Notifications are applied only for jobs created **after** this subscription.
  513. """
  514. return _SequenceManagerFactory._build_manager()._subscribe(callback, params, sequence)
  515. def unsubscribe_sequence(
  516. callback: Callable[[Sequence, Job], None], params: Optional[List[Any]] = None, sequence: Optional[Sequence] = None
  517. ):
  518. """Unsubscribe a function that is called when the status of a Job changes.
  519. Parameters:
  520. callback (Callable[[Sequence^, Job^], None]): The callable function to be called on
  521. status change.
  522. params (Optional[List[Any]]): The parameters to be passed to the _callback_.
  523. sequence (Optional[Sequence^]): The sequence to unsubscribe to. If None, it applies
  524. to all sequences.
  525. Note:
  526. The function will continue to be called for ongoing jobs.
  527. """
  528. return _SequenceManagerFactory._build_manager()._unsubscribe(callback, params, sequence)
  529. def get_sequences() -> List[Sequence]:
  530. """Return all existing sequences.
  531. Returns:
  532. The list of all sequences.
  533. """
  534. return _SequenceManagerFactory._build_manager()._get_all()
  535. def get_jobs() -> List[Job]:
  536. """Return all the existing jobs.
  537. Returns:
  538. The list of all jobs.
  539. """
  540. return _JobManagerFactory._build_manager()._get_all()
  541. def delete_job(job: Job, force: Optional[bool] = False):
  542. """Delete a job.
  543. This function deletes the specified job. If the job is not completed and
  544. *force* is not set to True, a `JobNotDeletedException^` may be raised.
  545. Parameters:
  546. job (Job^): The job to delete.
  547. force (Optional[bool]): If True, forces the deletion of _job_, even
  548. if it is not completed yet.
  549. Raises:
  550. JobNotDeletedException^: If the job is not finished.
  551. """
  552. return _JobManagerFactory._build_manager()._delete(job, force)
  553. def delete_jobs():
  554. """Delete all jobs."""
  555. return _JobManagerFactory._build_manager()._delete_all()
  556. def cancel_job(job: Union[str, Job]):
  557. """Cancel a job and set the status of the subsequent jobs to ABANDONED.
  558. This function cancels the specified job and sets the status of any subsequent jobs to ABANDONED.
  559. Parameters:
  560. job (Job^): The job to cancel.
  561. """
  562. _JobManagerFactory._build_manager()._cancel(job)
  563. def get_latest_job(task: Task) -> Optional[Job]:
  564. """Return the latest job of a task.
  565. This function retrieves the latest job associated with a task.
  566. Parameters:
  567. task (Task^): The task to retrieve the latest job from.
  568. Returns:
  569. The latest job created from _task_, or None if no job has been created from _task_.
  570. """
  571. return _JobManagerFactory._build_manager()._get_latest(task)
  572. def get_latest_submission(entity: Union[Scenario, Sequence, Task]) -> Optional[Submission]:
  573. """Return the latest submission of a scenario, sequence or task.
  574. This function retrieves the latest submission associated with a scenario, sequence or task.
  575. Parameters:
  576. entity (Union[Scenario^, Sequence^, Task^]): The scenario, sequence or task to
  577. retrieve the latest submission from.
  578. Returns:
  579. The latest submission created from _scenario_, _sequence_ and _task_, or None
  580. if no submission has been created from _scenario_, _sequence_ and _task_.
  581. """
  582. return _SubmissionManagerFactory._build_manager()._get_latest(entity)
  583. def get_data_nodes() -> List[DataNode]:
  584. """Return all the existing data nodes.
  585. Returns:
  586. The list of all data nodes.
  587. """
  588. return _DataManagerFactory._build_manager()._get_all()
  589. def get_cycles() -> List[Cycle]:
  590. """Return the list of all existing cycles.
  591. Returns:
  592. The list of all cycles.
  593. """
  594. return _CycleManagerFactory._build_manager()._get_all()
  595. def create_scenario(
  596. config: ScenarioConfig,
  597. creation_date: Optional[datetime] = None,
  598. name: Optional[str] = None,
  599. ) -> Scenario:
  600. """Create and return a new scenario based on a scenario configuration.
  601. If the scenario belongs to a cycle, a cycle (corresponding to the _creation_date_
  602. and the configuration frequency attribute) is created if it does not exist yet.
  603. Parameters:
  604. config (ScenarioConfig^): The scenario configuration used to create a new scenario.
  605. creation_date (Optional[datetime.datetime]): The creation date of the scenario.
  606. If None, the current date time is used.
  607. name (Optional[str]): The displayable name of the scenario.
  608. Returns:
  609. The new scenario.
  610. """
  611. return _ScenarioManagerFactory._build_manager()._create(config, creation_date, name)
  612. def create_global_data_node(config: DataNodeConfig) -> DataNode:
  613. """Create and return a new GLOBAL data node from a data node configuration.
  614. Parameters:
  615. config (DataNodeConfig^): The data node configuration. It must have a `GLOBAL` scope.
  616. Returns:
  617. The new global data node.
  618. Raises:
  619. DataNodeConfigIsNotGlobal^: If the data node configuration does not have GLOBAL scope.
  620. """
  621. # Check if the data node config has GLOBAL scope
  622. if config.scope is not Scope.GLOBAL:
  623. raise DataNodeConfigIsNotGlobal(config.id)
  624. if dns := _DataManagerFactory._build_manager()._get_by_config_id(config.id):
  625. return dns[0]
  626. return _DataManagerFactory._build_manager()._create_and_set(config, None, None)
  627. def clean_all_entities_by_version(version_number=None) -> bool:
  628. """Delete all entities of a specific version.
  629. This function deletes all entities associated with the specified version.
  630. Parameters:
  631. version_number (optional[str]): The version number of the entities to be deleted.
  632. If None, the default behavior may apply.
  633. Returns:
  634. True if the operation succeeded, False otherwise.
  635. Notes:
  636. - If the specified version does not exist, the operation will be aborted, and False will be returned.
  637. - This function cleans all entities, including jobs, scenarios, sequences, tasks, and data nodes.
  638. - The production version of the specified version is also deleted if it exists.
  639. """
  640. version_manager = _VersionManagerFactory._build_manager()
  641. try:
  642. version_number = version_manager._replace_version_number(version_number)
  643. except NonExistingVersion as e:
  644. __logger.warning(f"{e.message} Abort cleaning the entities of version '{version_number}'.")
  645. return False
  646. _JobManagerFactory._build_manager()._delete_by_version(version_number)
  647. _SubmissionManagerFactory._build_manager()._delete_by_version(version_number)
  648. _ScenarioManagerFactory._build_manager()._delete_by_version(version_number)
  649. _SequenceManagerFactory._build_manager()._delete_by_version(version_number)
  650. _TaskManagerFactory._build_manager()._delete_by_version(version_number)
  651. _DataManagerFactory._build_manager()._delete_by_version(version_number)
  652. version_manager._delete(version_number)
  653. try:
  654. version_manager._delete_production_version(version_number)
  655. except VersionIsNotProductionVersion:
  656. pass
  657. return True
  658. def export_scenario(
  659. scenario_id: ScenarioId,
  660. folder_path: Union[str, pathlib.Path],
  661. ):
  662. """Export all related entities of a scenario to a folder.
  663. This function exports all related entities of the specified scenario to the
  664. specified folder.
  665. Parameters:
  666. scenario_id (ScenarioId): The ID of the scenario to export.
  667. folder_path (Union[str, pathlib.Path]): The folder path to export the scenario to.
  668. """
  669. manager = _ScenarioManagerFactory._build_manager()
  670. scenario = manager._get(scenario_id)
  671. entity_ids = manager._get_children_entity_ids(scenario)
  672. entity_ids.scenario_ids = {scenario_id}
  673. entity_ids.cycle_ids = {scenario.cycle.id}
  674. shutil.rmtree(folder_path, ignore_errors=True)
  675. for data_node_id in entity_ids.data_node_ids:
  676. _DataManagerFactory._build_manager()._export(data_node_id, folder_path)
  677. for task_id in entity_ids.task_ids:
  678. _TaskManagerFactory._build_manager()._export(task_id, folder_path)
  679. for sequence_id in entity_ids.sequence_ids:
  680. _SequenceManagerFactory._build_manager()._export(sequence_id, folder_path)
  681. for cycle_id in entity_ids.cycle_ids:
  682. _CycleManagerFactory._build_manager()._export(cycle_id, folder_path)
  683. for scenario_id in entity_ids.scenario_ids:
  684. _ScenarioManagerFactory._build_manager()._export(scenario_id, folder_path)
  685. for job_id in entity_ids.job_ids:
  686. _JobManagerFactory._build_manager()._export(job_id, folder_path)
  687. def get_parents(
  688. entity: Union[TaskId, DataNodeId, SequenceId, Task, DataNode, Sequence], parent_dict=None
  689. ) -> Dict[str, Set[_Entity]]:
  690. """Get the parents of an entity from itself or its identifier.
  691. Parameters:
  692. entity (Union[TaskId, DataNodeId, SequenceId, Task, DataNode, Sequence]): The entity or its
  693. identifier to get the parents.
  694. Returns:
  695. The dictionary of all parent entities.
  696. They are grouped by their type (Scenario^, Sequences^, or tasks^) so each key corresponds
  697. to a level of the parents and the value is a set of the parent entities.
  698. An empty dictionary is returned if the entity does not have parents.<br/>
  699. Example: The following instruction returns all the scenarios that include the
  700. datanode identified by "my_datanode_id".
  701. `taipy.get_parents("id_of_my_datanode")["scenario"]`
  702. Raises:
  703. ModelNotFound^: If _entity_ does not match a correct entity pattern.
  704. """
  705. def update_parent_dict(parents_set, parent_dict):
  706. for k, value in parents_set.items():
  707. if k in parent_dict.keys():
  708. parent_dict[k].update(value)
  709. else:
  710. parent_dict[k] = value
  711. if isinstance(entity, str):
  712. entity = get(entity)
  713. parent_dict = parent_dict or dict()
  714. if isinstance(entity, (Scenario, Cycle)):
  715. return parent_dict
  716. current_parent_dict: Dict[str, Set] = {}
  717. for parent in entity.parent_ids:
  718. parent_entity = get(parent)
  719. if parent_entity._MANAGER_NAME in current_parent_dict.keys():
  720. current_parent_dict[parent_entity._MANAGER_NAME].add(parent_entity)
  721. else:
  722. current_parent_dict[parent_entity._MANAGER_NAME] = {parent_entity}
  723. if isinstance(entity, Sequence):
  724. update_parent_dict(current_parent_dict, parent_dict)
  725. if isinstance(entity, Task):
  726. parent_entity_key_to_search_next = "scenario"
  727. update_parent_dict(current_parent_dict, parent_dict)
  728. for parent in parent_dict.get(parent_entity_key_to_search_next, []):
  729. get_parents(parent, parent_dict)
  730. if isinstance(entity, DataNode):
  731. parent_entity_key_to_search_next = "task"
  732. update_parent_dict(current_parent_dict, parent_dict)
  733. for parent in parent_dict.get(parent_entity_key_to_search_next, []):
  734. get_parents(parent, parent_dict)
  735. return parent_dict
  736. def get_cycles_scenarios() -> Dict[Optional[Cycle], List[Scenario]]:
  737. """Get the scenarios grouped by cycles.
  738. Returns:
  739. The dictionary of all cycles and their corresponding scenarios.
  740. """
  741. cycles_scenarios: Dict[Optional[Cycle], List[Scenario]] = {}
  742. for scenario in get_scenarios():
  743. if scenario.cycle in cycles_scenarios.keys():
  744. cycles_scenarios[scenario.cycle].append(scenario)
  745. else:
  746. cycles_scenarios[scenario.cycle] = [scenario]
  747. return cycles_scenarios
  748. def get_entities_by_config_id(
  749. config_id: str,
  750. ) -> Union[List, List[Task], List[DataNode], List[Sequence], List[Scenario]]:
  751. """Get the entities by its config id.
  752. Parameters:
  753. config_id (str): The config id of the entities
  754. Returns:
  755. The list of all entities by the config id.
  756. """
  757. entities: List = []
  758. if entities := _ScenarioManagerFactory._build_manager()._get_by_config_id(config_id):
  759. return entities
  760. if entities := _TaskManagerFactory._build_manager()._get_by_config_id(config_id):
  761. return entities
  762. if entities := _DataManagerFactory._build_manager()._get_by_config_id(config_id):
  763. return entities
  764. return entities