xtft 0.1.0__py3-none-any.whl

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.
Files changed (124) hide show
  1. xtft/__init__.py +80 -0
  2. xtft/_configs.py +220 -0
  3. xtft/_deps.py +145 -0
  4. xtft/_dummies.py +119 -0
  5. xtft/_log.py +137 -0
  6. xtft/_log.yml +59 -0
  7. xtft/_optdeps.py +162 -0
  8. xtft/_util.py +44 -0
  9. xtft/api/bunch.py +721 -0
  10. xtft/api/docs.py +2690 -0
  11. xtft/api/property.py +2256 -0
  12. xtft/api/summary.py +180 -0
  13. xtft/api/types.py +256 -0
  14. xtft/api/util.py +5175 -0
  15. xtft/backends/__init__.py +31 -0
  16. xtft/backends/_framework.py +263 -0
  17. xtft/backends/array/base.py +138 -0
  18. xtft/backends/array/cupy.py +303 -0
  19. xtft/backends/array/dask.py +466 -0
  20. xtft/backends/array/devices.py +360 -0
  21. xtft/backends/array/nn.py +1270 -0
  22. xtft/backends/array/numpy.py +261 -0
  23. xtft/backends/array/scipy.py +245 -0
  24. xtft/backends/array/selector.py +1017 -0
  25. xtft/compat/__init__.py +41 -0
  26. xtft/compat/_config.py +199 -0
  27. xtft/compat/keras.py +925 -0
  28. xtft/compat/keras_fit.py +475 -0
  29. xtft/compat/kt.py +125 -0
  30. xtft/compat/numpy.py +98 -0
  31. xtft/compat/pandas.py +660 -0
  32. xtft/compat/scipy.py +393 -0
  33. xtft/compat/sklearn.py +1150 -0
  34. xtft/compat/tf.py +1182 -0
  35. xtft/compat/torch.py +99 -0
  36. xtft/compat/types.py +85 -0
  37. xtft/core/array_manager.py +4649 -0
  38. xtft/core/checks.py +7479 -0
  39. xtft/core/diagnose_q.py +2237 -0
  40. xtft/core/handlers.py +2685 -0
  41. xtft/core/io.py +2705 -0
  42. xtft/core/utils.py +3128 -0
  43. xtft/data/__init__.py +19 -0
  44. xtft/data/panel.py +549 -0
  45. xtft/data/seasonality.py +203 -0
  46. xtft/decorators.py +5154 -0
  47. xtft/evaluation/__init__.py +57 -0
  48. xtft/evaluation/bands.py +489 -0
  49. xtft/evaluation/conformal.py +637 -0
  50. xtft/evaluation/metrics.py +559 -0
  51. xtft/evaluation/stats.py +326 -0
  52. xtft/exceptions.py +336 -0
  53. xtft/metrics/__init__.py +32 -0
  54. xtft/metrics/_cas.py +470 -0
  55. xtft/metrics/_metrics.py +3500 -0
  56. xtft/metrics/_registry.py +217 -0
  57. xtft/nn/__init__.py +124 -0
  58. xtft/nn/tf/__init__.py +60 -0
  59. xtft/nn/tf/_shapes.py +1124 -0
  60. xtft/nn/tf/_tensor_validation.py +3845 -0
  61. xtft/nn/tf/_utils.py +7549 -0
  62. xtft/nn/tf/anomaly_detection.py +1065 -0
  63. xtft/nn/tf/calibration.py +312 -0
  64. xtft/nn/tf/callbacks.py +1317 -0
  65. xtft/nn/tf/components/__init__.py +154 -0
  66. xtft/nn/tf/components/_attention_utils.py +160 -0
  67. xtft/nn/tf/components/_config.py +207 -0
  68. xtft/nn/tf/components/_loss_utils.py +215 -0
  69. xtft/nn/tf/components/_temporal_utils.py +469 -0
  70. xtft/nn/tf/components/attention.py +1195 -0
  71. xtft/nn/tf/components/encoder_decoder.py +616 -0
  72. xtft/nn/tf/components/gating_norm.py +1081 -0
  73. xtft/nn/tf/components/heads.py +694 -0
  74. xtft/nn/tf/components/layer_utils.py +360 -0
  75. xtft/nn/tf/components/losses.py +940 -0
  76. xtft/nn/tf/components/masks.py +130 -0
  77. xtft/nn/tf/components/misc.py +1066 -0
  78. xtft/nn/tf/components/temporal.py +357 -0
  79. xtft/nn/tf/components/utils.py +243 -0
  80. xtft/nn/tf/custom_metrics.py +211 -0
  81. xtft/nn/tf/hybrid/__init__.py +11 -0
  82. xtft/nn/tf/hybrid/_base_extreme.py +636 -0
  83. xtft/nn/tf/hybrid/_super_xtft.py +677 -0
  84. xtft/nn/tf/hybrid/_xtft.py +607 -0
  85. xtft/nn/tf/hybrid/utils.py +852 -0
  86. xtft/nn/tf/keras_metrics.py +1313 -0
  87. xtft/nn/tf/keras_validator.py +643 -0
  88. xtft/nn/tf/losses.py +1139 -0
  89. xtft/nn/tf/transformers/__init__.py +10 -0
  90. xtft/nn/tf/transformers/_adj_tft.py +777 -0
  91. xtft/nn/tf/transformers/_tft.py +1060 -0
  92. xtft/nn/torch/__init__.py +16 -0
  93. xtft/nn/torch/layers/__init__.py +24 -0
  94. xtft/nn/torch/layers/attention.py +332 -0
  95. xtft/nn/torch/layers/grn.py +215 -0
  96. xtft/nn/torch/layers/missing.py +226 -0
  97. xtft/nn/torch/layers/multiresolution.py +348 -0
  98. xtft/nn/torch/layers/variable_selection.py +193 -0
  99. xtft/nn/torch/models/__init__.py +5 -0
  100. xtft/nn/torch/models/xtft.py +638 -0
  101. xtft/nn/torch/probabilistic/__init__.py +11 -0
  102. xtft/nn/torch/probabilistic/losses.py +139 -0
  103. xtft/nn/torch/probabilistic/quantile_head.py +154 -0
  104. xtft/nn/torch/trainer.py +357 -0
  105. xtft/utils/_array_api.py +183 -0
  106. xtft/utils/_dependency.py +187 -0
  107. xtft/utils/base_utils.py +1532 -0
  108. xtft/utils/calibrate.py +950 -0
  109. xtft/utils/data_utils.py +1278 -0
  110. xtft/utils/deps_utils.py +1401 -0
  111. xtft/utils/forecast_utils.py +4507 -0
  112. xtft/utils/generic_utils.py +4018 -0
  113. xtft/utils/io_utils.py +3465 -0
  114. xtft/utils/sequence_utils.py +1701 -0
  115. xtft/utils/shapes.py +1183 -0
  116. xtft/utils/sys_utils.py +3161 -0
  117. xtft/utils/ts_utils.py +4975 -0
  118. xtft/utils/validator.py +7647 -0
  119. xtft/utils/version.py +581 -0
  120. xtft-0.1.0.dist-info/METADATA +310 -0
  121. xtft-0.1.0.dist-info/RECORD +124 -0
  122. xtft-0.1.0.dist-info/WHEEL +5 -0
  123. xtft-0.1.0.dist-info/licenses/LICENSE +28 -0
  124. xtft-0.1.0.dist-info/top_level.txt +1 -0
