vtlengine 1.0.4__tar.gz → 1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of vtlengine might be problematic. Click here for more details.

Files changed (64) hide show
  1. {vtlengine-1.0.4 → vtlengine-1.1}/PKG-INFO +20 -17
  2. {vtlengine-1.0.4 → vtlengine-1.1}/pyproject.toml +41 -24
  3. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/API/_InternalApi.py +236 -44
  4. vtlengine-1.1/src/vtlengine/API/__init__.py +507 -0
  5. vtlengine-1.1/src/vtlengine/AST/ASTComment.py +56 -0
  6. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/ASTConstructor.py +71 -18
  7. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/ASTConstructorModules/Expr.py +191 -72
  8. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/ASTConstructorModules/ExprComponents.py +81 -38
  9. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/ASTConstructorModules/Terminals.py +76 -31
  10. vtlengine-1.1/src/vtlengine/AST/ASTConstructorModules/__init__.py +50 -0
  11. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/ASTEncoders.py +4 -0
  12. vtlengine-1.1/src/vtlengine/AST/ASTString.py +608 -0
  13. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/ASTTemplate.py +28 -2
  14. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/DAG/__init__.py +10 -1
  15. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/__init__.py +127 -14
  16. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Exceptions/messages.py +9 -0
  17. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Interpreter/__init__.py +53 -8
  18. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Model/__init__.py +9 -4
  19. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Aggregation.py +7 -5
  20. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Analytic.py +16 -11
  21. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Conditional.py +18 -3
  22. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Time.py +9 -8
  23. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Utils/__init__.py +49 -0
  24. vtlengine-1.1/src/vtlengine/__extras_check.py +17 -0
  25. vtlengine-1.1/src/vtlengine/__init__.py +3 -0
  26. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/files/output/__init__.py +2 -0
  27. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/files/parser/__init__.py +19 -47
  28. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/files/parser/_rfc_dialect.py +1 -1
  29. vtlengine-1.0.4/src/vtlengine/API/__init__.py +0 -318
  30. vtlengine-1.0.4/src/vtlengine/__init__.py +0 -3
  31. vtlengine-1.0.4/src/vtlengine/files/__init__.py +0 -0
  32. {vtlengine-1.0.4 → vtlengine-1.1}/LICENSE.md +0 -0
  33. {vtlengine-1.0.4 → vtlengine-1.1}/README.md +0 -0
  34. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/API/data/schema/json_schema_2.1.json +0 -0
  35. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/ASTDataExchange.py +0 -0
  36. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/ASTVisitor.py +0 -0
  37. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/DAG/_words.py +0 -0
  38. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/Grammar/Vtl.g4 +0 -0
  39. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/Grammar/VtlTokens.g4 +0 -0
  40. {vtlengine-1.0.4/src/vtlengine/AST/ASTConstructorModules → vtlengine-1.1/src/vtlengine/AST/Grammar}/__init__.py +0 -0
  41. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/Grammar/lexer.py +0 -0
  42. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/Grammar/parser.py +0 -0
  43. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/Grammar/tokens.py +0 -0
  44. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/AST/VtlVisitor.py +0 -0
  45. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/DataTypes/TimeHandling.py +0 -0
  46. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/DataTypes/__init__.py +0 -0
  47. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Exceptions/__init__.py +0 -0
  48. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Assignment.py +0 -0
  49. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Boolean.py +0 -0
  50. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/CastOperator.py +0 -0
  51. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Clause.py +0 -0
  52. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Comparison.py +0 -0
  53. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/General.py +0 -0
  54. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/HROperators.py +0 -0
  55. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Join.py +0 -0
  56. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Numeric.py +0 -0
  57. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/RoleSetter.py +0 -0
  58. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Set.py +0 -0
  59. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/String.py +0 -0
  60. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/Validation.py +0 -0
  61. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/Operators/__init__.py +0 -0
  62. {vtlengine-1.0.4/src/vtlengine/AST/Grammar → vtlengine-1.1/src/vtlengine/files}/__init__.py +0 -0
  63. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/files/output/_time_period_representation.py +0 -0
  64. {vtlengine-1.0.4 → vtlengine-1.1}/src/vtlengine/files/parser/_time_checking.py +0 -0
