taipy.py 39 KB

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