xtft/_log.py ADDED
@@ -0,0 +1,137 @@
1
+ # -*- coding: utf-8 -*-
2
+ # License: BSD-3-Clause
3
+ # Author: LKouadio <etanoyau@gmail.com>
4
+
5
+ """
6
+ Track bugs and issues, and handle all FusionLab exceptions.
7
+
8
+ This module provides a logging utility class `fusionlog` to configure and manage
9
+ logging across the `FusionLab` package. It supports various logging configurations,
10
+ including YAML and INI formats, and offers methods to set up default loggers,
11
+ retrieve named loggers, and configure log file outputs.
12
+
13
+ The module also includes helper functions to set up logging with environment
14
+ variable substitutions, enhancing flexibility in different deployment scenarios.
15
+ """
16
+
17
+ import os
18
+ import yaml
19
+ import logging
20
+ import logging.config
21
+ from string import Template # Noqa
22
+ from typing import Optional
23
+
24
+
25
+ __all__ = ["fusionlog"]
26
+
27
+
28
+ class fusionlog:
29
+ @staticmethod
30
+ def load_configuration(
31
+ config_path: Optional[str] = None,
32
+ use_default_logger: bool = True,
33
+ verbose: bool = False
34
+ ) -> None:
35
+ if not config_path:
36
+ if use_default_logger:
37
+ fusionlog.set_default_logger()
38
+ else:
39
+ logging.basicConfig()
40
+ return
41
+
42
+ if verbose:
43
+ print(f"Configuring logging with: {config_path}")
44
+
45
+ if config_path.endswith((".yaml", ".yml")):
46
+ fusionlog._configure_from_yaml(config_path, verbose)
47
+ elif config_path.endswith(".ini"):
48
+ logging.config.fileConfig(config_path, disable_existing_loggers=False)
49
+ else:
50
+ logging.warning(
51
+ f"Unsupported logging configuration format: {config_path}"
52
+ )
53
+
54
+ @staticmethod
55
+ def _configure_from_yaml(yaml_path: str, verbose: bool = False) -> None:
56
+ full_path = os.path.abspath(yaml_path)
57
+ if not os.path.exists(full_path):
58
+ logging.error(f"The YAML config file {full_path} does not exist.")
59
+ raise FileNotFoundError(f"The YAML config file {full_path} does not exist.")
60
+
61
+ if verbose:
62
+ print(f"Loading YAML config from {full_path}")
63
+
64
+ try:
65
+ with open(full_path, "rt") as f:
66
+ config = yaml.safe_load(f.read())
67
+ logging.config.dictConfig(config)
68
+ except yaml.YAMLError as e:
69
+ logging.error(f"Error parsing YAML config file: {e}")
70
+ raise
71
+
72
+ @staticmethod
73
+ def set_default_logger() -> None:
74
+ logging.basicConfig(
75
+ level=logging.INFO,
76
+ format='%(asctime)s - %(levelname)s - %(message)s'
77
+ )
78
+
79
+ @staticmethod
80
+ def get_fusionlab_logger(logger_name: str = '') -> logging.Logger:
81
+ return logging.getLogger(logger_name)
82
+
83
+ @staticmethod
84
+ def set_logger_output(
85
+ log_filename: str = "xtft.log",
86
+ date_format: str = '%Y-%m-%d %H:%M:%S',
87
+ file_mode: str = "w",
88
+ format_: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
89
+ level: int = logging.DEBUG
90
+ ) -> None:
91
+ handler = logging.FileHandler(log_filename, mode=file_mode)
92
+ handler.setLevel(level)
93
+ formatter = logging.Formatter(format_, datefmt=date_format)
94
+ handler.setFormatter(formatter)
95
+
96
+ logger = fusionlog.get_fusionlab_logger()
97
+ logger.setLevel(level)
98
+ logger.addHandler(handler)
99
+
100
+ logger.handlers = list(set(logger.handlers))
101
+
102
+
103
+ class OncePerMessageFilter(logging.Filter):
104
+ """Filter that lets each distinct log message through exactly once."""
105
+ def __init__(self, name: str = "") -> None:
106
+ super().__init__(name)
107
+ self._seen: set[str] = set()
108
+
109
+ def filter(self, record: logging.LogRecord) -> bool: # noqa: D401
110
+ key = record.getMessage()
111
+ if key in self._seen:
112
+ return False # suppress duplicate
113
+ self._seen.add(key)
114
+ return True
115
+
116
+
117
+ def setup_logging(config_path: str = 'path/to/_flog.yml') -> None:
118
+ with open(config_path, 'rt') as f:
119
+ config = yaml.safe_load(f.read())
120
+
121
+ log_path = os.getenv('LOG_PATH', config.get('default_log_path', '/fallback/path'))
122
+
123
+ if 'handlers' in config:
124
+ for handler in config['handlers'].values():
125
+ if 'filename' in handler:
126
+ handler['filename'] = handler['filename'].replace('${LOG_PATH}', log_path)
127
+
128
+ logging.config.dictConfig(config)
129
+
130
+
131
+ if __name__ == '__main__':
132
+ """
133
+ Entry point for testing the `fusionlog` module.
134
+
135
+ Prints the absolute path of the `fusionlog` module.
136
+ """
137
+ print(os.path.abspath(fusionlog.__name__))
xtft/_log.yml ADDED
@@ -0,0 +1,59 @@
1
+ version: 1
2
+ disable_existing_loggers: False
3
+
4
+ formatters:
5
+ detailed:
6
+ format: "%(asctime)s - %(name)s - %(levelname)s - [%(threadName)s] [%(process)d] %(message)s"
7
+ datefmt: "%Y-%m-%dT%H:%M:%S"
8
+
9
+ handlers:
10
+ console:
11
+ class: logging.StreamHandler
12
+ level: INFO
13
+ formatter: detailed
14
+ stream: ext://sys.stdout
15
+
16
+ info_file_handler:
17
+ class: logging.handlers.TimedRotatingFileHandler
18
+ level: INFO
19
+ formatter: detailed
20
+ filename: "fusionlab/flogs/infos.log"
21
+ when: midnight
22
+ backupCount: 7
23
+ encoding: utf-8
24
+ delay: True
25
+
26
+ error_file_handler:
27
+ class: logging.handlers.RotatingFileHandler
28
+ level: ERROR
29
+ formatter: detailed
30
+ filename: "fusionlab/flogs/errors.log"
31
+ maxBytes: 1048576 # 1MB
32
+ backupCount: 5
33
+ encoding: utf-8
34
+ delay: True
35
+
36
+ warning_file_handler:
37
+ class: logging.handlers.RotatingFileHandler
38
+ level: WARNING
39
+ formatter: detailed
40
+ filename: "fusionlab/flogs/warnings.log"
41
+ maxBytes: 1048576 # 1MB
42
+ backupCount: 5
43
+ encoding: utf-8
44
+ delay: True
45
+
46
+ loggers:
47
+ fusionlab:
48
+ level: DEBUG
49
+ handlers: [info_file_handler, error_file_handler, warning_file_handler]
50
+ propagate: no
51
+
52
+ __main__:
53
+ level: DEBUG
54
+ handlers: [info_file_handler, error_file_handler, warning_file_handler]
55
+ propagate: no
56
+
57
+ root:
58
+ level: DEBUG
59
+ handlers: [info_file_handler, error_file_handler, warning_file_handler]
xtft/_optdeps.py ADDED
@@ -0,0 +1,162 @@
1
+ # -*- coding: utf-8 -*-
2
+ # License: BSD-3-Clause
3
+ # Author: LKouadio <etanoyau@gmail.com>
4
+ """
5
+ Internal utilities for optional third-party dependencies.
6
+
7
+ This module centralizes feature flags such as ``HAS_TQDM`` so that
8
+ other modules can check availability of extra packages without
9
+ repeating try/except import blocks.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Callable
15
+ from typing import Any, Optional, Iterable, TypeVar
16
+
17
+
18
+ T = TypeVar("T")
19
+
20
+ # ---------------------------------------------------------------------
21
+ # tqdm (progress bar)
22
+ # ---------------------------------------------------------------------
23
+ HAS_TQDM: bool
24
+ TQDM: Optional[Any]
25
+
26
+ try: # pragma: no cover - optional dependency
27
+ from tqdm.auto import tqdm as _tqdm
28
+ except Exception: # pragma: no cover
29
+ HAS_TQDM = False
30
+ _tqdm = None
31
+ else:
32
+ HAS_TQDM = True
33
+
34
+ TQDM = _tqdm
35
+
36
+
37
+ class _TqdmLogStream:
38
+ """
39
+ Minimal file-like stream that forwards tqdm's text output
40
+ to a logger function instead of the terminal.
41
+
42
+ It buffers partial lines until a newline or carriage return
43
+ to avoid spamming the logger for every tiny write.
44
+ """
45
+
46
+ def __init__(self, log_fn: Callable[[str], None]) -> None:
47
+ self._log_fn = log_fn
48
+ self._buf = ""
49
+
50
+ def write(self, s: str) -> int:
51
+ # tqdm sometimes writes bytes or weird objects; be defensive
52
+ s = str(s)
53
+ if not s:
54
+ return 0
55
+
56
+ self._buf += s
57
+
58
+ # tqdm uses '\r' a lot; treat both '\n' and '\r' as flush points
59
+ for sep in ("\n", "\r"):
60
+ if sep in self._buf:
61
+ parts = self._buf.split(sep)
62
+ # all but last are complete "lines"
63
+ for line in parts[:-1]:
64
+ line = line.strip()
65
+ if line:
66
+ self._log_fn(line)
67
+ # keep the trailing incomplete fragment (if any)
68
+ self._buf = parts[-1]
69
+
70
+ return len(s)
71
+
72
+ def flush(self) -> None:
73
+ # Flush whatever is left in the buffer as a final line
74
+ if self._buf.strip():
75
+ self._log_fn(self._buf.strip())
76
+ self._buf = ""
77
+
78
+
79
+ def with_progress(
80
+ iterable: Iterable[T],
81
+ *,
82
+ total: Optional[int] = None,
83
+ desc: Optional[str] = None,
84
+ ascii: bool = True,
85
+ leave: bool = False,
86
+ disable: Optional[bool] = None,
87
+ log_fn: Optional[Callable[[str], None]] = None,
88
+ **tqdm_kwargs: Any,
89
+ ) -> Iterable[T]:
90
+ """
91
+ Wrap an iterable with tqdm if available, else return it unchanged.
92
+
93
+ Parameters
94
+ ----------
95
+ iterable :
96
+ Any iterable (e.g. Dataset, list, generator).
97
+ total : int or None, optional
98
+ Expected length for the progress bar. If None, tries
99
+ ``len(iterable)``; if that fails, tqdm will show an unknown
100
+ total.
101
+ desc : str or None, optional
102
+ Progress bar description (left side label).
103
+ ascii : bool, default=True
104
+ Whether to force an ASCII progress bar (safer on some
105
+ terminals).
106
+ leave : bool, default=False
107
+ Whether to leave the progress bar after completion.
108
+ disable : bool or None, optional
109
+ If True, always disable tqdm (return raw iterable).
110
+ If None, uses tqdm if installed; otherwise falls back.
111
+ log_fn : callable or None, optional
112
+ If provided, tqdm's progress bar output is redirected into
113
+ this logger instead of the terminal. The logger must accept
114
+ a single string argument.
115
+ **tqdm_kwargs :
116
+ Any additional keyword arguments passed directly to tqdm.
117
+
118
+ Returns
119
+ -------
120
+ iterable
121
+ If tqdm is installed and not disabled, a tqdm-wrapped
122
+ iterable; otherwise the original iterable.
123
+ """
124
+ # Explicitly disabled or tqdm not installed → raw iterable
125
+ if disable is True or not HAS_TQDM or TQDM is None:
126
+ return iterable
127
+
128
+ try:
129
+ # Try to infer total if not provided
130
+ if total is None:
131
+ try:
132
+ total = len(iterable) # type: ignore[arg-type]
133
+ except Exception:
134
+ total = None
135
+
136
+ tqdm_args = {
137
+ "total": total,
138
+ "desc": desc,
139
+ "ascii": ascii,
140
+ "leave": leave,
141
+ }
142
+ tqdm_args.update(tqdm_kwargs)
143
+
144
+ # If a logger is provided, redirect tqdm output to it
145
+ if log_fn is not None:
146
+ tqdm_args["file"] = _TqdmLogStream(log_fn)
147
+
148
+ return TQDM(
149
+ iterable,
150
+ **tqdm_args,
151
+ )
152
+ except Exception:
153
+ # Any failure → graceful fallback to plain iterable
154
+ return iterable
155
+
156
+
157
+
158
+ __all__ = [
159
+ "HAS_TQDM",
160
+ "TQDM",
161
+ "with_progress",
162
+ ]
xtft/_util.py ADDED
@@ -0,0 +1,44 @@
1
+
2
+ from __future__ import annotations
3
+
4
+ import warnings
5
+ import logging
6
+ from xtft._log import fusionlog
7
+
8
+ def initialize_logging(
9
+ config_path: str | None = None,
10
+ use_default_logger: bool = True,
11
+ verbose: bool = False
12
+ ) -> None:
13
+ """
14
+ Initialize FusionLab structured logging.
15
+
16
+ Attempts to load the logging configuration via `fusionlog.load_configuration`.
17
+ On failure, emits a warning and falls back to a basic console logger.
18
+
19
+ Parameters
20
+ ----------
21
+ config_path : str | None
22
+ Path to a YAML/INI logging config. If None, uses default/basic config.
23
+ use_default_logger : bool
24
+ Whether to install the default FusionLab logger if config_path is None.
25
+ verbose : bool
26
+ If True, prints out which config file is being used.
27
+ """
28
+ try:
29
+ fusionlog.load_configuration(
30
+ config_path=config_path,
31
+ use_default_logger=use_default_logger,
32
+ verbose=verbose
33
+ )
34
+ except Exception as e:
35
+ warnings.warn(
36
+ f"FusionLab logging initialization failed: {e}. "
37
+ "Falling back to basic console logging.",
38
+ RuntimeWarning
39
+ )
40
+ # Basic fallback
41
+ logging.basicConfig(
42
+ level=logging.INFO,
43
+ format="%(asctime)s - %(levelname)s - %(message)s"
44
+ )