@@ -1,32 +1,35 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: vtlengine
3
- Version: 1.0.4
3
+ Version: 1.1
4
4
  Summary: Run and Validate VTL Scripts
5
5
  License: AGPL-3.0
6
6
  Keywords: vtl,sdmx,vtlengine,Validation and Transformation Language
7
7
  Author: MeaningfulData
8
8
  Author-email: info@meaningfuldata.eu
9
- Requires-Python: >=3.9,<4.0
9
+ Maintainer: Francisco Javier Hernandez del Caño
10
+ Maintainer-email: javier.hernandez@meaningfuldata.eu
11
+ Requires-Python: >=3.9
10
12
  Classifier: Development Status :: 5 - Production/Stable
11
13
  Classifier: Intended Audience :: Developers
12
14
  Classifier: Intended Audience :: Information Technology
13
15
  Classifier: Intended Audience :: Science/Research
14
- Classifier: License :: OSI Approved :: GNU Affero General Public License v3
15
- Classifier: Programming Language :: Python :: 3
16
- Classifier: Programming Language :: Python :: 3.9
17
- Classifier: Programming Language :: Python :: 3.10
18
- Classifier: Programming Language :: Python :: 3.11
19
- Classifier: Programming Language :: Python :: 3.12
20
- Classifier: Programming Language :: Python :: 3.13
21
16
  Classifier: Typing :: Typed
22
- Requires-Dist: antlr4-python3-runtime (==4.9.2)
23
- Requires-Dist: duckdb (>=1.1,<2.0)
24
- Requires-Dist: jsonschema (>=4.23.0,<5.0.0)
25
- Requires-Dist: networkx (>=2.8.8,<3.0.0)
26
- Requires-Dist: numexpr (>=2.9.0,<3.0.0)
27
- Requires-Dist: pandas (>=2.1.4,<3.0.0)
28
- Requires-Dist: s3fs (>=2025.2.0,<2026.0.0)
29
- Requires-Dist: sqlglot (>=22.2.0,<23.0.0)
17
+ Provides-Extra: all
18
+ Provides-Extra: s3
19
+ Requires-Dist: antlr4-python3-runtime (>=4.9.2,<4.10)
20
+ Requires-Dist: duckdb (>=1.1,<1.2)
21
+ Requires-Dist: fsspec (>=2022.11.0,<2023.0) ; extra == "all"
22
+ Requires-Dist: fsspec (>=2022.11.0,<2023.0) ; extra == "s3"
23
+ Requires-Dist: jsonschema (>=3.2.0,<5.0)
24
+ Requires-Dist: networkx (>=2.8,<3.0)
25
+ Requires-Dist: numpy (>=1.23.2,<2) ; python_version < "3.13"
26
+ Requires-Dist: numpy (>=2.1.0) ; python_version >= "3.13"
27
+ Requires-Dist: pandas (>=2.1.4,<2.2) ; python_version < "3.13"
28
+ Requires-Dist: pandas (>=2.2,<3.0) ; python_version >= "3.13"
29
+ Requires-Dist: pysdmx[xml] (>=1.3.0,<2.0)
30
+ Requires-Dist: s3fs (>=2022.11.0,<2023.0) ; extra == "all"
31
+ Requires-Dist: s3fs (>=2022.11.0,<2023.0) ; extra == "s3"
32
+ Requires-Dist: sqlglot (>=22.2.0,<23.0)
30
33
  Project-URL: Authors, https://github.com/Meaningful-Data/vtlengine/graphs/contributors
31
34
  Project-URL: Documentation, https://docs.vtlengine.meaningfuldata.eu
32
35
  Project-URL: IssueTracker, https://github.com/Meaningful-Data/vtlengine/issues
@@ -1,11 +1,18 @@
1
- [tool.poetry]
1
+ [project]
2
2
  name = "vtlengine"
