treebo 0.1.0b1__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.
- treebo/__init__.py +9 -0
- treebo/algorithms/__init__.py +3 -0
- treebo/algorithms/algorithm.py +108 -0
- treebo/algorithms/beam_search.py +302 -0
- treebo/algorithms/bnb.py +88 -0
- treebo/algorithms/lazy_race_tree_search.py +369 -0
- treebo/comparison/__init__.py +4 -0
- treebo/comparison/abstract.py +127 -0
- treebo/comparison/base.py +124 -0
- treebo/comparison/comparison.py +214 -0
- treebo/comparison/mo.py +298 -0
- treebo/comparison/preshuffle.py +162 -0
- treebo/containers/__init__.py +3 -0
- treebo/containers/archive.py +205 -0
- treebo/containers/base.py +173 -0
- treebo/containers/multi_hashed.py +318 -0
- treebo/containers/node_dict.py +380 -0
- treebo/containers/node_list.py +64 -0
- treebo/containers/node_set.py +133 -0
- treebo/node.py +179 -0
- treebo/tree.py +762 -0
- treebo-0.1.0b1.dist-info/METADATA +259 -0
- treebo-0.1.0b1.dist-info/RECORD +26 -0
- treebo-0.1.0b1.dist-info/WHEEL +5 -0
- treebo-0.1.0b1.dist-info/licenses/LICENSE +373 -0
- treebo-0.1.0b1.dist-info/top_level.txt +1 -0
treebo/__init__.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Copyright (c) 2026 Carlos Ortega Absil
|
|
2
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
3
|
+
|
|
4
|
+
from collections import Counter
|
|
5
|
+
from typing import Callable
|
|
6
|
+
from treebo.tree import Tree
|
|
7
|
+
from treebo.containers.base import NodeContainer
|
|
8
|
+
from treebo.containers.node_dict import NodeDict
|
|
9
|
+
from treebo.comparison.abstract import AbstractComparison
|
|
10
|
+
|
|
11
|
+
class Algorithm:
|
|
12
|
+
"""Base class for algorithms that mutate and return a search tree."""
|
|
13
|
+
|
|
14
|
+
def __init__(self,
|
|
15
|
+
nproc: int = 1,
|
|
16
|
+
chunksize: int = None):
|
|
17
|
+
"""Configure optional multiprocessing parameters.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
nproc: Number of worker processes.
|
|
21
|
+
chunksize: Work-item chunk size for multiprocessing iterators.
|
|
22
|
+
"""
|
|
23
|
+
self._callback = None
|
|
24
|
+
self._nproc = nproc
|
|
25
|
+
self._chunksize = chunksize
|
|
26
|
+
|
|
27
|
+
def grow(self, tree: "Tree",
|
|
28
|
+
*args,
|
|
29
|
+
**kwargs) -> "Tree":
|
|
30
|
+
"""
|
|
31
|
+
Grow the tree to a specified depth or until no more nodes are available.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
tree: Tree to mutate.
|
|
35
|
+
*args: Algorithm-specific positional arguments.
|
|
36
|
+
**kwargs: Algorithm-specific keyword arguments.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
The mutated tree.
|
|
40
|
+
|
|
41
|
+
Raises:
|
|
42
|
+
NotImplementedError: Always, in the base class.
|
|
43
|
+
"""
|
|
44
|
+
raise NotImplementedError("The grow method must be implemented in subclasses.")
|
|
45
|
+
|
|
46
|
+
def set_callback(self, callback: Callable = None):
|
|
47
|
+
"""Set a callback invoked after an iteration or search level.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
callback: Callable receiving the tree and iteration or level
|
|
51
|
+
number, or ``None`` to disable callbacks.
|
|
52
|
+
"""
|
|
53
|
+
self._callback = callback
|
|
54
|
+
|
|
55
|
+
## parallelisation helpers
|
|
56
|
+
def _branch_node(n, br:int=None):
|
|
57
|
+
"""Return the children produced by one node.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
n: Node to branch.
|
|
61
|
+
br: Requested branching factor.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
The child nodes returned by ``n.branch(br)``.
|
|
65
|
+
"""
|
|
66
|
+
return n.branch(br)
|
|
67
|
+
|
|
68
|
+
def _parallel_beam_slot(job):
|
|
69
|
+
"""Prune one plain slot in a worker and return it for replacement."""
|
|
70
|
+
key, slot, beam_width = job
|
|
71
|
+
slot.prune(beam_width)
|
|
72
|
+
return key, slot
|
|
73
|
+
|
|
74
|
+
def _slot_to_beam(slot, beam_width:int):
|
|
75
|
+
"""Decide whether to submit one plain slot to beam in a worker."""
|
|
76
|
+
return len(slot) > beam_width
|
|
77
|
+
|
|
78
|
+
def _channel_width(beam_width, channel_key):
|
|
79
|
+
"""Return the beam width of one channel, ``beam_width[None]`` or 0 being the default for unlisted channels."""
|
|
80
|
+
if isinstance(beam_width, dict):
|
|
81
|
+
return beam_width.get(channel_key, beam_width.get(None, 0))
|
|
82
|
+
return beam_width
|
|
83
|
+
|
|
84
|
+
def _slot_channels_to_beam(slot, channel_idx: str, beam_width):
|
|
85
|
+
"""Decide whether any channel of one unchanneled slot holds more nodes than its beam width."""
|
|
86
|
+
if isinstance(beam_width, dict):
|
|
87
|
+
min_width = min(beam_width.values()) if None in beam_width else 0
|
|
88
|
+
else:
|
|
89
|
+
min_width = beam_width
|
|
90
|
+
if len(slot) <= min_width:
|
|
91
|
+
return False
|
|
92
|
+
counts = Counter(node[channel_idx] for node in slot)
|
|
93
|
+
return any(count > _channel_width(beam_width, key) for key, count in counts.items())
|
|
94
|
+
|
|
95
|
+
def _beam_slot_channels(slot, slot_ctor, channel_idx: str, beam_width):
|
|
96
|
+
"""Channel one slot, prune each channel to its beam width and return the slot rebuilt with ``slot_ctor``."""
|
|
97
|
+
channeled = NodeDict(nodes=slot, subclass=slot_ctor, index_key=channel_idx)
|
|
98
|
+
channeled.prune_values(beam_width)
|
|
99
|
+
return slot_ctor(channeled)
|
|
100
|
+
|
|
101
|
+
def _parallel_beam_slot_channels(job):
|
|
102
|
+
"""Channel, prune and unchannel one slot in a worker and return it for replacement."""
|
|
103
|
+
key, slot, slot_ctor, channel_idx, beam_width = job
|
|
104
|
+
return key, _beam_slot_channels(slot, slot_ctor, channel_idx, beam_width)
|
|
105
|
+
|
|
106
|
+
def _init_worker(comparison: AbstractComparison | type[AbstractComparison]):
|
|
107
|
+
"""Initialize a worker process with a comparison object."""
|
|
108
|
+
NodeContainer.set_comparison(comparison)
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
# Copyright (c) 2026 Carlos Ortega Absil
|
|
2
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
3
|
+
|
|
4
|
+
from treebo.algorithms.algorithm import Algorithm, _branch_node, _init_worker
|
|
5
|
+
from itertools import chain
|
|
6
|
+
from functools import partial
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class BeamSearch(Algorithm):
|
|
10
|
+
"""Expand one generation and retain a configured beam.
|
|
11
|
+
|
|
12
|
+
The active level may be archived before or after pruning, depending on
|
|
13
|
+
``archive_branch``. Channeled variants apply the beam independently per
|
|
14
|
+
channel rather than globally.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self,
|
|
18
|
+
br: int = 1,
|
|
19
|
+
be: int = 1,
|
|
20
|
+
archive_levels: bool = False,
|
|
21
|
+
archive_branch: bool = False,
|
|
22
|
+
archive_batchsize: int = None,
|
|
23
|
+
nproc: int = 1,
|
|
24
|
+
chunksize: int = 1):
|
|
25
|
+
"""Configure branching, beam width, archiving, and parallelism.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
br: Branching factor passed to each node.
|
|
29
|
+
be: Maximum number of nodes retained after each level.
|
|
30
|
+
archive_levels: Whether to retain archive contents across levels.
|
|
31
|
+
archive_branch: Whether to archive the generated branch before
|
|
32
|
+
pruning instead of the pruned level.
|
|
33
|
+
archive_batchsize: Size of batches to archive at a time, or ``None`` for no batching, which might imply materialising into a list.
|
|
34
|
+
nproc: Number of worker processes; ``1`` runs serially.
|
|
35
|
+
chunksize: Multiprocessing work-item chunk size.
|
|
36
|
+
"""
|
|
37
|
+
super().__init__(nproc=nproc, chunksize=chunksize)
|
|
38
|
+
self.br = br
|
|
39
|
+
self.be = be
|
|
40
|
+
if archive_branch and not archive_levels:
|
|
41
|
+
raise NotImplementedError("Archiving only the branch without retaining the archive across levels is not yet implemented.")
|
|
42
|
+
self.clear_archive = not archive_levels
|
|
43
|
+
self.archive_branch = archive_branch
|
|
44
|
+
self.archive_batchsize = archive_batchsize
|
|
45
|
+
|
|
46
|
+
def grow(self,
|
|
47
|
+
tree,
|
|
48
|
+
depth=None,
|
|
49
|
+
initial_depth=0):
|
|
50
|
+
"""Grow a tree through successive beam-search levels.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
tree: Tree to mutate.
|
|
54
|
+
depth: Number of levels to grow, or ``None`` until exhausted.
|
|
55
|
+
initial_depth: Starting depth counter for callbacks.
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
The mutated tree.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
dep = initial_depth
|
|
62
|
+
|
|
63
|
+
def growing():
|
|
64
|
+
return bool(tree.nodes) and (depth is None or dep < depth)
|
|
65
|
+
|
|
66
|
+
if self._nproc > 1:
|
|
67
|
+
from multiprocessing import Pool
|
|
68
|
+
with Pool(processes=self._nproc,
|
|
69
|
+
initializer=_init_worker,
|
|
70
|
+
initargs=(tree.comparison,)) as p:
|
|
71
|
+
while growing():
|
|
72
|
+
self._grow_one_depth(tree, pool=p)
|
|
73
|
+
dep += 1
|
|
74
|
+
if self._callback:
|
|
75
|
+
self._callback(tree, dep)
|
|
76
|
+
else:
|
|
77
|
+
while growing():
|
|
78
|
+
self._grow_one_depth(tree, pool=None)
|
|
79
|
+
dep += 1
|
|
80
|
+
if self._callback:
|
|
81
|
+
self._callback(tree, dep)
|
|
82
|
+
return tree
|
|
83
|
+
|
|
84
|
+
def _get_level(self, tree):
|
|
85
|
+
"""Return the current active level of the tree.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
tree: Tree to query.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
The active nodes.
|
|
92
|
+
"""
|
|
93
|
+
# swap active and next-level nodes to avoid copying the entire tree
|
|
94
|
+
level = tree.Nodes()
|
|
95
|
+
tree.nodes, level = level, tree.nodes
|
|
96
|
+
return level, tree
|
|
97
|
+
|
|
98
|
+
def branch(self, tree, pool=None):
|
|
99
|
+
"""Replace active nodes with their children.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
tree: Tree to mutate.
|
|
103
|
+
pool: Optional multiprocessing pool.
|
|
104
|
+
"""
|
|
105
|
+
_branch_func = partial(_branch_node, br=self.br)
|
|
106
|
+
level, tree = self._get_level(tree)
|
|
107
|
+
# branch
|
|
108
|
+
if pool is None or self._chunksize < 1:
|
|
109
|
+
# TODO: or len(tree.nodes) < self._chunksize
|
|
110
|
+
branched = map(_branch_func, level) # setter of the property takes iterable
|
|
111
|
+
else:
|
|
112
|
+
branched = pool.imap_unordered(func=_branch_func,
|
|
113
|
+
iterable=level,
|
|
114
|
+
chunksize=self._chunksize)
|
|
115
|
+
# add or add_and_archive the branched nodes (iterable assumed), by batches if needed
|
|
116
|
+
branched = chain.from_iterable(branched)
|
|
117
|
+
if self.archive_branch:
|
|
118
|
+
tree.add_and_archive_nodes(branched, batchsize=self.archive_batchsize)
|
|
119
|
+
else:
|
|
120
|
+
tree.add_nodes(branched)
|
|
121
|
+
|
|
122
|
+
def _beam(self, tree, pool=None):
|
|
123
|
+
# NB: always prune sequentially
|
|
124
|
+
tree.prune(self.be)
|
|
125
|
+
|
|
126
|
+
def beam(self, tree, pool=None):
|
|
127
|
+
"""Prune the active tree to the configured beam width.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
tree: Tree to mutate.
|
|
131
|
+
pool: Optional multiprocessing pool.
|
|
132
|
+
"""
|
|
133
|
+
self._beam(tree, pool=pool)
|
|
134
|
+
if not self.archive_branch and tree.nodes:
|
|
135
|
+
tree.archive_tree(clear=self.clear_archive, batchsize=self.archive_batchsize) # Likely duplicates in LowMem and LRTS
|
|
136
|
+
|
|
137
|
+
def _grow_one_depth(self, tree, pool=None):
|
|
138
|
+
self.branch(tree, pool=pool)
|
|
139
|
+
self.beam(tree, pool=pool)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class BeamSearchLowMem(BeamSearch):
|
|
143
|
+
"""Beam search variant that branches incrementally to limit memory."""
|
|
144
|
+
def __init__(self,
|
|
145
|
+
br: int = 1,
|
|
146
|
+
be: int = 1,
|
|
147
|
+
be_max: int = 1,
|
|
148
|
+
archive_levels: bool = False,
|
|
149
|
+
archive_branch: bool = False,
|
|
150
|
+
archive_batchsize: int = None,
|
|
151
|
+
nproc: int = 1,
|
|
152
|
+
chunksize: int = 1,
|
|
153
|
+
batchsize: int = None):
|
|
154
|
+
"""Configure low-memory branching and intermediate beam limits.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
br: Branching factor passed to each node.
|
|
158
|
+
be: Maximum number of nodes retained when pruning.
|
|
159
|
+
be_max: Temporary tree size at which intermediate pruning starts.
|
|
160
|
+
archive_levels: Whether to retain archive contents across levels.
|
|
161
|
+
archive_branch: Whether to archive before intermediate pruning.
|
|
162
|
+
archive_batchsize: Size of batches to archive at a time, or ``None`` for no batching, which might imply materialising into a list.
|
|
163
|
+
nproc: Number of worker processes; ``1`` runs serially.
|
|
164
|
+
chunksize: Multiprocessing work-item chunk size.
|
|
165
|
+
batchsize: Nodes expanded per multiprocessing batch, or ``None``
|
|
166
|
+
to derive it from ``nproc`` and ``chunksize``.
|
|
167
|
+
"""
|
|
168
|
+
super().__init__(br=br,
|
|
169
|
+
be=be,
|
|
170
|
+
archive_levels=archive_levels,
|
|
171
|
+
archive_branch=archive_branch,
|
|
172
|
+
archive_batchsize=archive_batchsize,
|
|
173
|
+
nproc=nproc,
|
|
174
|
+
chunksize=chunksize)
|
|
175
|
+
self.be_max = be_max
|
|
176
|
+
self._batchsize = batchsize if batchsize is not None else nproc * (chunksize or 1)
|
|
177
|
+
if self._batchsize < 1:
|
|
178
|
+
raise ValueError("Batch size must be positive, got {}".format(self._batchsize))
|
|
179
|
+
|
|
180
|
+
def branch(self, tree, pool=None):
|
|
181
|
+
"""Expand nodes incrementally while applying intermediate pruning.
|
|
182
|
+
|
|
183
|
+
Args:
|
|
184
|
+
tree: Tree to mutate.
|
|
185
|
+
pool: Optional multiprocessing pool.
|
|
186
|
+
"""
|
|
187
|
+
_branch_func = partial(_branch_node, br=self.br)
|
|
188
|
+
level, tree = self._get_level(tree)
|
|
189
|
+
while level:
|
|
190
|
+
batch = [level.pop() for _ in range(min(len(level), self._batchsize))]
|
|
191
|
+
# branch a batch of nodes, potentially in parallel
|
|
192
|
+
if pool is None or self._chunksize < 1 or len(batch) <= self._chunksize:
|
|
193
|
+
branched = map(_branch_func, batch)
|
|
194
|
+
else:
|
|
195
|
+
branched = pool.imap_unordered(func=_branch_func,
|
|
196
|
+
iterable=batch,
|
|
197
|
+
chunksize=self._chunksize)
|
|
198
|
+
branched = chain.from_iterable(branched)
|
|
199
|
+
# add or add_and_archive the branched nodes (iterable assumed), by batches if needed
|
|
200
|
+
if self.archive_branch:
|
|
201
|
+
tree.add_and_archive_nodes(branched, batchsize=self.archive_batchsize)
|
|
202
|
+
else:
|
|
203
|
+
tree.add_nodes(branched)
|
|
204
|
+
|
|
205
|
+
# prune only if the tree is too large
|
|
206
|
+
if len(tree.nodes) > self.be_max:
|
|
207
|
+
self._beam(tree, pool=None)
|
|
208
|
+
|
|
209
|
+
class ChanneledBeamMixin:
|
|
210
|
+
"""Mixin that beams independently within temporary channels."""
|
|
211
|
+
def __init__(self,
|
|
212
|
+
channel_idx: str = "channel",
|
|
213
|
+
**kwargs):
|
|
214
|
+
"""Configure the field used for temporary channeling.
|
|
215
|
+
|
|
216
|
+
Args:
|
|
217
|
+
channel_idx: Node field used as the channel key.
|
|
218
|
+
**kwargs: Arguments forwarded to the concrete search class.
|
|
219
|
+
"""
|
|
220
|
+
super().__init__(**kwargs)
|
|
221
|
+
self.channel_idx = channel_idx
|
|
222
|
+
|
|
223
|
+
def _beam(self, tree, pool=None):
|
|
224
|
+
# NB: channeling is only done before beaming to avoid interference with hash-indexed buckets.
|
|
225
|
+
tree.channel(channel_idx=self.channel_idx)
|
|
226
|
+
super()._beam(tree, pool=pool)
|
|
227
|
+
tree.unchannel()
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class ChanneledBeamSearch(ChanneledBeamMixin, BeamSearch):
|
|
231
|
+
"""Beam search with per-channel beam widths."""
|
|
232
|
+
def __init__(self,
|
|
233
|
+
br: int|dict[str, int] = 1,
|
|
234
|
+
be: int|dict[str, int] = 1,
|
|
235
|
+
channel_idx: str = "channel",
|
|
236
|
+
archive_levels: bool = False,
|
|
237
|
+
archive_branch: bool = False,
|
|
238
|
+
archive_batchsize: int = None,
|
|
239
|
+
nproc: int = 1,
|
|
240
|
+
chunksize: int = 1):
|
|
241
|
+
"""Configure channel-local beam search.
|
|
242
|
+
|
|
243
|
+
Args:
|
|
244
|
+
br: Branching factor passed to each node.
|
|
245
|
+
be: Maximum nodes retained per channel.
|
|
246
|
+
channel_idx: Node field used as the channel key.
|
|
247
|
+
archive_levels: Whether to retain archive contents across levels.
|
|
248
|
+
archive_branch: Whether to archive before channel pruning.
|
|
249
|
+
archive_batchsize: Size of batches to archive at a time, or ``None`` for no batching, which might imply materialising into a list.
|
|
250
|
+
nproc: Number of worker processes.
|
|
251
|
+
chunksize: Multiprocessing work-item chunk size.
|
|
252
|
+
"""
|
|
253
|
+
super().__init__(br=br,
|
|
254
|
+
be=be,
|
|
255
|
+
channel_idx=channel_idx,
|
|
256
|
+
archive_levels=archive_levels,
|
|
257
|
+
archive_branch=archive_branch,
|
|
258
|
+
archive_batchsize=archive_batchsize,
|
|
259
|
+
nproc=nproc,
|
|
260
|
+
chunksize=chunksize)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class ChanneledBeamSearchLowMem(ChanneledBeamMixin, BeamSearchLowMem):
|
|
264
|
+
"""Low-memory beam search with per-channel pruning."""
|
|
265
|
+
def __init__(self,
|
|
266
|
+
br: int|dict[str, int] = 1,
|
|
267
|
+
be: int|dict[str, int] = 1,
|
|
268
|
+
be_max: int = 1,
|
|
269
|
+
channel_idx: str = "channel",
|
|
270
|
+
archive_levels: bool = False,
|
|
271
|
+
archive_branch: bool = False,
|
|
272
|
+
archive_batchsize: int = None,
|
|
273
|
+
nproc: int = 1,
|
|
274
|
+
chunksize: int = 1,
|
|
275
|
+
batchsize: int = None):
|
|
276
|
+
"""Configure low-memory channel-local beam search.
|
|
277
|
+
|
|
278
|
+
Args:
|
|
279
|
+
br: Branching factor passed to each node.
|
|
280
|
+
be: Maximum nodes retained per channel.
|
|
281
|
+
be_max: Temporary tree size at which intermediate pruning starts.
|
|
282
|
+
channel_idx: Node field used as the channel key.
|
|
283
|
+
archive_levels: Whether to retain archive contents across levels.
|
|
284
|
+
archive_branch: Whether to archive before channel pruning.
|
|
285
|
+
archive_batchsize: Size of batches to archive at a time, or ``None`` for no batching, which might imply materialising into a list.
|
|
286
|
+
nproc: Number of worker processes.
|
|
287
|
+
chunksize: Multiprocessing work-item chunk size.
|
|
288
|
+
batchsize: Nodes expanded per multiprocessing batch, or ``None``
|
|
289
|
+
to derive it automatically.
|
|
290
|
+
"""
|
|
291
|
+
super().__init__(br=br,
|
|
292
|
+
be=be,
|
|
293
|
+
be_max=be_max,
|
|
294
|
+
channel_idx=channel_idx,
|
|
295
|
+
archive_levels=archive_levels,
|
|
296
|
+
archive_branch=archive_branch,
|
|
297
|
+
archive_batchsize=archive_batchsize,
|
|
298
|
+
nproc=nproc,
|
|
299
|
+
chunksize=chunksize,
|
|
300
|
+
batchsize=batchsize)
|
|
301
|
+
if isinstance(be_max, dict):
|
|
302
|
+
raise NotImplementedError("Different be_max per channel not implemented for efficiency reasons.")
|
treebo/algorithms/bnb.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Copyright (c) 2026 Carlos Ortega Absil
|
|
2
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
3
|
+
|
|
4
|
+
from treebo.algorithms.algorithm import Algorithm
|
|
5
|
+
from itertools import chain
|
|
6
|
+
|
|
7
|
+
class BnB(Algorithm):
|
|
8
|
+
"""Branch-and-bound search algorithm."""
|
|
9
|
+
|
|
10
|
+
def __init__(self,
|
|
11
|
+
iter_key=None, # key on which to sort the tree prior to popping the current node (or batch). None for fitness.
|
|
12
|
+
heuristic_key=None, # ibidem, applying only while tree.archive.best is None. Default equals to iter_key.
|
|
13
|
+
br=None, # when it applies, the branching factor
|
|
14
|
+
batchsize=1, # can branch in batches for efficiency
|
|
15
|
+
nproc=1):
|
|
16
|
+
"""Configure branch-and-bound ordering and expansion.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
iter_key: Node field used to select nodes for expansion.
|
|
20
|
+
heuristic_key: Temporary ordering field while no archive best
|
|
21
|
+
node exists.
|
|
22
|
+
br: Branching factor passed to nodes.
|
|
23
|
+
batchsize: Number of nodes expanded per iteration.
|
|
24
|
+
nproc: Number of worker processes reserved by the base class.
|
|
25
|
+
"""
|
|
26
|
+
super().__init__(nproc)
|
|
27
|
+
self.br = br
|
|
28
|
+
self.batchsize = batchsize
|
|
29
|
+
self.__iter_key = iter_key
|
|
30
|
+
self.__heuristic_key = heuristic_key
|
|
31
|
+
|
|
32
|
+
def iter_key(self, tree):
|
|
33
|
+
"""Return the active node-ordering field.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
tree: Tree whose archive state determines the ordering mode.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
The field used to select the next nodes.
|
|
40
|
+
"""
|
|
41
|
+
if self.__heuristic_key is not None:
|
|
42
|
+
if tree.archive.best is None:
|
|
43
|
+
return self.__heuristic_key
|
|
44
|
+
return self.__iter_key
|
|
45
|
+
|
|
46
|
+
def grow(self,
|
|
47
|
+
tree,
|
|
48
|
+
max_iters=None):
|
|
49
|
+
"""Expand a tree until exhausted or a limit is reached.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
tree: Tree to mutate.
|
|
53
|
+
max_iters: Maximum number of iterations, or ``None`` for no
|
|
54
|
+
explicit limit.
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
The mutated tree.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
iters = 0
|
|
61
|
+
def growing():
|
|
62
|
+
# todo: custom stopping criterion
|
|
63
|
+
return bool(tree.nodes) and (max_iters is None or iters < max_iters)
|
|
64
|
+
|
|
65
|
+
while growing():
|
|
66
|
+
self._grow_one_iter(tree)
|
|
67
|
+
iters += 1
|
|
68
|
+
if self._callback:
|
|
69
|
+
self._callback(tree, iters)
|
|
70
|
+
return tree
|
|
71
|
+
|
|
72
|
+
def _grow_one_iter(self, tree):
|
|
73
|
+
"""Expand one batch and add its non-sterile children.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
tree: Tree to mutate.
|
|
77
|
+
"""
|
|
78
|
+
batch = tree.pop_best(key=self.iter_key(tree),
|
|
79
|
+
n=self.batchsize)
|
|
80
|
+
batch.reverse()
|
|
81
|
+
children = []
|
|
82
|
+
while batch:
|
|
83
|
+
curr = batch.pop()
|
|
84
|
+
children.extend(curr.branch_and_bound(tree, br=self.br))
|
|
85
|
+
# we assume it is more efficient to archive first the branch
|
|
86
|
+
tree.archive_nodes(children)
|
|
87
|
+
# and then append the non-sterile nodes, but this might not be the case
|
|
88
|
+
tree.add_nodes([child for child in children if not child.sterile])
|