API Reference¶
tsam_xarray
¶
tsam_xarray: Lightweight xarray wrapper for tsam time series aggregation.
ClusteringInfo
module-attribute
¶
Backwards-compatible alias for :class:ClusteringResult.
ClusteringResult
dataclass
¶
Reusable clustering result with xarray dimension metadata.
Wraps one or more tsam ClusteringResult objects alongside
the dimension names needed to apply the clustering to new data.
Exposes clustering metadata as cached xarray DataArrays.
Attributes:
| Name | Type | Description |
|---|---|---|
time_dim |
str
|
Name of the time dimension. |
cluster_dim |
list[str]
|
Dimension(s) clustered together. |
slice_dims |
list[str]
|
Dimension(s) aggregated independently. |
clusterings |
dict[tuple[Hashable, ...], ClusteringResult]
|
Per-slice tsam clustering.
Single entry |
n_clusters |
int
|
Number of clusters. |
n_original_periods |
int
|
Number of original periods. |
n_timesteps_per_period |
int
|
Timesteps per period. |
n_segments |
int | None
|
Segments per period, or |
cluster_assignments |
DataArray
|
Cluster ID per period.
Dims: |
cluster_occurrences |
DataArray
|
Periods per cluster.
Dims: |
cluster_centers |
DataArray
|
Representative period per cluster.
Dims: |
segment_durations |
DataArray | None
|
Duration per segment, or |
segment_assignments |
DataArray | None
|
Segment ID per timestep, or
|
segment_centers |
DataArray | None
|
Representative timestep per segment,
or |
Source code in src/tsam_xarray/_clustering.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | |
n_timesteps_per_period
property
¶
Number of timesteps per period (e.g., 24 for hourly with daily periods).
n_segments
property
¶
Number of segments per period, or None if no segmentation.
cluster_assignments
property
¶
Cluster assignment for each period, as DataArray.
Dims: (period, *slice_dims).
cluster_occurrences
property
¶
Number of periods assigned to each cluster.
Dims: (cluster, *slice_dims).
segment_durations
property
¶
Duration of each segment per cluster, or None if no segmentation.
Dims: (cluster, timestep, *slice_dims).
cluster_centers
property
¶
Representative period index for each cluster.
Dims: (cluster, *slice_dims).
segment_assignments
property
¶
Segment assignment for each timestep per cluster, or None.
Dims: (cluster, timestep, *slice_dims).
segment_centers
property
¶
Representative timestep index for each segment per cluster, or None.
Dims: (cluster, segment, *slice_dims).
apply
¶
apply(
da: DataArray,
*,
time_dim: str | None = None,
cluster_dim: Sequence[str] | str | None = None,
**tsam_kwargs: Any,
) -> Any
Apply this clustering to new data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
New data with compatible time dimension length. |
required |
time_dim
|
str | None
|
Time dimension name. Defaults to the stored value. |
None
|
cluster_dim
|
Sequence[str] | str | None
|
Cluster dimension(s). Defaults to the stored value. Can differ from the original if the new data has different dimension names. |
None
|
**tsam_kwargs
|
Any
|
Additional keyword arguments passed
to |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Aggregation result using the stored clustering. |
Source code in src/tsam_xarray/_clustering.py
disaggregate
¶
Map data on (cluster, timestep) back to original time.
This is the inverse of aggregate(). Use it to expand
data computed on the compact cluster-representative grid
(e.g., optimization results) back to the full time axis.
Unlike AggregationResult.disaggregate(), this method
works on a ClusteringInfo loaded from JSON — no
original data needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataArray
|
Data with |
required |
Returns:
| Type | Description |
|---|---|
DataArray
|
Data with |
DataArray
|
the original |
Source code in src/tsam_xarray/_clustering.py
to_dict
¶
Serialize clustering to a dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Plain dict suitable for |
dict[str, Any]
|
storage in databases, APIs, etc. |
Source code in src/tsam_xarray/_clustering.py
to_json
¶
Save clustering to JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. |
required |
**json_kwargs
|
Any
|
Additional keyword arguments passed
to |
{}
|
Source code in src/tsam_xarray/_clustering.py
from_dict
classmethod
¶
Load clustering from a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dict as returned by :meth: |
required |
Returns:
| Type | Description |
|---|---|
ClusteringResult
|
The loaded |
Source code in src/tsam_xarray/_clustering.py
from_json
classmethod
¶
Load clustering from JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Input file path. |
required |
Returns:
| Type | Description |
|---|---|
ClusteringResult
|
The loaded |
Source code in src/tsam_xarray/_clustering.py
AccuracyMetrics
dataclass
¶
Accuracy metrics from time series aggregation.
Attributes:
| Name | Type | Description |
|---|---|---|
rmse |
DataArray
|
Per-column RMSE.
Dims: |
mae |
DataArray
|
Per-column MAE.
Dims: |
rmse_duration |
DataArray
|
Per-column duration-curve RMSE.
Dims: |
weighted_rmse |
DataArray
|
RMSE weighted across columns.
Dims: |
weighted_mae |
DataArray
|
MAE weighted across columns.
Dims: |
weighted_rmse_duration |
DataArray
|
Duration-curve RMSE weighted
across columns.
Dims: |
Source code in src/tsam_xarray/_result.py
AggregationResult
dataclass
¶
Result of tsam_xarray.aggregate().
Attributes:
| Name | Type | Description |
|---|---|---|
cluster_representatives |
DataArray
|
Typical periods.
Dims: |
cluster_assignments |
DataArray
|
Which cluster each period
belongs to. Dims: |
cluster_weights |
DataArray
|
Periods per cluster.
Dims: |
segment_durations |
DataArray | None
|
Duration of each segment, or
|
accuracy |
AccuracyMetrics
|
Per-column and weighted accuracy metrics. |
reconstructed |
DataArray
|
Reconstructed time series (same shape as input). |
original |
DataArray
|
The input data. |
clustering |
ClusteringResult
|
Reusable clustering metadata.
See |
is_transferred |
bool
|
Whether this result came from
|
Source code in src/tsam_xarray/_result.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | |
n_timesteps_per_period
property
¶
Number of timesteps per cluster representative.
n_segments
property
¶
Number of segments per period, if segmentation was used.
disaggregate
¶
Map data on (cluster, timestep) back to original time.
This is the inverse of aggregate(). Use it to expand
external data computed on the compact cluster-representative
grid (e.g., optimization results) back to the full time
axis.
Without segmentation, values are repeated for each timestep
in the period. With segmentation, values are placed at
segment boundaries and remaining timesteps are NaN — use
.ffill(dim="time"),
.interpolate_na(dim="time"), etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataArray
|
Data with |
required |
Returns:
| Type | Description |
|---|---|
DataArray
|
Data with |
DataArray
|
the original |
Source code in src/tsam_xarray/_result.py
TuningResult
dataclass
¶
Result of hyperparameter tuning.
Attributes:
| Name | Type | Description |
|---|---|---|
n_clusters |
int
|
Optimal number of typical periods. |
n_segments |
int
|
Optimal number of segments per period. |
rmse |
float
|
RMSE of the optimal configuration. |
best_result |
AggregationResult
|
The AggregationResult for the optimal configuration. |
history |
list[dict[str, Any]]
|
History of all tested configurations with their RMSE values. |
all_results |
list[AggregationResult]
|
All AggregationResults from tuning
(when |
Source code in src/tsam_xarray/_tuning.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
summary_matrix
property
¶
Metrics as Dataset with (n_clusters, n_segments) dims.
Contains rmse and timesteps as variables.
NaN where a combination was not tested.
reconstructed
property
¶
Reconstructed time series for each tested config.
Lazy and cached. Returns an xarray DataArray with the
original dimensions plus (n_clusters, n_segments).
NaN where a combination was not tested.
Requires save_all_results=True.
accuracy
property
¶
Per-column accuracy metrics for each tested config.
Lazy and cached. Returns an xarray Dataset with variables
rmse, mae, and rmse_duration, each with the
cluster dimensions plus (n_clusters, n_segments).
NaN where a combination was not tested.
Requires save_all_results=True.
find_by_timesteps
¶
Find the result closest to a target timestep count.
Requires save_all_results=True.
Source code in src/tsam_xarray/_tuning.py
find_by_rmse
¶
Find the smallest configuration that achieves a target RMSE.
Returns the configuration with the fewest timesteps whose RMSE
is at or below threshold.
Requires save_all_results=True.
Source code in src/tsam_xarray/_tuning.py
plot
¶
Plot RMSE vs timesteps.
Requires plotly (pip install plotly).
Source code in src/tsam_xarray/_tuning.py
aggregate
¶
aggregate(
da: DataArray,
*,
time_dim: str,
cluster_dim: Sequence[str] | str,
n_clusters: int,
weights: Weights = None,
**tsam_kwargs: Any,
) -> AggregationResult
Aggregate an xarray DataArray using tsam.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input data with a time dimension and optional extra dimensions. |
required |
time_dim
|
str
|
Name of the time dimension. |
required |
cluster_dim
|
Sequence[str] | str
|
Dimension(s) to cluster together.
Multiple dims are stacked internally into a
MultiIndex and unstacked in results. All remaining
dims are sliced independently. Empty |
required |
n_clusters
|
int
|
Number of cluster representatives. |
required |
weights
|
Weights
|
Per-coordinate weights for clustering. Missing entries default to 1.0. Two formats:
Weights are multiplied across dimensions,
e.g. |
None
|
**tsam_kwargs
|
Any
|
Additional keyword arguments passed to
|
{}
|
Source code in src/tsam_xarray/_core.py
find_best_combination
¶
Deprecated alias for :func:grid_search.
Source code in src/tsam_xarray/_tuning.py
find_optimal_combination
¶
find_optimal_combination(
da: Any,
*,
time_dim: str,
cluster_dim: Sequence[str] | str,
data_reduction: float,
weights: Weights = None,
period_duration: int | float | str = 24,
show_progress: bool = True,
save_all_results: bool = True,
**tsam_kwargs: Any,
) -> TuningResult
Find optimal n_clusters/n_segments for a target data reduction.
Tests all (n_clusters, n_segments) combinations that achieve the target data reduction, evaluating each across all slices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
Any
|
Input data. |
required |
time_dim
|
str
|
Name of the time dimension. |
required |
cluster_dim
|
Sequence[str] | str
|
Dimension(s) to cluster together. |
required |
data_reduction
|
float
|
Target data reduction (e.g., 0.01 for 1% of original). |
required |
weights
|
Weights
|
Per-coordinate weights for clustering and RMSE evaluation. |
None
|
period_duration
|
int | float | str
|
Hours per period (default: 24 for daily). |
24
|
show_progress
|
bool
|
Show progress bar (requires tqdm). |
True
|
save_all_results
|
bool
|
Keep all AggregationResults (memory-intensive). |
True
|
**tsam_kwargs
|
Any
|
Additional keyword arguments passed to
|
{}
|
Returns:
| Type | Description |
|---|---|
TuningResult
|
Best combination with lowest overall RMSE. |
Source code in src/tsam_xarray/_tuning.py
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
find_pareto_front
¶
find_pareto_front(
da: Any,
*,
time_dim: str,
cluster_dim: Sequence[str] | str,
max_timesteps: int | None = None,
timesteps: Sequence[int] | None = None,
weights: Weights = None,
period_duration: int | float | str = 24,
show_progress: bool = True,
save_all_results: bool = True,
**tsam_kwargs: Any,
) -> TuningResult
Find Pareto-optimal configs (RMSE vs complexity).
Runs the same grid search as :func:grid_search
but filters the results to the Pareto frontier --
configurations where no other tested combo has both lower
RMSE and fewer timesteps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
Any
|
Input data. |
required |
time_dim
|
str
|
Name of the time dimension. |
required |
cluster_dim
|
Sequence[str] | str
|
Dimension(s) to cluster together. |
required |
max_timesteps
|
int | None
|
Maximum total timesteps to test (n_clusters * n_segments). Defaults to total number of timesteps in the data. |
None
|
timesteps
|
Sequence[int] | None
|
Specific timestep counts to test. Only
combinations where |
None
|
weights
|
Weights
|
Per-coordinate weights for clustering and RMSE evaluation. |
None
|
period_duration
|
int | float | str
|
Hours per period (default: 24). |
24
|
show_progress
|
bool
|
Show progress bar. |
True
|
save_all_results
|
bool
|
Keep all AggregationResults (memory-intensive). |
True
|
**tsam_kwargs
|
Any
|
Additional keyword arguments passed to
|
{}
|
Returns:
| Type | Description |
|---|---|
TuningResult
|
Pareto-optimal result with lowest RMSE on the |
TuningResult
|
frontier. |
Source code in src/tsam_xarray/_tuning.py
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 | |
grid_search
¶
grid_search(
da: Any,
*,
time_dim: str,
cluster_dim: Sequence[str] | str,
max_timesteps: int | None = None,
timesteps: Sequence[int] | None = None,
weights: Weights = None,
period_duration: int | float | str = 24,
show_progress: bool = True,
save_all_results: bool = True,
**tsam_kwargs: Any,
) -> TuningResult
Full grid search for best (n_clusters, n_segments).
Tests all valid (n_clusters, n_segments) pairs up to
max_timesteps and returns the one with the lowest overall
RMSE. The complete unfiltered history is preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
Any
|
Input data. |
required |
time_dim
|
str
|
Name of the time dimension. |
required |
cluster_dim
|
Sequence[str] | str
|
Dimension(s) to cluster together. |
required |
max_timesteps
|
int | None
|
Maximum total timesteps to test (n_clusters * n_segments). Defaults to total number of timesteps in the data. |
None
|
timesteps
|
Sequence[int] | None
|
Specific timestep counts to test. Only
combinations where |
None
|
weights
|
Weights
|
Per-coordinate weights for clustering and RMSE evaluation. |
None
|
period_duration
|
int | float | str
|
Hours per period (default: 24). |
24
|
show_progress
|
bool
|
Show progress bar. |
True
|
save_all_results
|
bool
|
Keep all AggregationResults (memory-intensive). |
True
|
**tsam_kwargs
|
Any
|
Additional keyword arguments passed to
|
{}
|
Returns:
| Type | Description |
|---|---|
TuningResult
|
Best combination with lowest overall RMSE and full |
TuningResult
|
history. |
Source code in src/tsam_xarray/_tuning.py
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 | |