taipy.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  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 os
  12. import pathlib
  13. import shutil
  14. import tempfile
  15. from datetime import datetime
  16. from typing import Any, Callable, Dict, List, Literal, Optional, Set, Type, Union, overload
  17. from taipy.config import Scope
  18. from taipy.logger._taipy_logger import _TaipyLogger
  19. from ._core import Core
  20. from ._entity._entity import _Entity
  21. from ._manager._manager import _Manager
  22. from ._version._version_manager_factory import _VersionManagerFactory
  23. from .common._check_instance import (
  24. _is_cycle,
  25. _is_data_node,
  26. _is_job,
  27. _is_scenario,
  28. _is_sequence,
  29. _is_submission,
  30. _is_task,
  31. )
  32. from .common._warnings import _warn_deprecated, _warn_no_core_service
  33. from .common.reason import Reason
  34. from .config.data_node_config import DataNodeConfig
  35. from .config.scenario_config import ScenarioConfig
  36. from .cycle._cycle_manager_factory import _CycleManagerFactory
  37. from .cycle.cycle import Cycle
  38. from .cycle.cycle_id import CycleId
  39. from .data._data_manager_factory import _DataManagerFactory
  40. from .data.data_node import DataNode
  41. from .data.data_node_id import DataNodeId
  42. from .exceptions.exceptions import (
  43. DataNodeConfigIsNotGlobal,
  44. ExportPathAlreadyExists,
  45. ModelNotFound,
  46. NonExistingVersion,
  47. VersionIsNotProductionVersion,
  48. )
  49. from .job._job_manager_factory import _JobManagerFactory
  50. from .job.job import Job
  51. from .job.job_id import JobId
  52. from .scenario._scenario_manager_factory import _ScenarioManagerFactory
  53. from .scenario.scenario import Scenario
  54. from .scenario.scenario_id import ScenarioId
  55. from .sequence._sequence_manager_factory import _SequenceManagerFactory
  56. from .sequence.sequence import Sequence
  57. from .sequence.sequence_id import SequenceId
  58. from .submission._submission_manager_factory import _SubmissionManagerFactory
  59. from .submission.submission import Submission, SubmissionId
  60. from .task._task_manager_factory import _TaskManagerFactory
  61. from .task.task import Task
  62. from .task.task_id import TaskId
  63. __logger = _TaipyLogger._get_logger()
  64. def set(entity: Union[DataNode, Task, Sequence, Scenario, Cycle, Submission]):
  65. """Save or update an entity.
  66. This function allows you to save or update an entity in Taipy.
  67. Parameters:
  68. entity (Union[DataNode^, Task^, Sequence^, Scenario^, Cycle^, Submission^]): The
  69. entity to save or update.
  70. """
  71. if isinstance(entity, Cycle):
  72. return _CycleManagerFactory._build_manager()._set(entity)
  73. if isinstance(entity, Scenario):
  74. return _ScenarioManagerFactory._build_manager()._set(entity)
  75. if isinstance(entity, Sequence):
  76. return _SequenceManagerFactory._build_manager()._set(entity)
  77. if isinstance(entity, Task):
  78. return _TaskManagerFactory._build_manager()._set(entity)
  79. if isinstance(entity, DataNode):
  80. return _DataManagerFactory._build_manager()._set(entity)
  81. if isinstance(entity, Submission):
  82. return _SubmissionManagerFactory._build_manager()._set(entity)
  83. def is_submittable(entity: Union[Scenario, ScenarioId, Sequence, SequenceId, Task, TaskId, str]) -> Reason:
  84. """Indicate if an entity can be submitted.
  85. This function checks if the given entity can be submitted for execution.
  86. Returns:
  87. True if the given entity can be submitted. False otherwise.
  88. """
  89. if isinstance(entity, Scenario):
  90. return _ScenarioManagerFactory._build_manager()._is_submittable(entity)
  91. if isinstance(entity, str) and entity.startswith(Scenario._ID_PREFIX):
  92. return _ScenarioManagerFactory._build_manager()._is_submittable(ScenarioId(entity))
  93. if isinstance(entity, Sequence):
  94. return _SequenceManagerFactory._build_manager()._is_submittable(entity)
  95. if isinstance(entity, str) and entity.startswith(Sequence._ID_PREFIX):
  96. return _SequenceManagerFactory._build_manager()._is_submittable(SequenceId(entity))
  97. if isinstance(entity, Task):
  98. return _TaskManagerFactory._build_manager()._is_submittable(entity)
  99. if isinstance(entity, str) and entity.startswith(Task._ID_PREFIX):
  100. return _TaskManagerFactory._build_manager()._is_submittable(TaskId(entity))
  101. return Reason(str(entity))._add_reason(str(entity), _Manager._build_not_submittable_entity_reason(str(entity)))
  102. def is_editable(
  103. entity: Union[
  104. DataNode,
  105. Task,
  106. Job,
  107. Sequence,
  108. Scenario,
  109. Cycle,
  110. Submission,
  111. DataNodeId,
  112. TaskId,
  113. JobId,
  114. SequenceId,
  115. ScenarioId,
  116. CycleId,
  117. SubmissionId,
  118. ],
  119. ) -> bool:
  120. """Indicate if an entity can be edited.
  121. This function checks if the given entity can be edited.
  122. Returns:
  123. True if the given entity can be edited. False otherwise.
  124. """
  125. if isinstance(entity, Cycle):
  126. return _CycleManagerFactory._build_manager()._is_editable(entity)
  127. if isinstance(entity, str) and entity.startswith(Cycle._ID_PREFIX):
  128. return _CycleManagerFactory._build_manager()._is_editable(CycleId(entity))
  129. if isinstance(entity, Scenario):
  130. return _ScenarioManagerFactory._build_manager()._is_editable(entity)
  131. if isinstance(entity, str) and entity.startswith(Scenario._ID_PREFIX):
  132. return _ScenarioManagerFactory._build_manager()._is_editable(ScenarioId(entity))
  133. if isinstance(entity, Sequence):
  134. return _SequenceManagerFactory._build_manager()._is_editable(entity)
  135. if isinstance(entity, str) and entity.startswith(Sequence._ID_PREFIX):
  136. return _SequenceManagerFactory._build_manager()._is_editable(SequenceId(entity))
  137. if isinstance(entity, Task):
  138. return _TaskManagerFactory._build_manager()._is_editable(entity)
  139. if isinstance(entity, str) and entity.startswith(Task._ID_PREFIX):
  140. return _TaskManagerFactory._build_manager()._is_editable(TaskId(entity))
  141. if isinstance(entity, Job):
  142. return _JobManagerFactory._build_manager()._is_editable(entity)
  143. if isinstance(entity, str) and entity.startswith(Job._ID_PREFIX):
  144. return _JobManagerFactory._build_manager()._is_editable(JobId(entity))
  145. if isinstance(entity, DataNode):
  146. return _DataManagerFactory._build_manager()._is_editable(entity)
  147. if isinstance(entity, str) and entity.startswith(DataNode._ID_PREFIX):
  148. return _DataManagerFactory._build_manager()._is_editable(DataNodeId(entity))
  149. if isinstance(entity, Submission):
  150. return _SubmissionManagerFactory._build_manager()._is_editable(entity)
  151. if isinstance(entity, str) and entity.startswith(Submission._ID_PREFIX):
  152. return _SubmissionManagerFactory._build_manager()._is_editable(SequenceId(entity))
  153. return False
  154. def is_readable(
  155. entity: Union[
  156. DataNode,
  157. Task,
  158. Job,
  159. Sequence,
  160. Scenario,
  161. Cycle,
  162. Submission,
  163. DataNodeId,
  164. TaskId,
  165. JobId,
  166. SequenceId,
  167. ScenarioId,
  168. CycleId,
  169. SubmissionId,
  170. ],
  171. ) -> bool:
  172. """Indicate if an entity can be read.
  173. This function checks if the given entity can be read.
  174. Returns:
  175. True if the given entity can be read. False otherwise.
  176. """
  177. if isinstance(entity, Cycle):
  178. return _CycleManagerFactory._build_manager()._is_readable(entity)
  179. if isinstance(entity, str) and entity.startswith(Cycle._ID_PREFIX):
  180. return _CycleManagerFactory._build_manager()._is_readable(CycleId(entity))
  181. if isinstance(entity, Scenario):
  182. return _ScenarioManagerFactory._build_manager()._is_readable(entity)
  183. if isinstance(entity, str) and entity.startswith(Scenario._ID_PREFIX):
  184. return _ScenarioManagerFactory._build_manager()._is_readable(ScenarioId(entity))
  185. if isinstance(entity, Sequence):
  186. return _SequenceManagerFactory._build_manager()._is_readable(entity)
  187. if isinstance(entity, str) and entity.startswith(Sequence._ID_PREFIX):
  188. return _SequenceManagerFactory._build_manager()._is_readable(SequenceId(entity))
  189. if isinstance(entity, Task):
  190. return _TaskManagerFactory._build_manager()._is_readable(entity)
  191. if isinstance(entity, str) and entity.startswith(Task._ID_PREFIX):
  192. return _TaskManagerFactory._build_manager()._is_readable(TaskId(entity))
  193. if isinstance(entity, Job):
  194. return _JobManagerFactory._build_manager()._is_readable(entity)
  195. if isinstance(entity, str) and entity.startswith(Job._ID_PREFIX):
  196. return _JobManagerFactory._build_manager()._is_readable(JobId(entity))
  197. if isinstance(entity, DataNode):
  198. return _DataManagerFactory._build_manager()._is_readable(entity)
  199. if isinstance(entity, str) and entity.startswith(DataNode._ID_PREFIX):
  200. return _DataManagerFactory._build_manager()._is_readable(DataNodeId(entity))
  201. if isinstance(entity, Submission):
  202. return _SubmissionManagerFactory._build_manager()._is_readable(entity)
  203. if isinstance(entity, str) and entity.startswith(Submission._ID_PREFIX):
  204. return _SubmissionManagerFactory._build_manager()._is_readable(SequenceId(entity))
  205. return False
  206. @_warn_no_core_service("The submitted entity will not be executed until the Core service is running.")
  207. def submit(
  208. entity: Union[Scenario, Sequence, Task],
  209. force: bool = False,
  210. wait: bool = False,
  211. timeout: Optional[Union[float, int]] = None,
  212. **properties,
  213. ) -> Submission:
  214. """Submit a scenario, sequence or task entity for execution.
  215. This function submits the given entity for execution and returns the created job(s).
  216. If the entity is a sequence or a scenario, all the tasks of the entity are
  217. submitted for execution.
  218. Parameters:
  219. entity (Union[Scenario^, Sequence^, Task^]): The scenario, sequence or task to submit.
  220. force (bool): If True, the execution is forced even if for skippable tasks.
  221. wait (bool): Wait for the orchestrated jobs created from the submission to be finished
  222. in asynchronous mode.
  223. timeout (Union[float, int]): The optional maximum number of seconds to wait
  224. for the jobs to be finished before returning.
  225. **properties (dict[str, any]): A key-worded variable length list of user additional arguments
  226. that will be stored within the `Submission^`. It can be accessed via `Submission.properties^`.
  227. Returns:
  228. The created `Submission^` containing the information about the submission.
  229. """
  230. if isinstance(entity, Scenario):
  231. return _ScenarioManagerFactory._build_manager()._submit(
  232. entity, force=force, wait=wait, timeout=timeout, **properties
  233. )
  234. if isinstance(entity, Sequence):
  235. return _SequenceManagerFactory._build_manager()._submit(
  236. entity, force=force, wait=wait, timeout=timeout, **properties
  237. )
  238. if isinstance(entity, Task):
  239. return _TaskManagerFactory._build_manager()._submit(
  240. entity, force=force, wait=wait, timeout=timeout, **properties
  241. )
  242. return None
  243. @overload
  244. def exists(entity_id: TaskId) -> bool:
  245. ...
  246. @overload
  247. def exists(entity_id: DataNodeId) -> bool:
  248. ...
  249. @overload
  250. def exists(entity_id: SequenceId) -> bool:
  251. ...
  252. @overload
  253. def exists(entity_id: ScenarioId) -> bool:
  254. ...
  255. @overload
  256. def exists(entity_id: CycleId) -> bool:
  257. ...
  258. @overload
  259. def exists(entity_id: JobId) -> bool:
  260. ...
  261. @overload
  262. def exists(entity_id: SubmissionId) -> bool:
  263. ...
  264. @overload
  265. def exists(entity_id: str) -> bool:
  266. ...
  267. def exists(entity_id: Union[TaskId, DataNodeId, SequenceId, ScenarioId, JobId, CycleId, SubmissionId, str]) -> bool:
  268. """Check if an entity with the specified identifier exists.
  269. This function checks if an entity with the given identifier exists.
  270. It supports various types of entity identifiers, including `TaskId^`,
  271. `DataNodeId^`, `SequenceId^`, `ScenarioId^`, `JobId^`, `CycleId^`, `SubmissionId^`, and string
  272. representations.
  273. Parameters:
  274. entity_id (Union[DataNodeId^, TaskId^, SequenceId^, ScenarioId^, JobId^, CycleId^, SubmissionId^, str]): The
  275. identifier of the entity to check for existence.
  276. Returns:
  277. True if the given entity exists. False otherwise.
  278. Raises:
  279. ModelNotFound: If the entity's type cannot be determined.
  280. Note:
  281. The function performs checks for various entity types
  282. (`Job^`, `Cycle^`, `Scenario^`, `Sequence^`, `Task^`, `DataNode^`, `Submission^`)
  283. based on their respective identifier prefixes.
  284. """
  285. if _is_job(entity_id):
  286. return _JobManagerFactory._build_manager()._exists(JobId(entity_id))
  287. if _is_cycle(entity_id):
  288. return _CycleManagerFactory._build_manager()._exists(CycleId(entity_id))
  289. if _is_scenario(entity_id):
  290. return _ScenarioManagerFactory._build_manager()._exists(ScenarioId(entity_id))
  291. if _is_sequence(entity_id):
  292. return _SequenceManagerFactory._build_manager()._exists(SequenceId(entity_id))
  293. if _is_task(entity_id):
  294. return _TaskManagerFactory._build_manager()._exists(TaskId(entity_id))
  295. if _is_data_node(entity_id):
  296. return _DataManagerFactory._build_manager()._exists(DataNodeId(entity_id))
  297. if _is_submission(entity_id):
  298. return _SubmissionManagerFactory._build_manager()._exists(SubmissionId(entity_id))
  299. raise ModelNotFound("NOT_DETERMINED", entity_id)
  300. @overload
  301. def get(entity_id: TaskId) -> Task:
  302. ...
  303. @overload
  304. def get(entity_id: DataNodeId) -> DataNode:
  305. ...
  306. @overload
  307. def get(entity_id: SequenceId) -> Sequence:
  308. ...
  309. @overload
  310. def get(entity_id: ScenarioId) -> Scenario:
  311. ...
  312. @overload
  313. def get(entity_id: CycleId) -> Cycle:
  314. ...
  315. @overload
  316. def get(entity_id: JobId) -> Job:
  317. ...
  318. @overload
  319. def get(entity_id: SubmissionId) -> Submission:
  320. ...
  321. @overload
  322. def get(entity_id: str) -> Union[Task, DataNode, Sequence, Scenario, Job, Cycle, Submission]:
  323. ...
  324. def get(
  325. entity_id: Union[TaskId, DataNodeId, SequenceId, ScenarioId, JobId, CycleId, SubmissionId, str],
  326. ) -> Union[Task, DataNode, Sequence, Scenario, Job, Cycle, Submission]:
  327. """Retrieve an entity by its unique identifier.
  328. This function allows you to retrieve an entity by specifying its identifier.
  329. The identifier must match the pattern of one of the supported entity types:
  330. Task^, DataNode^, Sequence^, Job^, Cycle^, Submission^, or Scenario^.
  331. Parameters:
  332. entity_id (Union[TaskId, DataNodeId, SequenceId, ScenarioId, JobId, CycleId, str]):
  333. The identifier of the entity to retrieve.<br/>
  334. It should conform to the identifier pattern of one of the entities (`Task^`, `DataNode^`,
  335. `Sequence^`, `Job^`, `Cycle^` or `Scenario^`).
  336. Returns:
  337. The entity that corresponds to the provided identifier. Returns None if no matching entity is found.
  338. Raises:
  339. ModelNotFound^: If the provided *entity_id* does not match any known entity pattern.
  340. """
  341. if _is_job(entity_id):
  342. return _JobManagerFactory._build_manager()._get(JobId(entity_id))
  343. if _is_cycle(entity_id):
  344. return _CycleManagerFactory._build_manager()._get(CycleId(entity_id))
  345. if _is_scenario(entity_id):
  346. return _ScenarioManagerFactory._build_manager()._get(ScenarioId(entity_id))
  347. if _is_sequence(entity_id):
  348. return _SequenceManagerFactory._build_manager()._get(SequenceId(entity_id))
  349. if _is_task(entity_id):
  350. return _TaskManagerFactory._build_manager()._get(TaskId(entity_id))
  351. if _is_data_node(entity_id):
  352. return _DataManagerFactory._build_manager()._get(DataNodeId(entity_id))
  353. if _is_submission(entity_id):
  354. return _SubmissionManagerFactory._build_manager()._get(SubmissionId(entity_id))
  355. raise ModelNotFound("NOT_DETERMINED", entity_id)
  356. def get_tasks() -> List[Task]:
  357. """Retrieve a list of all existing tasks.
  358. This function returns a list of all tasks that currently exist.
  359. Returns:
  360. A list containing all the tasks.
  361. """
  362. return _TaskManagerFactory._build_manager()._get_all()
  363. def is_deletable(entity: Union[Scenario, Job, Submission, ScenarioId, JobId, SubmissionId]) -> bool:
  364. """Check if a `Scenario^`, a `Job^` or a `Submission^` can be deleted.
  365. This function determines whether a scenario or a job can be safely
  366. deleted without causing conflicts or issues.
  367. Parameters:
  368. entity (Union[Scenario, Job, Submission, ScenarioId, JobId, SubmissionId]): The scenario,
  369. job or submission to check.
  370. Returns:
  371. True if the given scenario, job or submission can be deleted. False otherwise.
  372. """
  373. if isinstance(entity, Job):
  374. return _JobManagerFactory._build_manager()._is_deletable(entity)
  375. if isinstance(entity, str) and entity.startswith(Job._ID_PREFIX):
  376. return _JobManagerFactory._build_manager()._is_deletable(JobId(entity))
  377. if isinstance(entity, Scenario):
  378. return _ScenarioManagerFactory._build_manager()._is_deletable(entity)
  379. if isinstance(entity, str) and entity.startswith(Scenario._ID_PREFIX):
  380. return _ScenarioManagerFactory._build_manager()._is_deletable(ScenarioId(entity))
  381. if isinstance(entity, Submission):
  382. return _SubmissionManagerFactory._build_manager()._is_deletable(entity)
  383. if isinstance(entity, str) and entity.startswith(Submission._ID_PREFIX):
  384. return _SubmissionManagerFactory._build_manager()._is_deletable(SubmissionId(entity))
  385. return True
  386. def delete(entity_id: Union[TaskId, DataNodeId, SequenceId, ScenarioId, JobId, CycleId, SubmissionId]):
  387. """Delete an entity and its nested entities.
  388. This function deletes the specified entity and recursively deletes all its nested entities.
  389. The behavior varies depending on the type of entity provided:
  390. - If a `CycleId` is provided, the nested scenarios, tasks, data nodes, and jobs are deleted.
  391. - If a `ScenarioId` is provided, the nested sequences, tasks, data nodes, submissions and jobs are deleted.
  392. If the scenario is primary, it can only be deleted if it is the only scenario in the cycle.
  393. In that case, its cycle is also deleted. Use the `is_deletable()^` function to check if
  394. the scenario can be deleted.
  395. - If a `SequenceId` is provided, the related jobs are deleted.
  396. - If a `TaskId` is provided, the related data nodes, and jobs are deleted.
  397. - If a `DataNodeId` is provided, the data node is deleted.
  398. - If a `SubmissionId^` is provided, the related jobs are deleted.
  399. The submission can only be deleted if the execution has been finished.
  400. - If a `JobId^` is provided, the job entity can only be deleted if the execution has been finished.
  401. Parameters:
  402. entity_id (Union[TaskId, DataNodeId, SequenceId, ScenarioId, SubmissionId, JobId, CycleId]):
  403. The identifier of the entity to delete.
  404. Raises:
  405. ModelNotFound: No entity corresponds to the specified *entity_id*.
  406. """
  407. if _is_job(entity_id):
  408. job_manager = _JobManagerFactory._build_manager()
  409. return job_manager._delete(job_manager._get(JobId(entity_id)))
  410. if _is_cycle(entity_id):
  411. return _CycleManagerFactory._build_manager()._hard_delete(CycleId(entity_id))
  412. if _is_scenario(entity_id):
  413. return _ScenarioManagerFactory._build_manager()._hard_delete(ScenarioId(entity_id))
  414. if _is_sequence(entity_id):
  415. return _SequenceManagerFactory._build_manager()._hard_delete(SequenceId(entity_id))
  416. if _is_task(entity_id):
  417. return _TaskManagerFactory._build_manager()._hard_delete(TaskId(entity_id))
  418. if _is_data_node(entity_id):
  419. return _DataManagerFactory._build_manager()._delete(DataNodeId(entity_id))
  420. if _is_submission(entity_id):
  421. return _SubmissionManagerFactory._build_manager()._hard_delete(SubmissionId(entity_id))
  422. raise ModelNotFound("NOT_DETERMINED", entity_id)
  423. def get_scenarios(
  424. cycle: Optional[Cycle] = None,
  425. tag: Optional[str] = None,
  426. is_sorted: bool = False,
  427. descending: bool = False,
  428. sort_key: Literal["name", "id", "config_id", "creation_date", "tags"] = "name",
  429. ) -> List[Scenario]:
  430. """Retrieve a list of existing scenarios filtered by cycle or tag.
  431. This function allows you to retrieve a list of scenarios based on optional
  432. filtering criteria. If both a *cycle* and a *tag* are provided, the returned
  433. list contains scenarios that belong to the specified *cycle* and also
  434. have the specified *tag*.
  435. Parameters:
  436. cycle (Optional[Cycle^]): The optional `Cycle^` to filter scenarios by.
  437. tag (Optional[str]): The optional tag to filter scenarios by.
  438. is_sorted (bool): If True, sort the output list of scenarios using the sorting key.
  439. The default value is False.
  440. descending (bool): If True, sort the output list of scenarios in descending order.
  441. The default value is False.
  442. sort_key (Literal["name", "id", "creation_date", "tags"]): The optional sort_key to
  443. decide upon what key scenarios are sorted. The sorting is in increasing order for
  444. dates, in alphabetical order for name and id, and in lexicographical order for tags.
  445. The default value is "name".<br/>
  446. If an incorrect sorting key is provided, the scenarios are sorted by name.
  447. Returns:
  448. The list of scenarios filtered by cycle or tag.
  449. """
  450. scenario_manager = _ScenarioManagerFactory._build_manager()
  451. if not cycle and not tag:
  452. scenarios = scenario_manager._get_all()
  453. elif cycle and not tag:
  454. scenarios = scenario_manager._get_all_by_cycle(cycle)
  455. elif not cycle and tag:
  456. scenarios = scenario_manager._get_all_by_tag(tag)
  457. elif cycle and tag:
  458. cycles_scenarios = scenario_manager._get_all_by_cycle(cycle)
  459. scenarios = [scenario for scenario in cycles_scenarios if scenario.has_tag(tag)]
  460. else:
  461. scenarios = []
  462. if is_sorted:
  463. scenario_manager._sort_scenarios(scenarios, descending, sort_key)
  464. return scenarios
  465. def get_primary(cycle: Cycle) -> Optional[Scenario]:
  466. """Retrieve the primary scenario associated with a cycle.
  467. Parameters:
  468. cycle (Cycle^): The cycle for which to retrieve the primary scenario.
  469. Returns:
  470. The primary scenario of the given _cycle_. If the cycle has no
  471. primary scenario, this method returns None.
  472. """
  473. return _ScenarioManagerFactory._build_manager()._get_primary(cycle)
  474. def get_primary_scenarios(
  475. is_sorted: bool = False,
  476. descending: bool = False,
  477. sort_key: Literal["name", "id", "config_id", "creation_date", "tags"] = "name",
  478. ) -> List[Scenario]:
  479. """Retrieve a list of all primary scenarios.
  480. Parameters:
  481. is_sorted (bool): If True, sort the output list of scenarios using the sorting key.
  482. The default value is False.
  483. descending (bool): If True, sort the output list of scenarios in descending order.
  484. The default value is False.
  485. sort_key (Literal["name", "id", "creation_date", "tags"]): The optional sort_key to
  486. decide upon what key scenarios are sorted. The sorting is in increasing order for
  487. dates, in alphabetical order for name and id, and in lexicographical order for tags.
  488. The default value is "name".<br/>
  489. If an incorrect sorting key is provided, the scenarios are sorted by name.
  490. Returns:
  491. A list contains all primary scenarios.
  492. """
  493. scenario_manager = _ScenarioManagerFactory._build_manager()
  494. scenarios = scenario_manager._get_primary_scenarios()
  495. if is_sorted:
  496. scenario_manager._sort_scenarios(scenarios, descending, sort_key)
  497. return scenarios
  498. def is_promotable(scenario: Union[Scenario, ScenarioId]) -> bool:
  499. """Determine if a scenario can be promoted to become a primary scenario.
  500. This function checks whether the given scenario is eligible to be promoted
  501. as a primary scenario.
  502. Parameters:
  503. scenario (Union[Scenario, ScenarioId]): The scenario to be evaluated for promotion.
  504. Returns:
  505. True if the given scenario can be promoted to be a primary scenario. False otherwise.
  506. """
  507. return _ScenarioManagerFactory._build_manager()._is_promotable_to_primary(scenario)
  508. def set_primary(scenario: Scenario):
  509. """Promote a scenario as the primary scenario of its cycle.
  510. This function promotes the given scenario as the primary scenario of its associated cycle.
  511. If the cycle already has a primary scenario, that scenario is demoted and is
  512. no longer considered the primary scenario for its cycle.
  513. Parameters:
  514. scenario (Scenario^): The scenario to promote as the new _primary_ scenario.
  515. """
  516. return _ScenarioManagerFactory._build_manager()._set_primary(scenario)
  517. def tag(scenario: Scenario, tag: str):
  518. """Add a tag to a scenario.
  519. This function adds a user-defined tag to the specified scenario. If another scenario
  520. within the same cycle already has the same tag applied, the previous scenario is untagged.
  521. Parameters:
  522. scenario (Scenario^): The scenario to which the tag will be added.
  523. tag (str): The tag to apply to the scenario.
  524. """
  525. return _ScenarioManagerFactory._build_manager()._tag(scenario, tag)
  526. def untag(scenario: Scenario, tag: str):
  527. """Remove a tag from a scenario.
  528. This function removes a specified tag from the given scenario. If the scenario does
  529. not have the specified tag, it has no effect.
  530. Parameters:
  531. scenario (Scenario^): The scenario from which the tag will be removed.
  532. tag (str): The tag to remove from the scenario.
  533. """
  534. return _ScenarioManagerFactory._build_manager()._untag(scenario, tag)
  535. def compare_scenarios(*scenarios: Scenario, data_node_config_id: Optional[str] = None) -> Dict[str, Any]:
  536. """Compare the data nodes of several scenarios.
  537. You can specify which data node config identifier should the comparison be performed
  538. on.
  539. Parameters:
  540. *scenarios (*Scenario^): The list of the scenarios to compare.
  541. data_node_config_id (Optional[str]): The config identifier of the DataNode to perform
  542. the comparison on. <br/>
  543. If _data_node_config_id_ is not provided, the scenarios are
  544. compared on all defined comparators.<br/>
  545. Returns:
  546. The comparison results. The key is the data node config identifier used for
  547. comparison.
  548. Raises:
  549. InsufficientScenarioToCompare^: Raised when only one or no scenario for comparison
  550. is provided.
  551. NonExistingComparator^: Raised when the scenario comparator does not exist.
  552. DifferentScenarioConfigs^: Raised when the provided scenarios do not share the
  553. same scenario config.
  554. NonExistingScenarioConfig^: Raised when the scenario config of the provided
  555. scenarios could not be found.
  556. """
  557. return _ScenarioManagerFactory._build_manager()._compare(*scenarios, data_node_config_id=data_node_config_id)
  558. def subscribe_scenario(
  559. callback: Callable[[Scenario, Job], None],
  560. params: Optional[List[Any]] = None,
  561. scenario: Optional[Scenario] = None,
  562. ):
  563. """Subscribe a function to be called on job status change.
  564. The subscription is applied to all jobs created for the execution of _scenario_.
  565. If no scenario is provided, the subscription applies to all scenarios.
  566. Parameters:
  567. callback (Callable[[Scenario^, Job^], None]): The function to be called on
  568. status change.
  569. params (Optional[List[Any]]): The parameters to be passed to the _callback_.
  570. scenario (Optional[Scenario^]): The scenario to which the callback is applied.
  571. If None, the subscription is registered for all scenarios.
  572. Note:
  573. Notifications are applied only for jobs created **after** this subscription.
  574. """
  575. params = [] if params is None else params
  576. return _ScenarioManagerFactory._build_manager()._subscribe(callback, params, scenario)
  577. def unsubscribe_scenario(
  578. callback: Callable[[Scenario, Job], None], params: Optional[List[Any]] = None, scenario: Optional[Scenario] = None
  579. ):
  580. """Unsubscribe a function that is called when the status of a `Job^` changes.
  581. If no scenario is provided, the subscription is removed for all scenarios.
  582. Parameters:
  583. callback (Callable[[Scenario^, Job^], None]): The function to unsubscribe from.
  584. params (Optional[List[Any]]): The parameters to be passed to the callback.
  585. scenario (Optional[Scenario]): The scenario to unsubscribe from. If None, it
  586. applies to all scenarios.
  587. Note:
  588. The callback function will continue to be called for ongoing jobs.
  589. """
  590. return _ScenarioManagerFactory._build_manager()._unsubscribe(callback, params, scenario)
  591. def subscribe_sequence(
  592. callback: Callable[[Sequence, Job], None], params: Optional[List[Any]] = None, sequence: Optional[Sequence] = None
  593. ):
  594. """Subscribe a function to be called on job status change.
  595. The subscription is applied to all jobs created for the execution of _sequence_.
  596. Parameters:
  597. callback (Callable[[Sequence^, Job^], None]): The callable function to be called on
  598. status change.
  599. params (Optional[List[Any]]): The parameters to be passed to the _callback_.
  600. sequence (Optional[Sequence^]): The sequence to subscribe on. If None, the subscription
  601. is applied to all sequences.
  602. Note:
  603. Notifications are applied only for jobs created **after** this subscription.
  604. """
  605. return _SequenceManagerFactory._build_manager()._subscribe(callback, params, sequence)
  606. def unsubscribe_sequence(
  607. callback: Callable[[Sequence, Job], None], params: Optional[List[Any]] = None, sequence: Optional[Sequence] = None
  608. ):
  609. """Unsubscribe a function that is called when the status of a Job changes.
  610. Parameters:
  611. callback (Callable[[Sequence^, Job^], None]): The callable function to be called on
  612. status change.
  613. params (Optional[List[Any]]): The parameters to be passed to the _callback_.
  614. sequence (Optional[Sequence^]): The sequence to unsubscribe to. If None, it applies
  615. to all sequences.
  616. Note:
  617. The function will continue to be called for ongoing jobs.
  618. """
  619. return _SequenceManagerFactory._build_manager()._unsubscribe(callback, params, sequence)
  620. def get_sequences() -> List[Sequence]:
  621. """Return all existing sequences.
  622. Returns:
  623. The list of all sequences.
  624. """
  625. return _SequenceManagerFactory._build_manager()._get_all()
  626. def get_jobs() -> List[Job]:
  627. """Return all the existing jobs.
  628. Returns:
  629. The list of all jobs.
  630. """
  631. return _JobManagerFactory._build_manager()._get_all()
  632. def get_submissions() -> List[Submission]:
  633. """Return all the existing submissions.
  634. Returns:
  635. The list of all submissions.
  636. """
  637. return _SubmissionManagerFactory._build_manager()._get_all()
  638. def delete_job(job: Job, force: Optional[bool] = False):
  639. """Delete a job.
  640. This function deletes the specified job. If the job is not completed and
  641. *force* is not set to True, a `JobNotDeletedException^` may be raised.
  642. Parameters:
  643. job (Job^): The job to delete.
  644. force (Optional[bool]): If True, forces the deletion of _job_, even
  645. if it is not completed yet.
  646. Raises:
  647. JobNotDeletedException^: If the job is not finished.
  648. """
  649. return _JobManagerFactory._build_manager()._delete(job, force)
  650. def delete_jobs():
  651. """Delete all jobs."""
  652. return _JobManagerFactory._build_manager()._delete_all()
  653. def cancel_job(job: Union[str, Job]):
  654. """Cancel a job and set the status of the subsequent jobs to ABANDONED.
  655. This function cancels the specified job and sets the status of any subsequent jobs to ABANDONED.
  656. Parameters:
  657. job (Job^): The job to cancel.
  658. """
  659. _JobManagerFactory._build_manager()._cancel(job)
  660. def get_latest_job(task: Task) -> Optional[Job]:
  661. """Return the latest job of a task.
  662. This function retrieves the latest job associated with a task.
  663. Parameters:
  664. task (Task^): The task to retrieve the latest job from.
  665. Returns:
  666. The latest job created from _task_, or None if no job has been created from _task_.
  667. """
  668. return _JobManagerFactory._build_manager()._get_latest(task)
  669. def get_latest_submission(entity: Union[Scenario, Sequence, Task]) -> Optional[Submission]:
  670. """Return the latest submission of a scenario, sequence or task.
  671. This function retrieves the latest submission associated with a scenario, sequence or task.
  672. Parameters:
  673. entity (Union[Scenario^, Sequence^, Task^]): The scenario, sequence or task to
  674. retrieve the latest submission from.
  675. Returns:
  676. The latest submission created from _scenario_, _sequence_ and _task_, or None
  677. if no submission has been created from _scenario_, _sequence_ and _task_.
  678. """
  679. return _SubmissionManagerFactory._build_manager()._get_latest(entity)
  680. def get_data_nodes() -> List[DataNode]:
  681. """Return all the existing data nodes.
  682. Returns:
  683. The list of all data nodes.
  684. """
  685. return _DataManagerFactory._build_manager()._get_all()
  686. def get_cycles() -> List[Cycle]:
  687. """Return the list of all existing cycles.
  688. Returns:
  689. The list of all cycles.
  690. """
  691. return _CycleManagerFactory._build_manager()._get_all()
  692. def create_scenario(
  693. config: ScenarioConfig,
  694. creation_date: Optional[datetime] = None,
  695. name: Optional[str] = None,
  696. ) -> Scenario:
  697. """Create and return a new scenario based on a scenario configuration.
  698. This function checks and locks the configuration, manages application's version,
  699. and creates a new scenario from the scenario configuration provided.
  700. If the scenario belongs to a cycle, the cycle (corresponding to the _creation_date_
  701. and the configuration frequency attribute) is created if it does not exist yet.
  702. Parameters:
  703. config (ScenarioConfig^): The scenario configuration used to create a new scenario.
  704. creation_date (Optional[datetime.datetime]): The creation date of the scenario.
  705. If None, the current date time is used.
  706. name (Optional[str]): The displayable name of the scenario.
  707. Returns:
  708. The new scenario.
  709. Raises:
  710. SystemExit: If the configuration check returns some errors.
  711. """
  712. Core._manage_version_and_block_config()
  713. return _ScenarioManagerFactory._build_manager()._create(config, creation_date, name)
  714. def create_global_data_node(config: DataNodeConfig) -> DataNode:
  715. """Create and return a new GLOBAL data node from a data node configuration.
  716. This function checks and locks the configuration, manages application's version,
  717. and creates the new data node from the data node configuration provided.
  718. Parameters:
  719. config (DataNodeConfig^): The data node configuration. It must have a `GLOBAL` scope.
  720. Returns:
  721. The new global data node.
  722. Raises:
  723. DataNodeConfigIsNotGlobal^: If the data node configuration does not have GLOBAL scope.
  724. SystemExit: If the configuration check returns some errors.
  725. """
  726. # Check if the data node config has GLOBAL scope
  727. if config.scope is not Scope.GLOBAL:
  728. raise DataNodeConfigIsNotGlobal(config.id)
  729. Core._manage_version_and_block_config()
  730. if dns := _DataManagerFactory._build_manager()._get_by_config_id(config.id):
  731. return dns[0]
  732. return _DataManagerFactory._build_manager()._create_and_set(config, None, None)
  733. def clean_all_entities_by_version(version_number=None) -> bool:
  734. """Deprecated. Use `clean_all_entities` function instead."""
  735. _warn_deprecated("'clean_all_entities_by_version'", suggest="the 'clean_all_entities' function")
  736. return clean_all_entities(version_number)
  737. def clean_all_entities(version_number: str) -> bool:
  738. """Deletes all entities associated with the specified version.
  739. Parameters:
  740. version_number (str): The version number of the entities to be deleted.
  741. The version_number should not be a production version.
  742. Returns:
  743. True if the operation succeeded, False otherwise.
  744. Notes:
  745. - If the specified version does not exist, the operation will be aborted, and False will be returned.
  746. - If the specified version is a production version, the operation will be aborted, and False will be returned.
  747. - This function cleans all entities, including jobs, submissions, scenarios, cycles, sequences, tasks,
  748. and data nodes.
  749. """
  750. version_manager = _VersionManagerFactory._build_manager()
  751. try:
  752. version_number = version_manager._replace_version_number(version_number)
  753. except NonExistingVersion as e:
  754. __logger.warning(f"{e.message} Abort cleaning the entities of version '{version_number}'.")
  755. return False
  756. if version_number in version_manager._get_production_versions():
  757. __logger.warning(
  758. f"Abort cleaning the entities of version '{version_number}'. A production version can not be deleted."
  759. )
  760. return False
  761. _JobManagerFactory._build_manager()._delete_by_version(version_number)
  762. _SubmissionManagerFactory._build_manager()._delete_by_version(version_number)
  763. _ScenarioManagerFactory._build_manager()._delete_by_version(version_number)
  764. _SequenceManagerFactory._build_manager()._delete_by_version(version_number)
  765. _TaskManagerFactory._build_manager()._delete_by_version(version_number)
  766. _DataManagerFactory._build_manager()._delete_by_version(version_number)
  767. version_manager._delete(version_number)
  768. try:
  769. version_manager._delete_production_version(version_number)
  770. except VersionIsNotProductionVersion:
  771. pass
  772. return True
  773. def export_scenario(
  774. scenario_id: ScenarioId,
  775. output_path: Union[str, pathlib.Path],
  776. override: bool = False,
  777. include_data: bool = False,
  778. ):
  779. """Export all related entities of a scenario to an archive zip file.
  780. This function exports all related entities of the specified scenario to the
  781. specified archive zip file.
  782. Parameters:
  783. scenario_id (ScenarioId): The ID of the scenario to export.
  784. output_path (Union[str, pathlib.Path]): The path to export the scenario to.
  785. The path should include the file name without the extension or with the `.zip` extension.
  786. If the path exists and the override parameter is False, an exception is raised.
  787. override (bool): If True, the existing folder will be overridden. The default value is False.
  788. include_data (bool): If True, the file-based data nodes are exported as well.
  789. This includes Pickle, CSV, Excel, Parquet, and JSON data nodes.
  790. If the scenario has a data node that is not file-based, a warning will be logged, and the data node
  791. will not be exported. The default value is False.
  792. Raises:
  793. ExportPathAlreadyExists^: If the `output_path` already exists and the override parameter is False.
  794. """
  795. manager = _ScenarioManagerFactory._build_manager()
  796. scenario = manager._get(scenario_id)
  797. entity_ids = manager._get_children_entity_ids(scenario)
  798. entity_ids.scenario_ids = {scenario_id}
  799. if scenario.cycle:
  800. entity_ids.cycle_ids = {scenario.cycle.id}
  801. output_filename = os.path.splitext(output_path)[0] if str(output_path).endswith(".zip") else str(output_path)
  802. output_zip_path = pathlib.Path(output_filename + ".zip")
  803. if output_zip_path.exists():
  804. if override:
  805. __logger.warning(f"Override the existing path '{output_zip_path}' to export scenario {scenario_id}.")
  806. output_zip_path.unlink()
  807. else:
  808. raise ExportPathAlreadyExists(str(output_zip_path), scenario_id)
  809. with tempfile.TemporaryDirectory() as tmp_dir:
  810. for data_node_id in entity_ids.data_node_ids:
  811. _DataManagerFactory._build_manager()._export(data_node_id, tmp_dir, include_data=include_data)
  812. for task_id in entity_ids.task_ids:
  813. _TaskManagerFactory._build_manager()._export(task_id, tmp_dir)
  814. for sequence_id in entity_ids.sequence_ids:
  815. _SequenceManagerFactory._build_manager()._export(sequence_id, tmp_dir)
  816. for cycle_id in entity_ids.cycle_ids:
  817. _CycleManagerFactory._build_manager()._export(cycle_id, tmp_dir)
  818. for scenario_id in entity_ids.scenario_ids:
  819. _ScenarioManagerFactory._build_manager()._export(scenario_id, tmp_dir)
  820. for job_id in entity_ids.job_ids:
  821. _JobManagerFactory._build_manager()._export(job_id, tmp_dir)
  822. for submission_id in entity_ids.submission_ids:
  823. _SubmissionManagerFactory._build_manager()._export(submission_id, tmp_dir)
  824. _VersionManagerFactory._build_manager()._export(scenario.version, tmp_dir)
  825. shutil.make_archive(output_filename, "zip", tmp_dir)
  826. def import_scenario(input_path: Union[str, pathlib.Path], override: bool = False) -> Optional[Scenario]:
  827. """Import from an archive zip file containing an exported scenario into the current Taipy application.
  828. The zip file should be created by the `taipy.import()^` method, which contains all related entities
  829. of the scenario.
  830. All entities should belong to the same version that is compatible with the current Taipy application version.
  831. Parameters:
  832. input_path (Union[str, pathlib.Path]): The path to the archive scenario to import.
  833. If the path doesn't exist, an exception is raised.
  834. override (bool): If True, override the entities if existed. The default value is False.
  835. Return:
  836. The imported scenario.
  837. Raises:
  838. FileNotFoundError: If the import path does not exist.
  839. ImportArchiveDoesntContainAnyScenario: If the unzip folder doesn't contain any scenario.
  840. ConflictedConfigurationError: If the configuration of the imported scenario is conflicted with the current one.
  841. """
  842. if isinstance(input_path, str):
  843. zip_file_path: pathlib.Path = pathlib.Path(input_path)
  844. else:
  845. zip_file_path = input_path
  846. if not zip_file_path.exists():
  847. raise FileNotFoundError(f"The import archive path '{zip_file_path}' does not exist.")
  848. entity_managers: Dict[str, Type[_Manager]] = {
  849. "cycles": _CycleManagerFactory._build_manager(),
  850. "cycle": _CycleManagerFactory._build_manager(),
  851. "data_nodes": _DataManagerFactory._build_manager(),
  852. "data_node": _DataManagerFactory._build_manager(),
  853. "tasks": _TaskManagerFactory._build_manager(),
  854. "task": _TaskManagerFactory._build_manager(),
  855. "scenarios": _ScenarioManagerFactory._build_manager(),
  856. "scenario": _ScenarioManagerFactory._build_manager(),
  857. "jobs": _JobManagerFactory._build_manager(),
  858. "job": _JobManagerFactory._build_manager(),
  859. "submission": _SubmissionManagerFactory._build_manager(),
  860. "version": _VersionManagerFactory._build_manager(),
  861. }
  862. return _ScenarioManagerFactory._build_manager()._import_scenario_and_children_entities(
  863. zip_file_path, override, entity_managers
  864. )
  865. def get_parents(
  866. entity: Union[TaskId, DataNodeId, SequenceId, Task, DataNode, Sequence], parent_dict=None
  867. ) -> Dict[str, Set[_Entity]]:
  868. """Get the parents of an entity from itself or its identifier.
  869. Parameters:
  870. entity (Union[TaskId, DataNodeId, SequenceId, Task, DataNode, Sequence]): The entity or its
  871. identifier to get the parents.
  872. Returns:
  873. The dictionary of all parent entities.
  874. They are grouped by their type (Scenario^, Sequences^, or tasks^) so each key corresponds
  875. to a level of the parents and the value is a set of the parent entities.
  876. An empty dictionary is returned if the entity does not have parents.<br/>
  877. Example: The following instruction returns all the scenarios that include the
  878. datanode identified by "my_datanode_id".
  879. `taipy.get_parents("id_of_my_datanode")["scenario"]`
  880. Raises:
  881. ModelNotFound^: If _entity_ does not match a correct entity pattern.
  882. """
  883. def update_parent_dict(parents_set, parent_dict):
  884. for k, value in parents_set.items():
  885. if k in parent_dict.keys():
  886. parent_dict[k].update(value)
  887. else:
  888. parent_dict[k] = value
  889. if isinstance(entity, str):
  890. entity = get(entity)
  891. parent_dict = parent_dict or {}
  892. if isinstance(entity, (Scenario, Cycle)):
  893. return parent_dict
  894. current_parent_dict: Dict[str, Set] = {}
  895. for parent in entity.parent_ids:
  896. parent_entity = get(parent)
  897. if parent_entity._MANAGER_NAME in current_parent_dict.keys():
  898. current_parent_dict[parent_entity._MANAGER_NAME].add(parent_entity)
  899. else:
  900. current_parent_dict[parent_entity._MANAGER_NAME] = {parent_entity}
  901. if isinstance(entity, Sequence):
  902. update_parent_dict(current_parent_dict, parent_dict)
  903. if isinstance(entity, Task):
  904. parent_entity_key_to_search_next = "scenario"
  905. update_parent_dict(current_parent_dict, parent_dict)
  906. for parent in parent_dict.get(parent_entity_key_to_search_next, []):
  907. get_parents(parent, parent_dict)
  908. if isinstance(entity, DataNode):
  909. parent_entity_key_to_search_next = "task"
  910. update_parent_dict(current_parent_dict, parent_dict)
  911. for parent in parent_dict.get(parent_entity_key_to_search_next, []):
  912. get_parents(parent, parent_dict)
  913. return parent_dict
  914. def get_cycles_scenarios() -> Dict[Optional[Cycle], List[Scenario]]:
  915. """Get the scenarios grouped by cycles.
  916. Returns:
  917. The dictionary of all cycles and their corresponding scenarios.
  918. """
  919. cycles_scenarios: Dict[Optional[Cycle], List[Scenario]] = {}
  920. for scenario in get_scenarios():
  921. if scenario.cycle in cycles_scenarios.keys():
  922. cycles_scenarios[scenario.cycle].append(scenario)
  923. else:
  924. cycles_scenarios[scenario.cycle] = [scenario]
  925. return cycles_scenarios
  926. def get_entities_by_config_id(
  927. config_id: str,
  928. ) -> Union[List, List[Task], List[DataNode], List[Sequence], List[Scenario]]:
  929. """Get the entities by its config id.
  930. Parameters:
  931. config_id (str): The config id of the entities
  932. Returns:
  933. The list of all entities by the config id.
  934. """
  935. entities: List = []
  936. if entities := _ScenarioManagerFactory._build_manager()._get_by_config_id(config_id):
  937. return entities
  938. if entities := _TaskManagerFactory._build_manager()._get_by_config_id(config_id):
  939. return entities
  940. if entities := _DataManagerFactory._build_manager()._get_by_config_id(config_id):
  941. return entities
  942. return entities