hots 2.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.
hots/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ """Expose the package version."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+ from pathlib import Path
7
+
8
+
9
+ def _read_dist_version() -> str | None:
10
+ """Version of the installed distribution (VERSION.txt at build time)."""
11
+ try:
12
+ return version("hots")
13
+ except PackageNotFoundError:
14
+ return None
15
+
16
+
17
+ def _read_version_txt() -> str | None:
18
+ """VERSION.txt of a source checkout that isn't installed.
19
+
20
+ Returns None if not found/readable.
21
+ """
22
+ # repo layout: <root>/hots/__init__.py and <root>/VERSION.txt
23
+ p = Path(__file__).resolve().parent.parent / "VERSION.txt"
24
+ try:
25
+ return p.read_text(encoding="utf-8").strip()
26
+ except OSError:
27
+ return None
28
+
29
+
30
+ __version__ = _read_dist_version() or _read_version_txt() or "0.0.0"
hots/cli.py ADDED
@@ -0,0 +1,35 @@
1
+ """Command‑line interface for the HOTS application."""
2
+
3
+ import click
4
+
5
+ from hots.config.loader import load_config
6
+ from hots.core.app import App
7
+ from hots.utils.logging_config import setup_logging
8
+
9
+
10
+ @click.command()
11
+ @click.version_option(package_name="hots")
12
+ @click.option(
13
+ "--config",
14
+ "-c",
15
+ "config_path",
16
+ required=True,
17
+ type=click.Path(exists=True),
18
+ help="Path to the JSON config file",
19
+ )
20
+ def main(config_path):
21
+ """Load the configuration and run the HOTS application."""
22
+ cfg = load_config(config_path)
23
+
24
+ setup_logging(
25
+ level=cfg.logging.level,
26
+ filename=cfg.logging.filename,
27
+ fmt=cfg.logging.fmt,
28
+ )
29
+
30
+ app = App(cfg)
31
+ app.run()
32
+
33
+
34
+ if __name__ == "__main__":
35
+ main()
hots/config/loader.py ADDED
@@ -0,0 +1,308 @@
1
+ """Configuration loader for the HOTS application."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Mapping, Sequence
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
11
+
12
+ # Base model config
13
+
14
+
15
+ class _Cfg(BaseModel):
16
+ """
17
+ Shared configuration for all config models.
18
+
19
+ - extra="forbid" catches typos / unknown keys early.
20
+ - validate_assignment is handy if configs are modified programmatically.
21
+ """
22
+
23
+ model_config = ConfigDict(extra="forbid", validate_assignment=True)
24
+
25
+
26
+ # Core configuration sections
27
+
28
+
29
+ class KafkaConfig(_Cfg):
30
+ """Configuration for the Kafka connector: topics and optional schema settings."""
31
+
32
+ topics: list[str]
33
+ schema_: dict[str, Any] | None = Field(default=None, alias="schema")
34
+ schema_url: str | None = None
35
+ connector_url: str = ""
36
+
37
+ model_config = ConfigDict(extra="forbid", populate_by_name=True)
38
+
39
+
40
+ class ClusteringConfig(_Cfg):
41
+ """Configuration for the clustering plugin: method name and its parameters."""
42
+
43
+ method: str
44
+ nb_clusters: int
45
+ parameters: dict[str, Any]
46
+
47
+
48
+ class OptimizationConfig(_Cfg):
49
+ """Configuration for the optimization plugin: backend and its parameters."""
50
+
51
+ backend: str
52
+ parameters: dict[str, Any]
53
+
54
+
55
+ class ProblemConfig(_Cfg):
56
+ """Configuration for the domain problem plugin: type and its parameters."""
57
+
58
+ type: str
59
+ parameters: dict[str, Any]
60
+
61
+
62
+ class ConnectorConfig(_Cfg):
63
+ """Configuration for the connector plugin: type and its parameters."""
64
+
65
+ type: str
66
+ parameters: dict[str, Any]
67
+
68
+
69
+ #: Field names describing the input series, shared by every component.
70
+ DATA_FIELD_KEYS = ("tick_field", "individual_field", "host_field", "metrics")
71
+
72
+
73
+ class DataConfig(_Cfg):
74
+ """Names of the columns describing the input time series.
75
+
76
+ These belong to the *data*, not to whichever connector happens to deliver it,
77
+ so they live in a top-level ``data`` section that every component reads. For
78
+ backward compatibility they may still be given under
79
+ ``connector.parameters``; see :meth:`AppConfig._sync_data_section`.
80
+ """
81
+
82
+ tick_field: str = "timestamp"
83
+ individual_field: str = "container_id"
84
+ host_field: str = "machine_id"
85
+ metrics: list[str]
86
+
87
+ @model_validator(mode="after")
88
+ def _enforce_single_metric(self):
89
+ """Reject multi-metric configs: the pipeline only uses ``metrics[0]``.
90
+
91
+ The clustering matrices, the placement heuristics and both Pyomo models
92
+ all read a single metric column, so a config listing several would
93
+ silently optimize only the first. Fail loudly instead.
94
+ """
95
+ if len(self.metrics) != 1:
96
+ raise ValueError(
97
+ "data.metrics currently supports exactly one metric "
98
+ f"(got {list(self.metrics)}); multi-metric optimization is not implemented."
99
+ )
100
+ return self
101
+
102
+
103
+ class LoggingConfig(_Cfg):
104
+ """Configuration for application-wide logging."""
105
+
106
+ level: str # e.g. "INFO" or "DEBUG"
107
+ filename: str | None = None # if None, logs to stdout
108
+ fmt: str # e.g. "%(asctime)s %(levelname)s: %(message)s"
109
+
110
+
111
+ class ReportingConfig(_Cfg):
112
+ """Configuration for reporting: folders and file paths for outputs."""
113
+
114
+ results_folder: Path
115
+ metrics_file: Path
116
+ plots_folder: Path
117
+
118
+
119
+ # Visualization configuration
120
+
121
+
122
+ class SaveConfig(_Cfg):
123
+ enabled: bool = True
124
+ plots_folder: Path | None = None # if None -> don't save unless explicit out_path is passed
125
+ default_format: str = "png"
126
+ dpi: int = 150
127
+ bbox_inches: str = "tight"
128
+ close_on_save: bool = True
129
+
130
+ @field_validator("plots_folder", mode="before")
131
+ @classmethod
132
+ def _empty_string_to_none(cls, v):
133
+ # Preserve your previous behavior: "" (or None) means "no folder".
134
+ if v in (None, ""):
135
+ return None
136
+ return v
137
+
138
+
139
+ class ColorConfig(_Cfg):
140
+ clusters: Sequence[str] = (
141
+ "blue",
142
+ "orange",
143
+ "green",
144
+ "red",
145
+ "purple",
146
+ "brown",
147
+ "pink",
148
+ "gray",
149
+ "olive",
150
+ "cyan",
151
+ "turquoise",
152
+ "chocolate",
153
+ "navy",
154
+ "lightcoral",
155
+ "violet",
156
+ )
157
+ highlight: Sequence[str] = ("violet", "lightcoral", "navy", "chocolate", "turquoise")
158
+
159
+
160
+ class DendrogramConfig(_Cfg):
161
+ leaf_rotation: float = 90.0
162
+ leaf_font_size: float = 8.0
163
+
164
+
165
+ class SpringLayoutConfig(_Cfg):
166
+ k: float = 0.15
167
+ iterations: int = 20
168
+
169
+
170
+ class GraphConfig(_Cfg):
171
+ spring_layout: SpringLayoutConfig = Field(default_factory=SpringLayoutConfig)
172
+ show_edge_weights: bool = True
173
+
174
+
175
+ class NodesConfig(_Cfg):
176
+ capacity_margin_ratio: float = 0.2
177
+ sep_time_color: str = "red"
178
+ sep_time_style: str = "--"
179
+ capacity_color: str = "red"
180
+
181
+
182
+ class LiveConfig(_Cfg):
183
+ pause_seconds: float = 0.5
184
+
185
+
186
+ class NamingConfig(_Cfg):
187
+ prefix: str = ""
188
+ suffix: str = ""
189
+ slugify: bool = True
190
+
191
+
192
+ class VisualizationConfig(_Cfg):
193
+ enabled: bool = True
194
+ default_metric: str = "cpu"
195
+
196
+ save: SaveConfig = Field(default_factory=SaveConfig)
197
+ colors: ColorConfig = Field(default_factory=ColorConfig)
198
+
199
+ dendrogram: DendrogramConfig = Field(default_factory=DendrogramConfig)
200
+ graphs: GraphConfig = Field(default_factory=GraphConfig)
201
+ nodes: NodesConfig = Field(default_factory=NodesConfig)
202
+ live: LiveConfig = Field(default_factory=LiveConfig)
203
+ naming: NamingConfig = Field(default_factory=NamingConfig)
204
+
205
+ @model_validator(mode="before")
206
+ @classmethod
207
+ def _unwrap_optional_visualization_root(cls, data):
208
+ """
209
+ Preserve old tolerance:
210
+ - accept either {"enabled": ..., ...}
211
+ - or {"visualization": {...}} as an extra wrapper
212
+ """
213
+ if isinstance(data, Mapping) and "visualization" in data and len(data) == 1:
214
+ inner = data.get("visualization")
215
+ if isinstance(inner, Mapping):
216
+ return inner
217
+ return data
218
+
219
+
220
+ # Top-level configuration
221
+
222
+
223
+ class AppConfig(_Cfg):
224
+ """Top-level application configuration, combining all sub-configs."""
225
+
226
+ time_limit: int | None = Field(default=None, ge=0)
227
+ kafka: KafkaConfig | None = None
228
+ data: DataConfig
229
+ clustering: ClusteringConfig
230
+ optimization: OptimizationConfig
231
+ problem: ProblemConfig
232
+ connector: ConnectorConfig
233
+ logging: LoggingConfig
234
+ reporting: ReportingConfig
235
+ viz: VisualizationConfig = Field(default_factory=VisualizationConfig, alias="visualization")
236
+
237
+ model_config = ConfigDict(
238
+ extra="forbid",
239
+ validate_assignment=True,
240
+ populate_by_name=True, # allows using either "viz" or "visualization" when needed
241
+ )
242
+
243
+ @model_validator(mode="before")
244
+ @classmethod
245
+ def _sync_data_section(cls, values):
246
+ """Keep the ``data`` section and ``connector.parameters`` in agreement.
247
+
248
+ Field names used to live under ``connector.parameters``. They now belong
249
+ in a top-level ``data`` section, but both spellings stay valid:
250
+
251
+ - given only under ``connector.parameters``, they populate ``data``;
252
+ - given only under ``data``, they are mirrored into
253
+ ``connector.parameters`` so connector plugins keep working unchanged;
254
+ - given in both places with different values, that is a config error.
255
+ """
256
+ if not isinstance(values, Mapping):
257
+ return values
258
+
259
+ values = dict(values)
260
+ connector = values.get("connector")
261
+ if not isinstance(connector, Mapping):
262
+ return values
263
+
264
+ connector = dict(connector)
265
+ params = dict(connector.get("parameters") or {})
266
+ data = dict(values.get("data") or {})
267
+
268
+ conflicts = [
269
+ k for k in DATA_FIELD_KEYS if k in data and k in params and data[k] != params[k]
270
+ ]
271
+ if conflicts:
272
+ raise ValueError(
273
+ f"Conflicting values for {conflicts} between the 'data' section and "
274
+ "'connector.parameters'. Declare them once, preferably under 'data'."
275
+ )
276
+
277
+ # connector.parameters -> data (legacy configs)
278
+ for key in DATA_FIELD_KEYS:
279
+ if key not in data and key in params:
280
+ data[key] = params[key]
281
+ # data -> connector.parameters (so connector plugins still find them)
282
+ for key in DATA_FIELD_KEYS:
283
+ if key in data:
284
+ params[key] = data[key]
285
+
286
+ connector["parameters"] = params
287
+ values["connector"] = connector
288
+ values["data"] = data
289
+ return values
290
+
291
+
292
+ def load_config(path: Path) -> AppConfig:
293
+ """
294
+ Load JSON configuration from the given path into nested validated models.
295
+
296
+ :param path: Path to the JSON config file.
297
+ :return: An AppConfig instance populated from the file.
298
+ :raises ValueError: if the config is invalid.
299
+ """
300
+ raw_text = Path(path).read_text(encoding="utf-8")
301
+
302
+ try:
303
+ # Validate directly from JSON and apply aliases (visualization -> viz).
304
+ return AppConfig.model_validate_json(raw_text)
305
+ except ValidationError as exc:
306
+ raise ValueError(f"Invalid config file at {path}:\n{exc}") from exc
307
+ except json.JSONDecodeError as exc:
308
+ raise ValueError(f"Invalid JSON in config file at {path}:\n{exc}") from exc
@@ -0,0 +1,97 @@
1
+ {
2
+ "time_limit": null,
3
+ "data": {
4
+ "tick_field": "timestamp",
5
+ "individual_field": "container_id",
6
+ "host_field": "machine_id",
7
+ "metrics": ["cpu"]
8
+ },
9
+ "clustering": {
10
+ "method": "kmeans",
11
+ "nb_clusters": 3,
12
+ "parameters": {
13
+ "nb_clusters": 3
14
+ }
15
+ },
16
+ "optimization": {
17
+ "backend": "pyomo",
18
+ "parameters": {
19
+ "solver": "glpk",
20
+ "verbose": 0
21
+ }
22
+ },
23
+ "problem": {
24
+ "type": "placement",
25
+ "parameters": {
26
+ "initial_placement": 0,
27
+ "tol": 0.1,
28
+ "tol_move": 0.5
29
+ }
30
+ },
31
+ "connector": {
32
+ "type": "file",
33
+ "parameters": {
34
+ "data_folder": "./tests/data/thesis_ex_10",
35
+ "file_name": "container_usage.csv",
36
+ "sep_time": 3,
37
+ "tick_increment": 2,
38
+ "window_duration" : 3,
39
+ "outfile": "./out/moves.log"
40
+ }
41
+ },
42
+ "logging": {
43
+ "level": "INFO",
44
+ "filename": "./out/hots.log",
45
+ "fmt": "%(asctime)s %(levelname)s: %(message)s"
46
+ },
47
+ "reporting": {
48
+ "results_folder": "./out",
49
+ "metrics_file": "./out/metrics.csv",
50
+ "plots_folder": "./out/plots"
51
+ },
52
+ "visualization": {
53
+ "enabled": false,
54
+ "default_metric": "cpu",
55
+ "save": {
56
+ "enabled": true,
57
+ "plots_folder": "./out/plots",
58
+ "default_format": "png",
59
+ "dpi": 150,
60
+ "bbox_inches": "tight",
61
+ "close_on_save": true
62
+ },
63
+ "colors": {
64
+ "clusters": [
65
+ "blue", "orange", "green", "red", "purple",
66
+ "brown", "pink", "gray", "olive", "cyan",
67
+ "turquoise", "chocolate", "navy", "lightcoral", "violet"
68
+ ],
69
+ "highlight": ["violet", "lightcoral", "navy", "chocolate", "turquoise"]
70
+ },
71
+ "dendrogram": {
72
+ "leaf_rotation": 90.0,
73
+ "leaf_font_size": 8.0
74
+ },
75
+ "graphs": {
76
+ "spring_layout": {
77
+ "k": 0.15,
78
+ "iterations": 20
79
+ },
80
+ "show_edge_weights": true
81
+ },
82
+ "nodes": {
83
+ "capacity_margin_ratio": 0.2,
84
+ "sep_time_color": "red",
85
+ "sep_time_style": "--",
86
+ "capacity_color": "red"
87
+ },
88
+ "live": {
89
+ "pause_seconds": 0.5
90
+ },
91
+ "naming": {
92
+ "prefix": "",
93
+ "suffix": "",
94
+ "slugify": true
95
+ }
96
+ }
97
+ }
@@ -0,0 +1,69 @@
1
+ {
2
+ "time_limit": 600,
3
+ "data": {
4
+ "tick_field": "timestamp",
5
+ "individual_field": "container_id",
6
+ "host_field": "machine_id",
7
+ "metrics": ["cpu"]
8
+ },
9
+ "clustering": {
10
+ "method": "kmeans",
11
+ "nb_clusters": 3,
12
+ "parameters": {
13
+ "nb_clusters": 3
14
+ }
15
+ },
16
+ "optimization": {
17
+ "backend": "pyomo",
18
+ "parameters": {
19
+ "pb_number": 1,
20
+ "solver": "glpk"
21
+ }
22
+ },
23
+ "problem": {
24
+ "type": "placement",
25
+ "parameters": {
26
+ "initial_placement": false,
27
+ "tol": 0.1,
28
+ "tol_move": 0.2
29
+ }
30
+ },
31
+ "connector": {
32
+ "type": "kafka",
33
+ "parameters": {
34
+ "sep_time": 30,
35
+ "_comment_sep_time": "With live Kafka and real Prometheus timestamps (Unix epoch ~1.7e9), any value below 1e9 is satisfied by the very first message — bootstrap always completes on batch 1. Only set this to a meaningful wall-clock value when using the FileConnector.",
36
+ "tick_increment": 10,
37
+ "window_duration": 3,
38
+ "bootstrap.servers": "localhost:9092",
39
+ "topic_data": "hots_data",
40
+ "topic_moves": "hots_moves",
41
+ "consumer_conf": {
42
+ "bootstrap.servers": "localhost:9092",
43
+ "group.id": "hots",
44
+ "auto.offset.reset": "earliest"
45
+ },
46
+ "batch_size": 10,
47
+ "poll_timeout": 1.0,
48
+ "bootstrap_timeout_seconds": 120,
49
+ "node_capacities": {
50
+ "vm1": 2.0,
51
+ "vm2": 2.0,
52
+ "vm3": 2.0
53
+ }
54
+ }
55
+ },
56
+ "logging": {
57
+ "level": "INFO",
58
+ "filename": "./out/hots.log",
59
+ "fmt": "%(asctime)s %(levelname)s: %(message)s"
60
+ },
61
+ "reporting": {
62
+ "results_folder": "./out",
63
+ "metrics_file": "./out/metrics.csv",
64
+ "plots_folder": "./out/plots"
65
+ },
66
+ "visualization": {
67
+ "enabled": false
68
+ }
69
+ }