tsam.api¶
tsam.api
¶
New simplified API for tsam aggregation.
aggregate
¶
aggregate(
data: DataFrame,
n_clusters: int,
*,
period_duration: int | float | str = 24,
temporal_resolution: float | str | None = None,
cluster: ClusterConfig | None = None,
segments: SegmentConfig | None = None,
extremes: ExtremeConfig | None = None,
weights: dict[str, float] | None = None,
preserve_column_means: bool = True,
rescale_exclude_columns: list[str] | None = None,
round_decimals: int | None = None,
numerical_tolerance: float = 1e-13,
) -> AggregationResult
Aggregate time series data into typical periods.
This function reduces a time series dataset to a smaller set of representative "typical periods" using clustering algorithms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input time series data with a datetime index. Each column represents a different variable (e.g., solar, wind, demand). The index should be a DatetimeIndex with regular intervals. |
required |
n_clusters
|
int
|
Number of clusters (typical periods) to create. Higher values = more accuracy but less data reduction. Typical range: 4-20 for energy system models. |
required |
period_duration
|
int, float, or str
|
Length of each period. Accepts: - int/float: hours (e.g., 24 for daily, 168 for weekly) - str: pandas Timedelta string (e.g., '24h', '1d', '1w') |
24
|
temporal_resolution
|
float or str
|
Time resolution of input data. Accepts: - float: hours (e.g., 1.0 for hourly, 0.25 for 15-minute) - str: pandas Timedelta string (e.g., '1h', '15min', '30min') If not provided, inferred from the datetime index. |
None
|
cluster
|
ClusterConfig
|
Clustering configuration. If not provided, uses defaults: - method: "hierarchical" - representation: "medoid" |
None
|
segments
|
SegmentConfig
|
Segmentation configuration for reducing temporal resolution within periods. If not provided, no segmentation is applied. |
None
|
extremes
|
ExtremeConfig
|
Configuration for preserving extreme periods. If not provided, no extreme period handling is applied. |
None
|
weights
|
dict[str, float]
|
Per-column weights that influence all pipeline stages (clustering, segmentation, representation, rescaling). Higher weight = more influence on distance calculations. Example: {"demand": 2.0, "solar": 1.0} |
None
|
preserve_column_means
|
bool
|
Rescale typical periods so each column's weighted mean matches the original data's mean. Ensures total energy/load is preserved when weights represent occurrence counts. |
True
|
rescale_exclude_columns
|
list[str]
|
Column names to exclude from rescaling when preserve_column_means=True. Useful for binary/indicator columns (0/1 values) that should not be rescaled. If None (default), all columns are rescaled. |
None
|
round_decimals
|
int
|
Round output values to this many decimal places. If not provided, no rounding is applied. |
None
|
numerical_tolerance
|
float
|
Tolerance for numerical precision issues. Controls when warnings are raised for aggregated values exceeding the original time series bounds. Increase this value to silence warnings caused by floating-point precision errors. |
1e-13
|
Returns:
| Type | Description |
|---|---|
AggregationResult
|
Object containing: - cluster_representatives: DataFrame with aggregated periods - cluster_assignments: Which cluster each original period belongs to - cluster_weights: Occurrence count per cluster - accuracy: RMSE, MAE metrics - Methods: to_dict() |
Raises:
| Type | Description |
|---|---|
ValueError
|
If input data is invalid or parameters are inconsistent. |
TypeError
|
If parameter types are incorrect. |
Examples:
Basic usage with defaults:
>>> import tsam
>>> result = tsam.aggregate(df, n_clusters=8)
>>> typical = result.cluster_representatives
With custom clustering:
>>> from tsam import aggregate, ClusterConfig
>>> result = aggregate(
... df,
... n_clusters=8,
... cluster=ClusterConfig(method="kmeans", representation="mean"),
... )
With segmentation (reduce to 12 timesteps per period):
>>> from tsam import aggregate, SegmentConfig
>>> result = aggregate(
... df,
... n_clusters=8,
... segments=SegmentConfig(n_segments=12),
... )
Preserving peak demand periods:
>>> from tsam import aggregate, ExtremeConfig
>>> result = aggregate(
... df,
... n_clusters=8,
... extremes=ExtremeConfig(max_value=["demand"]),
... )
Transferring assignments to new data:
See Also
ClusterConfig : Clustering algorithm configuration SegmentConfig : Temporal segmentation configuration ExtremeConfig : Extreme period preservation configuration AggregationResult : Result object with all outputs
Source code in src/tsam/api.py
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 | |
unstack_to_periods
¶
Reshape time series data into period structure for visualization.
Transforms a flat time series into a DataFrame with periods as rows and timesteps as a MultiIndex level, suitable for creating heatmaps with plotly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Time series data with datetime index. |
required |
period_duration
|
int, float, or str
|
Length of each period. Accepts: - int/float: hours (e.g., 24 for daily, 168 for weekly) - str: pandas Timedelta string (e.g., '24h', '1d', '1w') |
24
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Reshaped data with shape (n_periods, n_timesteps_per_period) for each column.
Suitable for |
Examples:
>>> import tsam
>>> import plotly.express as px
>>>
>>> # Reshape data for heatmap visualization
>>> unstacked = tsam.unstack_to_periods(df, period_duration=24)
>>>
>>> # Create heatmap with plotly
>>> px.imshow(
... unstacked["Load"].values.T,
... labels={"x": "Day", "y": "Hour", "color": "Load"},
... title="Load Heatmap"
... )