Search Algorithms¶
SearchAlgorithm
¶
Bases: ABC
Base class for all selection search algorithms (Pillar A).
Defines the interface for algorithms that find optimal representative subsets. The algorithm's sole responsibility is to take a problem context and find the best selection of k items based on its internal logic and objective function.
Different workflow types implement this protocol differently: - Generate-and-Test: Generates candidates, evaluates with ObjectiveSet, selects best - Constructive: Builds solution iteratively (e.g., k-means clustering) - Direct Optimization: Formulates and solves as single optimization problem (e.g., MILP)
Examples:
>>> class SimpleExhaustiveSearch(SearchAlgorithm):
... def __init__(self, objective_set: ObjectiveSet, selection_policy: SelectionPolicy, k: int):
... self.objective_set = objective_set
... self.selection_policy = selection_policy
... self.k = k
...
... def find_selection(self, context: ProblemContext) -> RepSetResult:
... # Generate all k-combinations
... from itertools import combinations
... all_combis = list(combinations(context.slicer.slices, self.k))
...
... # Score each combination
... scored_combis = []
... for combi in all_combis:
... scores = self.objective_set.evaluate(context, combi)
... scored_combis.append((combi, scores))
...
... # Select best according to policy
... best_combi, best_scores = self.selection_policy.select(scored_combis)
...
... return RepSetResult(
... selection=best_combi,
... weights={s: 1/self.k for s in best_combi},
... scores=best_scores
... )
...
>>> algorithm = SimpleExhaustiveSearch(objective_set, policy, k=4)
>>> result = algorithm.find_selection(context)
>>> print(result.selection) # e.g., (0, 3, 6, 9) - selected slice IDs
Source code in energy_repset/search_algorithms/search_algorithm.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 | |
find_selection
abstractmethod
¶
find_selection(context: ProblemContext) -> RepSetResult
Find the best subset of k representative periods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
ProblemContext
|
The problem context with df_features populated (feature engineering must be run before calling this method). |
required |
Returns:
| Type | Description |
|---|---|
RepSetResult
|
A RepSetResult containing the selected slice identifiers, their |
RepSetResult
|
representation weights, and objective scores. |
Source code in energy_repset/search_algorithms/search_algorithm.py
53 54 55 56 57 58 59 60 61 62 63 64 65 | |
ObjectiveDrivenSearchAlgorithm
¶
Bases: SearchAlgorithm, ABC
Base class for search algorithms guided by external objective functions.
Provides a common structure for algorithms that rely on a user-defined ObjectiveSet to score candidates and a SelectionPolicy to choose the best. This pattern separates the search strategy from the objective function, enabling flexible algorithm design.
Examples:
>>> from energy_repset.objectives import ObjectiveSet, ObjectiveSpec
>>> from energy_repset.score_components import WassersteinFidelity
>>> from energy_repset.selection_policies import WeightedSumPolicy
>>> objectives = ObjectiveSet({
... 'wasserstein': (1.0, WassersteinFidelity()),
... })
>>> policy = WeightedSumPolicy()
>>> # See ObjectiveDrivenCombinatorialSearchAlgorithm for concrete usage
Source code in energy_repset/search_algorithms/objective_driven.py
17 18 19 20 21 22 23 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 | |
__init__
¶
__init__(objective_set: ObjectiveSet, selection_policy: SelectionPolicy)
Initialize objective-driven search algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_set
|
ObjectiveSet
|
Collection of score components defining quality metrics. |
required |
selection_policy
|
SelectionPolicy
|
Strategy for selecting best combination from scored candidates (e.g., weighted sum, Pareto dominance). |
required |
Source code in energy_repset/search_algorithms/objective_driven.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
ObjectiveDrivenCombinatorialSearchAlgorithm
¶
Bases: ObjectiveDrivenSearchAlgorithm
Generate-and-test search using a combination generator (Workflow Type 1).
Generates candidate combinations using a CombinationGenerator, scores each with the ObjectiveSet, and selects the best according to the SelectionPolicy. This is the canonical implementation of the Generate-and-Test workflow.
Supports exhaustive search (all k-combinations) and constrained generation (e.g., seasonal quotas). Displays progress with tqdm and stores all evaluations in diagnostics for analysis.
Examples:
>>> from energy_repset.objectives import ObjectiveSet, ObjectiveSpec,
>>> from energy_repset.combi_gens import ExhaustiveCombiGen,
>>> from energy_repset.selection_policies import WeightedSumPolicy
>>> from energy_repset.score_components import WassersteinFidelity, CorrelationFidelity
>>> objectives = ObjectiveSet({
... 'wasserstein': (1.0, WassersteinFidelity()),
... 'correlation': (0.5, CorrelationFidelity())
... })
>>> policy = WeightedSumPolicy()
>>> generator = ExhaustiveCombiGen(k=4)
>>> algorithm = ObjectiveDrivenCombinatorialSearchAlgorithm(
... objective_set=objectives,
... selection_policy=policy,
... combination_generator=generator
... )
>>> result = algorithm.find_selection(context, k=4)
>>> print(result.selection) # Best 4-month selection
>>> print(result.diagnostics['evaluations_df']) # All scored combinations
Source code in energy_repset/search_algorithms/objective_driven.py
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 | |
__init__
¶
__init__(objective_set: ObjectiveSet, selection_policy: SelectionPolicy, combination_generator: CombinationGenerator)
Initialize combinatorial search algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective_set
|
ObjectiveSet
|
Collection of score components defining quality metrics. |
required |
selection_policy
|
SelectionPolicy
|
Strategy for selecting the best combination. |
required |
combination_generator
|
CombinationGenerator
|
Defines which combinations to evaluate (e.g., all combinations, seasonal constraints). |
required |
Source code in energy_repset/search_algorithms/objective_driven.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
find_selection
¶
find_selection(context: ProblemContext) -> RepSetResult
Find optimal selection by exhaustively scoring generated combinations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
ProblemContext
|
Problem context with df_features populated. |
required |
Returns:
| Type | Description |
|---|---|
RepSetResult
|
RepSetResult with the winning selection, scores, representatives, |
RepSetResult
|
and diagnostics containing evaluations_df with all scored combinations. |
Source code in energy_repset/search_algorithms/objective_driven.py
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 | |
get_all_scores
¶
get_all_scores() -> DataFrame
Return DataFrame of all evaluated combinations with scores.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: slices, label, score_comp_1, score_comp_2, ... |
Raises:
| Type | Description |
|---|---|
ValueError
|
If find_selection() has not been called yet. |
Source code in energy_repset/search_algorithms/objective_driven.py
147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
HullClusteringSearch
¶
Bases: SearchAlgorithm
Farthest-point greedy hull clustering (Neustroev et al., 2025).
Implements the greedy convex/conic hull clustering algorithm from Neustroev et al. (2025). At each iteration the algorithm selects the data point furthest from the current hull, i.e. the point with maximum projection error onto the hull spanned by the already- selected representatives. The first representative is the point furthest from the dataset mean.
This farthest-point strategy naturally selects extreme/boundary periods first, producing a hull that spans the data well.
The algorithm leaves weights=None in the result so that an external
RepresentationModel (typically BlendedRepresentationModel) can
compute the final soft-assignment weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of representative periods to select. |
required |
hull_type
|
Literal['convex', 'conic']
|
Type of projection constraint. |
'convex'
|
References
G. Neustroev, D. A. Tejada-Arango, G. Morales-Espana, M. M. de Weerdt. "Hull Clustering with Blended Representative Periods for Energy System Optimization Models." arXiv:2508.21641, 2025.
Examples:
Basic usage with blended representation:
>>> from energy_repset.search_algorithms import HullClusteringSearch
>>> from energy_repset.representation import BlendedRepresentationModel
>>> search = HullClusteringSearch(k=4, hull_type='convex')
>>> repr_model = BlendedRepresentationModel(blend_type='convex')
Source code in energy_repset/search_algorithms/hull_clustering.py
15 16 17 18 19 20 21 22 23 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 | |
__init__
¶
__init__(k: int, hull_type: Literal['convex', 'conic'] = 'convex')
Initialize Hull Clustering search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of hull vertices (representative periods) to select. |
required |
hull_type
|
Literal['convex', 'conic']
|
Projection type. |
'convex'
|
Source code in energy_repset/search_algorithms/hull_clustering.py
53 54 55 56 57 58 59 60 61 62 | |
find_selection
¶
find_selection(context: ProblemContext) -> RepSetResult
Find k hull vertices via farthest-point greedy selection.
The algorithm (Algorithm 2 in Neustroev et al.):
- Select the point furthest from the dataset mean.
- For iterations 2..k, compute the projection error (hull distance) for every remaining point and select the one with the maximum error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
ProblemContext
|
Problem context with |
required |
Returns:
| Type | Description |
|---|---|
RepSetResult
|
RepSetResult with the selected hull vertices, |
RepSetResult
|
(to be filled by an external representation model), and the |
RepSetResult
|
final projection error in |
Source code in energy_repset/search_algorithms/hull_clustering.py
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 | |
CTPCSearch
¶
Bases: SearchAlgorithm
Chronological Time-Period Clustering with contiguity constraint.
Implements hierarchical agglomerative clustering where only temporally adjacent periods may merge, producing k contiguous time segments. Based on Pineda & Morales (2018).
The algorithm computes weights as the fraction of time covered by each
segment, so the external representation model is skipped when the result
is used in RepSetExperiment.run().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of contiguous time segments to produce. |
required |
linkage
|
Literal['ward', 'complete', 'average', 'single']
|
Linkage criterion for agglomerative clustering. One of
|
'ward'
|
References
S. Pineda, J. M. Morales. "Chronological Time-Period Clustering for Optimal Capacity Expansion Planning With Storage." IEEE Trans. Power Syst., 33(6), 7162--7170, 2018.
Examples:
Basic usage:
>>> from energy_repset.search_algorithms import CTPCSearch
>>> search = CTPCSearch(k=4, linkage='ward')
>>> result = search.find_selection(feature_context)
>>> result.selection # Tuple of medoid labels
>>> result.weights # Dict mapping labels to time fractions
Source code in energy_repset/search_algorithms/ctpc.py
16 17 18 19 20 21 22 23 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 | |
__init__
¶
__init__(k: int, linkage: Literal['ward', 'complete', 'average', 'single'] = 'ward')
Initialize CTPC search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of contiguous clusters to produce. |
required |
linkage
|
Literal['ward', 'complete', 'average', 'single']
|
Agglomerative linkage criterion. |
'ward'
|
Source code in energy_repset/search_algorithms/ctpc.py
47 48 49 50 51 52 53 54 55 56 57 58 59 | |
find_selection
¶
find_selection(context: ProblemContext) -> RepSetResult
Run contiguity-constrained hierarchical clustering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
ProblemContext
|
Problem context with |
required |
Returns:
| Type | Description |
|---|---|
RepSetResult
|
RepSetResult with medoid (or centroid) labels as the selection, |
RepSetResult
|
pre-computed weights (segment size fractions), and within-cluster |
RepSetResult
|
sum of squares in |
Source code in energy_repset/search_algorithms/ctpc.py
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 | |
SnippetSearch
¶
Bases: SearchAlgorithm
Greedy p-median selection of multi-day representative subsequences.
Implements a greedy approximation of the Snippet algorithm from
Anderson et al. (2024). Selects k sliding-window subsequences of
period_length_days days each, minimizing the total day-level
distance across the full time horizon.
Each candidate subsequence contains period_length_days daily profile
snippets. The distance from any day to a candidate is the minimum
squared Euclidean distance to any of its constituent daily snippets.
The greedy selection picks the candidate with the greatest total cost
reduction at each iteration.
The original paper solves the selection as a MILP; this implementation uses a greedy p-median heuristic which provides a (1 - 1/e) approximation guarantee.
Requires context.slicer.unit == 'day'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of representative subsequences to select. |
required |
period_length_days
|
int
|
Length of each candidate subsequence in days. |
7
|
step_days
|
int
|
Stride between consecutive sliding-window candidates. |
1
|
References
O. Anderson, N. Yu, K. Oikonomou, D. Wu. "On the Selection of Intermediate Length Representative Periods for Capacity Expansion." arXiv:2401.02888, 2024.
Examples:
Basic usage with daily slicing:
>>> from energy_repset.search_algorithms import SnippetSearch
>>> from energy_repset.time_slicer import TimeSlicer
>>> slicer = TimeSlicer(unit='day')
>>> search = SnippetSearch(k=8, period_length_days=7, step_days=1)
Source code in energy_repset/search_algorithms/snippet.py
15 16 17 18 19 20 21 22 23 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 | |
__init__
¶
__init__(k: int, period_length_days: int = 7, step_days: int = 1)
Initialize Snippet search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of representative subsequences to select. |
required |
period_length_days
|
int
|
Number of days in each candidate subsequence. |
7
|
step_days
|
int
|
Stride between consecutive candidate start positions. |
1
|
Source code in energy_repset/search_algorithms/snippet.py
54 55 56 57 58 59 60 61 62 63 64 65 66 | |
find_selection
¶
find_selection(context: ProblemContext) -> RepSetResult
Find k representative subsequences via greedy p-median selection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
ProblemContext
|
Problem context. Must have |
required |
Returns:
| Type | Description |
|---|---|
RepSetResult
|
RepSetResult with selected starting-day labels, pre-computed |
RepSetResult
|
weights (fraction of days assigned), and total distance score. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in energy_repset/search_algorithms/snippet.py
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 | |
KMedoidsSearch
¶
Bases: SearchAlgorithm
K-medoids clustering for representative subset selection.
Wraps sklearn_extra.cluster.KMedoids to partition feature-space
slices into k clusters and select the medoid of each cluster as a
representative period. Weights are computed as the fraction of slices
assigned to each cluster.
This is a constructive (Workflow Type 2) algorithm: it has its own
internal objective and does not require an external ObjectiveSet.
The RepresentationModel is skipped by RepSetExperiment.run()
because weights are pre-computed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of clusters / representative periods. |
required |
metric
|
str
|
Distance metric for k-medoids (default |
'euclidean'
|
method
|
str
|
K-medoids algorithm variant. |
'alternate'
|
init
|
str
|
Initialization method (default |
'k-medoids++'
|
random_state
|
int | None
|
Seed for reproducibility. |
None
|
max_iter
|
int
|
Maximum number of iterations. |
300
|
Examples:
Basic usage:
>>> from energy_repset.search_algorithms import KMedoidsSearch
>>> search = KMedoidsSearch(k=4, random_state=42)
>>> result = search.find_selection(feature_context)
>>> result.selection # Tuple of medoid labels
>>> result.weights # Dict mapping labels to cluster-size fractions
Source code in energy_repset/search_algorithms/clustering.py
15 16 17 18 19 20 21 22 23 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 | |
__init__
¶
__init__(k: int, metric: str = 'euclidean', method: str = 'alternate', init: str = 'k-medoids++', random_state: int | None = None, max_iter: int = 300)
Initialize k-medoids clustering search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of clusters to produce. |
required |
metric
|
str
|
Distance metric passed to |
'euclidean'
|
method
|
str
|
Algorithm variant ( |
'alternate'
|
init
|
str
|
Medoid initialization strategy. |
'k-medoids++'
|
random_state
|
int | None
|
Random seed for reproducibility. |
None
|
max_iter
|
int
|
Maximum iterations for convergence. |
300
|
Source code in energy_repset/search_algorithms/clustering.py
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 | |
find_selection
¶
find_selection(context: ProblemContext) -> RepSetResult
Run k-medoids clustering on the feature space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
ProblemContext
|
Problem context with |
required |
Returns:
| Type | Description |
|---|---|
RepSetResult
|
RepSetResult with medoid labels as the selection, pre-computed |
RepSetResult
|
cluster-size-proportional weights, and WCSS (Within-Cluster Sum |
RepSetResult
|
of Squares) in |
Source code in energy_repset/search_algorithms/clustering.py
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 | |