3
- version = "1.0.4"
3
+ version = "1.1"
4
4
  description = "Run and Validate VTL Scripts"
5
- authors = ["MeaningfulData <info@meaningfuldata.eu>"]
6
5
  license = "AGPL-3.0"
7
6
  readme = "README.md"
8
-
7
+ requires-python = ">=3.9"
8
+ authors = [
9
+ {name = "MeaningfulData", email = "info@meaningfuldata.eu"},
10
+ ]
11
+ maintainers = [
12
+ {name = "Francisco Javier Hernandez del Caño", email = "javier.hernandez@meaningfuldata.eu"},
13
+ {name = "Alberto Hernandez del Caño", email = "alberto.hernandez@meaningfuldata.eu"},
14
+ {name = "Mateo de Lorenzo Argeles", email = "mateo.delorenzo@meaningfuldata.eu"}
15
+ ]
9
16
  classifiers = [
10
17
  "Development Status :: 5 - Production/Stable",
11
18
  "Intended Audience :: Developers",
@@ -13,10 +20,28 @@ classifiers = [
13
20
  "Intended Audience :: Science/Research",
14
21
  "Typing :: Typed"
15
22
  ]
16
-
17
23
  keywords = ['vtl', 'sdmx', 'vtlengine', 'Validation and Transformation Language']
18
24
 
19
- [tool.poetry.urls]
25
+ dependencies = [
26
+ # PyPi dependencies
27
+ "duckdb>=1.1,<1.2",
28
+ "pysdmx[xml]>=1.3.0,<2.0",
29
+ # APT-supported dependencies
30
+ "jsonschema>=3.2.0,<5.0",
31
+ "sqlglot>=22.2.0,<23.0",
32
+ "antlr4-python3-runtime>=4.9.2,<4.10",
33
+ "pandas>=2.1.4,<2.2 ; python_version < '3.13'",
34
+ "pandas>=2.2,<3.0 ; python_version >= '3.13'",
35
+ "networkx>=2.8,<3.0",
36
+ "numpy>=1.23.2,<2 ; python_version < '3.13'",
37
+ "numpy>=2.1.0; python_version >= '3.13'",
38
+ ]
39
+
40
+ [project.optional-dependencies]
41
+ s3 = ["s3fs>=2022.11.0,<2023.0", "fsspec>=2022.11.0,<2023.0"]
42
+ all = ["s3fs>=2022.11.0,<2023.0", "fsspec>=2022.11.0,<2023.0"]
43
+
44
+ [project.urls]
20
45
  Repository = 'https://github.com/Meaningful-Data/vtlengine'
21
46
  Documentation = 'https://docs.vtlengine.meaningfuldata.eu'
22
47
  MeaningfulData = 'https://www.meaningfuldata.eu/'
@@ -24,31 +49,23 @@ IssueTracker = 'https://github.com/Meaningful-Data/vtlengine/issues'
24
49
  Authors = 'https://github.com/Meaningful-Data/vtlengine/graphs/contributors'
25
50
 
26
51
  [tool.poetry.dependencies]
27
- python = "^3.9"
28
- # PyPi dependencies
29
- duckdb = "^1.1"
30
- #numba = "^0.60.0"
31
- s3fs = "^2025.2.0"
32
- jsonschema = "^4.23.0"
33
-
34
- # APT dependencies
35
- antlr4-python3-runtime = "4.9.2"
36
- networkx = "^2.8.8"
37
- numexpr = "^2.9.0"
38
- pandas = "^2.1.4"
39
- sqlglot = "^22.2.0"
52
+ python = ">=3.9,<4.0"
40
53
 
41
54
  [tool.poetry.group.dev.dependencies]
42
55
  pytest = "^8.3"
43
- pytest-cov = "^6.0.0"
56
+ pytest-cov = "^6.1.1"
44
57
  line-profiler-pycharm = "^1.2.0"
58
+ mypy = "1.15.0"
59
+ pandas-stubs = "^2.1.4.231227"
60
+ ruff = "^0.11.11"
61
+ types-jsonschema = "4.23.0.20250516"
62
+
63
+ [tool.poetry.group.docs.dependencies]
45
64
  sphinx = "^7.4.7"
46
65
  sphinx-rtd-theme = "^3.0.2"
47
- mypy = "1.14.1"
48
- pandas-stubs = "^2.1.4.231227"
49
66
  toml = "^0.10.2"
50
- ruff = "^0.9.4"
51
- types-jsonschema = "4.23.0.20241208"
67
+
68
+
52
69
 
53
70
  [tool.ruff]
54
71
  line-length = 100
@@ -1,18 +1,33 @@
1
1
  import json
2
2
  import os
3
3
  from pathlib import Path
4
- from typing import Any, Dict, List, Optional, Union
4
+ from typing import Any, Dict, List, Literal, Optional, Union
5
5
 
6
6
  import jsonschema
7
7
  import pandas as pd
8
- from s3fs import S3FileSystem # type: ignore[import-untyped]
8
+ from pysdmx.model.dataflow import Component as SDMXComponent
9
+ from pysdmx.model.dataflow import DataStructureDefinition, Schema
10
+ from pysdmx.model.dataflow import Role as SDMX_Role
11
+ from pysdmx.model.vtl import (
12
+ Ruleset,
13
+ RulesetScheme,
14
+ Transformation,
15
+ TransformationScheme,
16
+ UserDefinedOperator,
17
+ UserDefinedOperatorScheme,
18
+ )
9
19
 
10
- from vtlengine.AST import PersistentAssignment, Start
20
+ from vtlengine import AST as AST
21
+ from vtlengine.__extras_check import __check_s3_extra
22
+ from vtlengine.AST import Assignment, DPRuleset, HRuleset, Operator, PersistentAssignment, Start
23
+ from vtlengine.AST.ASTString import ASTString
11
24
  from vtlengine.DataTypes import SCALAR_TYPES
12
25
  from vtlengine.Exceptions import InputValidationException, check_key
13
26
  from vtlengine.files.parser import _fill_dataset_empty_data, _validate_pandas
14
27
  from vtlengine.Model import (
15
- Component,
28
+ Component as VTL_Component,
29
+ )
30
+ from vtlengine.Model import (
16
31
  Dataset,
17
32
  ExternalRoutine,
18
33
  Role,
@@ -20,9 +35,11 @@ from vtlengine.Model import (
20
35
  Scalar,
21
36
  ValueDomain,
22
37
  )
38
+ from vtlengine.Utils import VTL_DTYPES_MAPPING, VTL_ROLE_MAPPING
23
39
 
24
40
  base_path = Path(__file__).parent
25
41
  schema_path = base_path / "data" / "schema"
42
+ sdmx_csv_path = base_path / "data" / "sdmx_csv"
26
43
  with open(schema_path / "json_schema_2.1.json", "r") as file:
27
44
  schema = json.load(file)
28
45
 
@@ -66,7 +83,7 @@ def _load_dataset_from_structure(structures: Dict[str, Any]) -> Dict[str, Any]:
66
83
  else:
67
84
  component["nullable"] = False
68
85
 
69
- components[component["name"]] = Component(
86
+ components[component["name"]] = VTL_Component(
70
87
  name=component["name"],
71
88
  data_type=SCALAR_TYPES[component["data_type"]],
72
89
  role=Role(component["role"]),
@@ -77,7 +94,7 @@ def _load_dataset_from_structure(structures: Dict[str, Any]) -> Dict[str, Any]:
77
94
  for component in dataset_json["DataStructure"]:
78
95
  check_key("data_type", SCALAR_TYPES.keys(), component["type"])
79
96
  check_key("role", Role_keys, component["role"])
80
- components[component["name"]] = Component(
97
+ components[component["name"]] = VTL_Component(
81
98
  name=component["name"],
82
99
  data_type=SCALAR_TYPES[component["type"]],
83
100
  role=Role(component["role"]),
@@ -105,38 +122,16 @@ def _load_single_datapoint(datapoint: Union[str, Path]) -> Dict[str, Any]:
105
122
  raise Exception("Invalid datapoint. Input must be a Path or an S3 URI")
106
123
  if isinstance(datapoint, str):
107
124
  if "s3://" in datapoint:
108
- # Handling S3 URI
109
- s3fs_obj = S3FileSystem()
110
-
111
- # Check if the S3 URI is valid
112
- if not s3fs_obj.exists(datapoint):
113
- raise Exception(
114
- f"Invalid datapoint. S3 URI does not exist or it is not accessible: {datapoint}"
115
- )
116
-
117
- # Check if the S3 URI is a directory
118
- if s3fs_obj.isdir(datapoint):
119
- datapoints: Dict[str, Any] = {}
120
- for f in s3fs_obj.ls(datapoint):
121
- if f.endswith(".csv"):
122
- dataset_name = f.split("/")[-1].removesuffix(".csv")
123
- dict_data = {dataset_name: f"s3://{f}"}
124
- datapoints = {**datapoints, **dict_data}
125
- return datapoints
126
-
127
- # Check if the S3 URI is a csv file
128
- if s3fs_obj.isfile(datapoint) and not datapoint.endswith(".csv"):
129
- raise Exception(f"Invalid datapoint. S3 URI must refer to a csv file: {datapoint}")
125
+ __check_s3_extra()
130
126
  dataset_name = datapoint.split("/")[-1].removesuffix(".csv")
131
127
  dict_data = {dataset_name: datapoint}
132
128
  return dict_data
133
-
134
129
  try:
135
130
  datapoint = Path(datapoint)
136
131
  except Exception:
137
132
  raise Exception("Invalid datapoint. Input must refer to a Path or an S3 URI")
138
133
  if datapoint.is_dir():
139
- datapoints = {}
134
+ datapoints: Dict[str, Any] = {}
140
135
  for f in datapoint.iterdir():
141
136
  if f.suffix != ".csv":
142
137
  continue
@@ -191,7 +186,7 @@ def _load_datastructure_single(data_structure: Union[Dict[str, Any], Path]) -> D
191
186
 
192
187
 
193
188
  def load_datasets(
194
- data_structure: Union[Dict[str, Any], Path, List[Union[Dict[str, Any], Path]]],
189
+ data_structure: Union[Dict[str, Any], Path, List[Dict[str, Any]], List[Path]],
195
190
  ) -> Dict[str, Dataset]:
196
191
  """
197
192
  Loads multiple datasets.
@@ -400,25 +395,222 @@ def _check_output_folder(output_folder: Union[str, Path]) -> None:
400
395
  """
401
396
  if isinstance(output_folder, str):
402
397
  if "s3://" in output_folder:
403
- s3fs_obj = S3FileSystem()
404
- # Check if the S3 URI is valid
405
- if not s3fs_obj.exists(output_folder):
406
- try:
407
- s3fs_obj.mkdir(output_folder)
408
- except Exception:
409
- raise Exception(
410
- f"Invalid output folder. S3 URI is invalid or "
411
- f"it is not accessible: {output_folder}"
412
- )
398
+ __check_s3_extra()
399
+ if not output_folder.endswith("/"):
400
+ raise ValueError("Output folder must be a Path or S3 URI to a directory")
413
401
  return
414
402
  try:
415
403
  output_folder = Path(output_folder)
416
404
  except Exception:
417
- raise Exception("Output folder must be a Path or S3 URI to a directory")
405
+ raise ValueError("Output folder must be a Path or S3 URI to a directory")
418
406
 
419
407
  if not isinstance(output_folder, Path):
420
- raise Exception("Output folder must be a Path or S3 URI to a directory")
408
+ raise ValueError("Output folder must be a Path or S3 URI to a directory")
421
409
  if not output_folder.exists():
422
410
  if output_folder.suffix != "":
423
- raise Exception("Output folder must be a Path or S3 URI to a directory")
411
+ raise ValueError("Output folder must be a Path or S3 URI to a directory")
424
412
  os.mkdir(output_folder)
413
+
414
+
415
+ def to_vtl_json(dsd: Union[DataStructureDefinition, Schema], dataset_name: str) -> Dict[str, Any]:
416
+ """
417
+ Converts a pysdmx `DataStructureDefinition` or `Schema` into a VTL-compatible JSON
418
+ representation.
419
+
420
+ This function extracts and transforms the components (dimensions, measures, and attributes)
421
+ from the given SDMX data structure and maps them into a dictionary format that conforms
422
+ to the expected VTL data structure json schema.
423
+
424
+ Args:
425
+ dsd: An instance of `DataStructureDefinition` or `Schema` from the `pysdmx` model.
426
+ dataset_name: The name of the resulting VTL dataset.
427
+
428
+ Returns:
429
+ A dictionary representing the dataset in VTL format, with keys for dataset name and its
430
+ components, including their name, role, data type, and nullability.
431
+ """
432
+ components = []
433
+ NAME = "name"
434
+ ROLE = "role"
435
+ TYPE = "type"
436
+ NULLABLE = "nullable"
437
+
438
+ _components: List[SDMXComponent] = []
439
+ _components.extend(dsd.components.dimensions)
440
+ _components.extend(dsd.components.measures)
441
+ _components.extend(dsd.components.attributes)
442
+
443
+ for c in _components:
444
+ _type = VTL_DTYPES_MAPPING[c.dtype]
445
+ _nullability = c.role != SDMX_Role.DIMENSION
446
+ _role = VTL_ROLE_MAPPING[c.role]
447
+
448
+ component = {
449
+ NAME: c.id,
450
+ ROLE: _role,
451
+ TYPE: _type,
452
+ NULLABLE: _nullability,
453
+ }
454
+
455
+ components.append(component)
456
+
457
+ result = {"datasets": [{"name": dataset_name, "DataStructure": components}]}
458
+
459
+ return result
460
+
461
+
462
+ def __generate_transformation(
463
+ child: Union[Assignment, PersistentAssignment], is_persistent: bool, count: int
464
+ ) -> Transformation:
465
+ expression = ASTString().render(ast=child.right)
466
+ result = child.left.value # type: ignore[attr-defined]
467
+ return Transformation(
468
+ id=f"T{count}",
469
+ expression=expression,
470
+ is_persistent=is_persistent,
471
+ result=result,
472
+ name=f"Transformation {result}",
473
+ )
474
+
475
+
476
+ def __generate_udo(child: Operator, count: int) -> UserDefinedOperator:
477
+ operator_definition = ASTString().render(ast=child)
478
+ return UserDefinedOperator(
479
+ id=f"UDO{count}",
480
+ operator_definition=operator_definition,
481
+ name=f"UserDefinedOperator {child.op}",
482
+ )
483
+
484
+
485
+ def __generate_ruleset(child: Union[DPRuleset, HRuleset], count: int) -> Ruleset:
486
+ ruleset_definition = ASTString().render(ast=child)
487
+ ruleset_type: Literal["datapoint", "hierarchical"] = (
488
+ "datapoint" if isinstance(child, DPRuleset) else "hierarchical"
489
+ )
490
+ return Ruleset(
491
+ id=f"R{count}",
492
+ ruleset_definition=ruleset_definition,
493
+ ruleset_type=ruleset_type,
494
+ name=f"{ruleset_type.capitalize()} ruleset {child.name}",
495
+ )
496
+
497
+
498
+ def ast_to_sdmx(ast: AST.Start, agency_id: str, id: str, version: str) -> TransformationScheme:
499
+ """
500
+ Converts a vtl AST into an SDMX compatible `TransformationScheme` object, following
501
+ the pysdmx model.
502
+
503
+ This function iterates over the child nodes of the given AST and categorizes each into one of
504
+ the following types:
505
+ - `PersistentAssignment`: Represents a persistent transformation. These are added to the
506
+ transformation list with a persistence flag.
507
+ - `Assignment`: Represents a temporary (non-persistent) transformation. These are added to the
508
+ transformation list without the persistence flag
509
+ - `DPRuleset` or `HRuleset`: Represent validation rule sets.
510
+ These are collected and wrapped into a `RulesetScheme` object.
511
+ - `Operator`: Defines user-defined operators. These are collected
512
+ into a `UserDefinedOperatorScheme` object.
513
+
514
+ After parsing all AST elements:
515
+ - If any rulesets were found, a `RulesetScheme` is created and added to the references.
516
+ - If any user-defined operators were found, a `UserDefinedOperatorScheme` is created and added
517
+ to the references.
518
+ - A `TransformationScheme` object is constructed with all collected transformations and any
519
+ additional references.
520
+
521
+ Args:
522
+ ast: The root node of the vtl ast representing the set of
523
+ vtl expressions.
524
+ agency_id: The identifier of the agency defining the SDMX structure as a string.
525
+ id: The identifier of the transformation scheme as a string.
526
+ version: The version of the transformation scheme given as a string.
527
+
528
+ Returns:
529
+ TransformationScheme: A fully constructed transformation scheme that includes
530
+ transformations, and optionally rule sets and user-defined operator schemes,
531
+ suitable for SDMX.
532
+
533
+ """
534
+ list_transformation = []
535
+ list_udos = []
536
+ list_rulesets = []
537
+ count_transformation = 0
538
+ count_udo = 0
539
+ count_ruleset = 0
540
+
541
+ for child in ast.children:
542
+ if isinstance(child, PersistentAssignment):
543
+ count_transformation += 1
544
+ list_transformation.append(
545
+ __generate_transformation(
546
+ child=child, is_persistent=True, count=count_transformation
547
+ )
548
+ )
549
+ elif isinstance(child, Assignment):
550
+ count_transformation += 1
551
+ list_transformation.append(
552
+ __generate_transformation(
553
+ child=child, is_persistent=False, count=count_transformation
554
+ )
555
+ )
556
+ elif isinstance(child, (DPRuleset, HRuleset)):
557
+ count_ruleset += 1
558
+ list_rulesets.append(__generate_ruleset(child=child, count=count_ruleset))
559
+ elif isinstance(child, Operator):
560
+ count_udo += 1
561
+ list_udos.append(__generate_udo(child=child, count=count_udo))
562
+
563
+ references: Any = {}
564
+ if list_rulesets:
565
+ references["ruleset_schemes"] = [
566
+ RulesetScheme(
567
+ items=list_rulesets,
568
+ agency=agency_id,
569
+ id="RS1",
570
+ vtl_version="2.1",
571
+ version=version,
572
+ name=f"RulesetScheme {id}-RS",
573
+ )
574
+ ]
575
+ if list_udos:
576
+ references["user_defined_operator_schemes"] = [
577
+ UserDefinedOperatorScheme(
578
+ items=list_udos,
579
+ agency=agency_id,
580
+ id="UDS1",
581
+ vtl_version="2.1",
582
+ version=version,
583
+ name=f"UserDefinedOperatorScheme {id}-UDS",
584
+ )
585
+ ]
586
+
587
+ transformation_scheme = TransformationScheme(
588
+ items=list_transformation,
589
+ agency=agency_id,
590
+ id="TS1",
591
+ vtl_version="2.1",
592
+ version=version,
593
+ name=f"TransformationScheme {id}",
594
+ **references,
595
+ )
596
+
597
+ return transformation_scheme
598
+
599
+
600
+ def _check_script(script: Union[str, TransformationScheme, Path]) -> str:
601
+ """
602
+ Check if the TransformationScheme object is valid to generate a vtl script.
603
+ """
604
+ if not isinstance(script, (str, TransformationScheme, Path)):
605
+ raise Exception(
606
+ "Invalid script format. Input must be a string, TransformationScheme or Path object"
607
+ )
608
+ if isinstance(script, TransformationScheme):
609
+ from pysdmx.toolkit.vtl.generate_vtl_script import (
610
+ generate_vtl_script,
611
+ )
612
+
613
+ vtl_script = generate_vtl_script(script, model_validation=True)
614
+ return vtl_script
615
+ else:
616
+ return str(script)