Skip to main content

subgraphsearch_core/
search.rs

1//! Randomized tabu search for vertex-induced subgraphs with a prescribed edge count.
2//!
3//! This is a faithful port of the original `sub_search.c`. Each *experiment* starts from
4//! a random set of `size` vertices (always including any fixed vertices) and makes up to
5//! `max_moves` *moves*, each swapping one subgraph vertex for one outside vertex, trying to drive
6//! the objective `|e - target|` to zero, where `e` is the number of edges the subgraph induces.
7//!
8//! - Normally a move is chosen at random among the best swaps in a *restricted* neighborhood:
9//!   when the edge count did not change on the last move, only rows for vertices adjacent to
10//!   exactly one of the two vertices just swapped get a full scan; the rest only look at such
11//!   columns.
12//! - The vertices just swapped are *tabu* for [`SearchParams::tabu_tenure`] moves: the vertex just
13//!   added cannot be removed and the vertex just removed cannot be added back. The original
14//!   programs' tenure was 1, a single move; by default it is a tenth of the subgraph size.
15//! - For the first `div_dur` moves of every `div_freq` (and whenever no optimal move is known),
16//!   a uniformly random swap is made instead ("diversification").
17//!
18//! - With [`SearchParams::aspiration`] (the original `asub_search`), an *aspiration criterion*
19//!   lifts the tabu: the swaps involving the two vertices just swapped are also examined after
20//!   each move, and one is taken whenever it would beat the best value so far. With
21//!   [`SearchParams::full_aspiration`], every swap the tabu tenure forbids is examined the same
22//!   way; with tenure 1 the two are the same.
23//!
24//! - With [`SearchParams::connected`], every component of the subgraph beyond the first adds 1 to
25//!   the conflict, so an experiment succeeds only on a connected subgraph that hits the target.
26//!   Moves are still chosen by the target alone: a disconnected subgraph that hits it leaves the
27//!   search on a plateau, which it walks across until it reaches a connected one.
28//!
29//! With [`RngKind::Legacy`] the search consumes random numbers exactly as the C programs do, so
30//! the same seed gives the same experiments, move for move (see [`search_sequential`]).
31
32use rayon::prelude::*;
33use serde::{Deserialize, Serialize};
34
35use crate::Error;
36use crate::graph::{Graph, WeightedGraph, bit};
37use crate::rng::{Randu, RngKind, SearchRng, Xoshiro};
38
39/// Number of "boxes" in the distribution of moves needed by successful experiments.
40pub const NUM_BOXES: usize = 10;
41
42/// A graph the search can run on: [`Graph`] (`sub_search`), where every edge counts 1, or
43/// [`WeightedGraph`] (`wsub_search`), where an edge counts its weight and the target is a total
44/// weight. The search is compiled separately for each, so the unweighted case pays nothing for
45/// weights.
46pub trait SearchGraph: Sync {
47    /// A row of the adjacency (or weight) matrix.
48    type Row<'a>: AdjacencyRow
49    where
50        Self: 'a;
51
52    fn num_vertices(&self) -> usize;
53    /// Neighbors of `u`, ascending.
54    fn neighbors(&self, u: usize) -> &[u32];
55    fn adjacency_row(&self, u: usize) -> Self::Row<'_>;
56    /// What the edge `{u, v}` contributes to the subgraph's value: its weight, or 0 or 1.
57    fn edge_value(&self, u: usize, v: usize) -> i64;
58    /// The graph as an unweighted [`Graph`], if it is one (regular searches need one).
59    fn as_graph(&self) -> Option<&Graph> {
60        None
61    }
62    /// [`SearchGraph::edge_value`] for a known neighbor `v` of `u`.
63    fn neighbor_value(&self, u: usize, v: usize) -> i64 {
64        self.edge_value(u, v)
65    }
66    /// The initial "best value so far" of an experiment: the sum of the degrees in
67    /// `sub_search`, the total weight in `wsub_search`.
68    fn objective_bound(&self) -> i64;
69    /// An upper bound on [`AdjacencyRow::value`] in `u`'s row: 1 in an unweighted graph, the
70    /// largest weight at `u` in a weighted one. The search uses it to skip rows that cannot hold a
71    /// best move; the default, a bound too large to skip any, is always correct.
72    fn max_row_value(&self, _u: usize) -> i64 {
73        NO_ROW_BOUND
74    }
75}
76
77/// [`SearchGraph::max_row_value`]'s default: large enough to bound any row, small enough that the
78/// search's arithmetic with it cannot overflow.
79const NO_ROW_BOUND: i64 = i64::MAX / 4;
80
81/// In tests, makes every row's bound 0 and turns off the buckets, so the search scans every
82/// column of every row, as a reference.
83#[cfg(test)]
84static NO_ROW_SKIPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
85
86/// Constant-time access to one row of an adjacency or weight matrix.
87pub trait AdjacencyRow: Copy {
88    fn value(self, v: usize) -> i64;
89}
90
91impl AdjacencyRow for &[u64] {
92    #[inline(always)]
93    fn value(self, v: usize) -> i64 {
94        bit(self, v) as i64
95    }
96}
97
98impl AdjacencyRow for &[u8] {
99    #[inline(always)]
100    fn value(self, v: usize) -> i64 {
101        i64::from(self[v])
102    }
103}
104
105impl SearchGraph for Graph {
106    type Row<'a> = &'a [u64];
107
108    fn num_vertices(&self) -> usize {
109        Graph::num_vertices(self)
110    }
111    fn neighbors(&self, u: usize) -> &[u32] {
112        Graph::neighbors(self, u)
113    }
114    fn adjacency_row(&self, u: usize) -> &[u64] {
115        self.row(u)
116    }
117    fn edge_value(&self, u: usize, v: usize) -> i64 {
118        i64::from(self.has_edge(u, v))
119    }
120    #[inline(always)]
121    fn neighbor_value(&self, _u: usize, _v: usize) -> i64 {
122        1
123    }
124    fn objective_bound(&self) -> i64 {
125        2 * self.num_edges() as i64
126    }
127    #[inline(always)]
128    fn max_row_value(&self, _u: usize) -> i64 {
129        1
130    }
131    fn as_graph(&self) -> Option<&Graph> {
132        Some(self)
133    }
134}
135
136impl SearchGraph for WeightedGraph {
137    type Row<'a> = &'a [u8];
138
139    fn num_vertices(&self) -> usize {
140        WeightedGraph::num_vertices(self)
141    }
142    fn neighbors(&self, u: usize) -> &[u32] {
143        WeightedGraph::neighbors(self, u)
144    }
145    fn adjacency_row(&self, u: usize) -> &[u8] {
146        self.row(u)
147    }
148    fn edge_value(&self, u: usize, v: usize) -> i64 {
149        i64::from(self.weight(u, v))
150    }
151    fn objective_bound(&self) -> i64 {
152        self.total_weight() as i64
153    }
154    #[inline(always)]
155    fn max_row_value(&self, u: usize) -> i64 {
156        i64::from(self.max_weight_at(u))
157    }
158}
159
160/// Search parameters. See the module documentation for what they mean.
161#[derive(Clone, Debug, Serialize, Deserialize)]
162pub struct SearchParams {
163    /// Number of subgraph vertices, including fixed ones.
164    pub size: usize,
165    /// Desired number of subgraph edges.
166    pub edges: i64,
167    /// Vertices that must belong to the subgraph.
168    #[serde(default)]
169    pub fixed: Vec<usize>,
170    /// Number of independent experiments.
171    pub experiments: usize,
172    /// Maximum number of moves per experiment.
173    pub max_moves: usize,
174    /// Diversification frequency: a cycle of random moves starts every `div_freq` moves (>= 1).
175    pub div_freq: usize,
176    /// Diversification duration: the number of random moves at the start of each cycle (0 = none).
177    pub div_dur: usize,
178    /// With a positive size `k`, each diversification cycle starts with a *region kick* instead of
179    /// random moves: the `k` free subgraph vertices nearest a random one (in breadth-first order from
180    /// it, at whatever distance) are swapped out, one per move, each for the best vertex to swap in,
181    /// and the vertices removed may not return for `kick_ban` moves. It rebuilds one part of the
182    /// subgraph at a time, as large-neighborhood moves in searches for codes do. The first cycle
183    /// keeps its random moves. [`SearchParams::new`] sets [`DEFAULT_KICK_SIZE`], a safe default;
184    /// larger sizes can help much more on some problems and hurt on others, so compare a few, as
185    /// with `div_dur`. 0 keeps the random moves throughout, and is what
186    /// results saved before kicks existed used. Edge-count and weight searches only: regular and
187    /// path searches ignore it. To reproduce the original programs' runs with
188    /// [`RngKind::Legacy`], set it to 0.
189    #[serde(default)]
190    pub kick_size: usize,
191    /// How many moves a vertex removed by a region kick stays out (see `kick_size`).
192    #[serde(default = "default_kick_ban")]
193    pub kick_ban: usize,
194    /// The *tabu tenure*: for how many moves a vertex just swapped out may not be swapped back in,
195    /// and a vertex just swapped in may not be swapped out. [`AUTO_TABU_TENURE`] (0), which
196    /// [`SearchParams::new`] sets, chooses [`auto_tabu_tenure`] of the subgraph size and the
197    /// number of vertices left outside it, and results record the tenure chosen. 1 is the shortest tenure, the original programs', and what
198    /// results saved before the tenure existed used; to reproduce the original programs' runs with
199    /// [`RngKind::Legacy`], set it to 1. Edge-count and weight searches only: regular and path
200    /// searches ignore it.
201    #[serde(default = "default_tabu_tenure")]
202    pub tabu_tenure: usize,
203    /// Random seed.
204    pub seed: i64,
205    /// Random number generator.
206    pub rng: RngKind,
207    /// Record the objective value after every move (memory: experiments x moves).
208    #[serde(default)]
209    pub record_trace: bool,
210    /// An aspiration criterion, as in the original `asub_search`: after each move, also consider
211    /// the swaps involving the two vertices just swapped (which are otherwise tabu), and take one
212    /// of them whenever it would beat the best value so far.
213    #[serde(default)]
214    pub aspiration: bool,
215    /// The full aspiration criterion: after each move, also consider every swap the tabu tenure
216    /// forbids, not only those involving the two vertices just swapped, and take one of them
217    /// whenever it would beat the best value so far. It lets a long tenure keep the search from
218    /// circling back without blocking improvements, at some cost per move. With a tenure of 1 it is
219    /// the same as `aspiration`, whose code it then uses, so legacy runs are unchanged. Edge-count
220    /// and weight searches only.
221    #[serde(default)]
222    pub full_aspiration: bool,
223    /// Require a connected subgraph: each component beyond the first adds 1 to the conflict. The
224    /// components are counted after every move, at a cost of about the sum of the subgraph's
225    /// degrees in the whole graph.
226    #[serde(default)]
227    pub connected: bool,
228    /// Search for induced paths on `size` vertices instead, with the regular search's moves aimed at
229    /// the degrees of a path (see [`crate::regular`]); the `edges` target is then ignored, and
230    /// `regular` must be `None`. Needs an unweighted [`Graph`].
231    #[serde(default)]
232    pub path: bool,
233    /// With `path`: the two vertices the path must run between, as its two ends. The search adds a
234    /// new vertex adjacent to each, which an induced path can only contain as an end, and fixes all
235    /// four; the results leave the new vertices out (see [`crate::regular`]).
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub endpoints: Option<[usize; 2]>,
238    /// Search for regular induced subgraphs instead (the original `reg_search` and `ereg_search`); the
239    /// `edges` target is then ignored. Needs an unweighted [`Graph`].
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub regular: Option<Regular>,
242}
243
244/// A regular-subgraph search: see [`crate::regular`].
245#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
246pub struct Regular {
247    /// The degree every subgraph vertex should have within the subgraph.
248    pub degree: i64,
249    /// First find the right number of edges, then make the subgraph regular (`ereg_search`).
250    #[serde(default)]
251    pub two_phase: bool,
252}
253
254fn default_kick_ban() -> usize {
255    20
256}
257
258/// The region kick size [`SearchParams::new`] sets: small enough to be a safe default; compare
259/// larger sizes on hard problems.
260pub const DEFAULT_KICK_SIZE: usize = 4;
261
262fn default_tabu_tenure() -> usize {
263    1
264}
265
266/// The `tabu_tenure` that chooses [`auto_tabu_tenure`], and the one [`SearchParams::new`] sets.
267pub const AUTO_TABU_TENURE: usize = 0;
268
269/// The tabu tenure [`AUTO_TABU_TENURE`] chooses for a subgraph of `size` of the graph's `vertices`:
270/// a tenth of the size or an eightieth of the vertices left outside it, whichever is smaller,
271/// at least 1 and at most [`MAX_AUTO_TABU_TENURE`]. The best tenure grows with both, and too long a
272/// tenure hems the search in, so this errs on the short side: small graphs get 1, the original
273/// programs' tenure. Compare others with [`SearchParams::tabu_tenure`].
274pub fn auto_tabu_tenure(size: usize, vertices: usize) -> usize {
275    (size / 10)
276        .min(vertices.saturating_sub(size) / 80)
277        .clamp(1, MAX_AUTO_TABU_TENURE)
278}
279
280/// The longest tenure [`auto_tabu_tenure`] chooses: longer tenures rarely help, and on large
281/// subgraphs of structured graphs they stop the search from finding anything.
282pub const MAX_AUTO_TABU_TENURE: usize = 20;
283
284/// The kick size and tabu tenure a search uses, from those requested (`None` for the default, and
285/// [`AUTO_TABU_TENURE`] for the automatic tenure): the one place that knows which searches take
286/// them. The counting search takes both, by default kicks of [`DEFAULT_KICK_SIZE`] and the
287/// automatic tenure. The degree search (`degree_search`: regular subgraphs, cycles and paths) and
288/// the legacy random number generator (`legacy`) default to no kicks and a tenure of 1, the
289/// original programs'; the degree search accepts no others.
290pub fn search_settings(
291    kick_size: Option<usize>,
292    tabu_tenure: Option<usize>,
293    degree_search: bool,
294    legacy: bool,
295) -> Result<(usize, usize), Error> {
296    let not_for_degree = |what: &str| {
297        Err(Error::Invalid(format!(
298            "{what} for the counting search only, not for regular subgraphs, paths or cycles"
299        )))
300    };
301    let kick_size = match kick_size {
302        Some(k) if k > 0 && degree_search => return not_for_degree("region kicks are"),
303        Some(k) => k,
304        None if degree_search || legacy => 0,
305        None => DEFAULT_KICK_SIZE,
306    };
307    let tabu_tenure = match tabu_tenure {
308        Some(t) if t != 1 && degree_search => {
309            return not_for_degree("a tabu tenure other than 1 is");
310        }
311        Some(t) => t,
312        None if degree_search || legacy => 1,
313        None => AUTO_TABU_TENURE,
314    };
315    Ok((kick_size, tabu_tenure))
316}
317
318impl SearchParams {
319    /// The tabu tenure a search of a graph on `vertices` vertices uses: `tabu_tenure`, or
320    /// [`auto_tabu_tenure`] for [`AUTO_TABU_TENURE`].
321    pub fn resolved_tabu_tenure(&self, vertices: usize) -> usize {
322        if self.tabu_tenure == AUTO_TABU_TENURE {
323            auto_tabu_tenure(self.size, vertices)
324        } else {
325            self.tabu_tenure
326        }
327    }
328}
329
330impl SearchParams {
331    /// Parameters with the given subgraph size and edge count and otherwise reasonable defaults:
332    /// 40 experiments of up to 250 moves (many short runs usually beat a few long ones), 4 random
333    /// moves every 250, region kicks of [`DEFAULT_KICK_SIZE`] from the second cycle on, seed 1,
334    /// xoshiro.
335    pub fn new(size: usize, edges: i64) -> Self {
336        SearchParams {
337            size,
338            edges,
339            fixed: Vec::new(),
340            experiments: 40,
341            max_moves: 250,
342            div_freq: 250,
343            div_dur: 4,
344            kick_size: DEFAULT_KICK_SIZE,
345            kick_ban: default_kick_ban(),
346            tabu_tenure: AUTO_TABU_TENURE,
347            seed: 1,
348            rng: RngKind::Xoshiro,
349            record_trace: false,
350            aspiration: false,
351            full_aspiration: false,
352            connected: false,
353            path: false,
354            endpoints: None,
355            regular: None,
356        }
357    }
358
359    /// Checks the parameters against a graph on `n` vertices, with the same rules as the C program
360    /// plus checks it omitted (fixed vertices must be distinct and in range).
361    pub fn validate(&self, n: usize) -> Result<(), Error> {
362        if self.size < 2 || self.size <= self.fixed.len() || self.size + 1 > n {
363            return Err(Error::InvalidSubgraphSize(self.size as i64));
364        }
365        if self.div_freq < 1 {
366            return Err(Error::InvalidDiversificationFrequency(self.div_freq as i64));
367        }
368        let mut seen = vec![false; n];
369        for &v in &self.fixed {
370            if v >= n {
371                return Err(Error::VertexOutOfRange {
372                    vertex: v as i64,
373                    n,
374                });
375            }
376            if std::mem::replace(&mut seen[v], true) {
377                return Err(Error::DuplicateVertex(v));
378            }
379        }
380        if let Some([s, t]) = self.endpoints {
381            if !self.path {
382                return Err(Error::Invalid("endpoints need a path search".into()));
383            }
384            for v in [s, t] {
385                if v >= n {
386                    return Err(Error::VertexOutOfRange {
387                        vertex: v as i64,
388                        n,
389                    });
390                }
391            }
392            if s == t {
393                return Err(Error::Invalid(format!(
394                    "a path's two endpoints must differ, got {s} twice"
395                )));
396            }
397            let extra = [s, t].iter().filter(|&&v| !seen[v]).count();
398            if self.size <= self.fixed.len() + extra {
399                return Err(Error::InvalidSubgraphSize(self.size as i64));
400            }
401        }
402        Ok(())
403    }
404}
405
406/// Counts the components of the current subgraph, for [`SearchParams::connected`].
407pub(crate) struct Components {
408    /// The pass that last reached each vertex; a new pass needs no clearing.
409    seen: Vec<u32>,
410    pass: u32,
411    stack: Vec<usize>,
412}
413
414impl Components {
415    pub(crate) fn new(n: usize) -> Self {
416        Components {
417            seen: vec![0; n],
418            pass: 0,
419            stack: Vec::new(),
420        }
421    }
422
423    /// The number of components beyond the first among `members`, the vertices with
424    /// `in_sub[v] != 0`, with each vertex's neighbors in the whole graph given by `neighbors`.
425    pub(crate) fn extra<'g>(
426        &mut self,
427        members: impl Iterator<Item = usize>,
428        in_sub: &[u8],
429        neighbors: impl Fn(usize) -> &'g [u32],
430    ) -> i64 {
431        if self.pass == u32::MAX {
432            self.seen.fill(0);
433            self.pass = 0;
434        }
435        self.pass += 1;
436        let pass = self.pass;
437        let mut components = 0;
438        for start in members {
439            if self.seen[start] == pass {
440                continue;
441            }
442            components += 1;
443            self.seen[start] = pass;
444            self.stack.push(start);
445            while let Some(u) = self.stack.pop() {
446                for &x in neighbors(u) {
447                    let x = x as usize;
448                    if in_sub[x] != 0 && self.seen[x] != pass {
449                        self.seen[x] = pass;
450                        self.stack.push(x);
451                    }
452                }
453            }
454        }
455        (components - 1).max(0)
456    }
457}
458
459/// The outcome of one experiment.
460#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
461pub struct Experiment {
462    /// The smallest conflict reached, which is that of `vertices`: `|e - target|`, or for a regular
463    /// search the deviation from regularity, plus the components beyond the first with
464    /// [`SearchParams::connected`]. 0 exactly when the experiment succeeded.
465    pub best_conflict: i64,
466    /// Moves made: the index of the successful move, or `max_moves` if none succeeded.
467    pub moves: usize,
468    /// Whether a subgraph with exactly the target edge count was found.
469    pub success: bool,
470    /// Vertices (ascending, fixed ones included) of the subgraph that reached `best_conflict`.
471    pub vertices: Vec<usize>,
472    /// Objective value after each move, if requested.
473    #[serde(default, skip_serializing_if = "Option::is_none")]
474    pub trace: Option<Vec<u32>>,
475}
476
477/// The outcome of a search: its parameters and one [`Experiment`] per experiment.
478#[derive(Clone, Debug, Serialize, Deserialize)]
479pub struct SearchResult {
480    pub params: SearchParams,
481    pub experiments: Vec<Experiment>,
482}
483
484impl SearchResult {
485    /// Number of successful experiments.
486    pub fn successes(&self) -> usize {
487        self.experiments.iter().filter(|e| e.success).count()
488    }
489
490    /// The distribution of moves needed by successful experiments over [`NUM_BOXES`] equal boxes.
491    pub fn boxes(&self) -> [usize; NUM_BOXES] {
492        let size = self.params.max_moves / NUM_BOXES + 1;
493        let mut boxes = [0; NUM_BOXES];
494        for e in self.experiments.iter().filter(|e| e.success) {
495            boxes[e.moves / size] += 1;
496        }
497        boxes
498    }
499
500    /// Mean moves per success, over successful experiments only ("relative cost").
501    pub fn relative_cost(&self) -> Option<f64> {
502        let s = self.successes();
503        (s > 0).then(|| {
504            self.experiments
505                .iter()
506                .filter(|e| e.success)
507                .map(|e| e.moves)
508                .sum::<usize>() as f64
509                / s as f64
510        })
511    }
512
513    /// Total moves over all experiments divided by the number of successes ("true cost").
514    pub fn true_cost(&self) -> Option<f64> {
515        let s = self.successes();
516        (s > 0).then(|| self.experiments.iter().map(|e| e.moves).sum::<usize>() as f64 / s as f64)
517    }
518
519    /// The best experiment of a densest or sparsest search of `graph`: the smallest conflict; then,
520    /// if the graph was made from scores ([`WeightedGraph::from_scores`]), the highest total score
521    /// (`highest`) or the lowest, since selections tied at rounded weights can differ in their
522    /// exact totals; then the earliest. `None` without experiments.
523    pub fn best_by_score(&self, graph: &WeightedGraph, highest: bool) -> Option<usize> {
524        let least = self.experiments.iter().map(|e| e.best_conflict).min()?;
525        let tied =
526            (0..self.experiments.len()).filter(|&i| self.experiments[i].best_conflict == least);
527        let score = |i: usize| {
528            graph
529                .induced_score(&self.experiments[i].vertices)
530                .unwrap_or(0.0)
531        };
532        tied.reduce(|best, i| {
533            let (a, b) = (score(best), score(i));
534            if (highest && b > a) || (!highest && b < a) {
535                i
536            } else {
537                best
538            }
539        })
540    }
541
542    /// Mean best objective value over all experiments ("average conflict").
543    pub fn average_conflict(&self) -> f64 {
544        if self.experiments.is_empty() {
545            return f64::NAN;
546        }
547        self.experiments
548            .iter()
549            .map(|e| e.best_conflict)
550            .sum::<i64>() as f64
551            / self.experiments.len() as f64
552    }
553}
554
555/// Runs a search. With [`RngKind::Xoshiro`], experiments run in parallel, each with its own random
556/// stream, so results depend only on the seed. With [`RngKind::Legacy`], experiments run one after
557/// another and match the C program exactly.
558pub fn search<G: SearchGraph>(graph: &G, params: &SearchParams) -> Result<SearchResult, Error> {
559    if params.regular.is_some() || params.path {
560        // regular and path searches have a tenure of 1
561        let mut result = crate::regular::search(unweighted(graph)?, params)?;
562        result.params.tabu_tenure = 1;
563        return Ok(result);
564    }
565    params.validate(graph.num_vertices())?;
566    let experiments = match params.rng {
567        RngKind::Legacy => {
568            let mut out = Vec::with_capacity(params.experiments);
569            search_sequential(graph, params, |e| out.push(e.clone()))?;
570            out
571        }
572        RngKind::Xoshiro => (0..params.experiments)
573            .into_par_iter()
574            .map_init(
575                || Workspace::new(graph, params),
576                |ws, i| {
577                    ws.reset(params);
578                    let mut rng = Xoshiro::for_stream(params.seed as u64, i as u64);
579                    ws.run(graph, params, &mut rng)
580                },
581            )
582            .collect(),
583    };
584    // record the tenure the search used, not "automatic"
585    let mut params = params.clone();
586    params.tabu_tenure = params.resolved_tabu_tenure(graph.num_vertices());
587    Ok(SearchResult {
588        params,
589        experiments,
590    })
591}
592
593/// Runs the experiments one at a time, calling `on_experiment` after each.
594///
595/// With [`RngKind::Legacy`] this reproduces the C program exactly: a single random stream shared
596/// by all experiments, and state (the permutation used to pick starting subgraphs, the best
597/// subgraph seen) carried over from one experiment to the next. With [`RngKind::Xoshiro`] the
598/// results equal those of [`search`].
599pub fn search_sequential<G: SearchGraph, F>(
600    graph: &G,
601    params: &SearchParams,
602    mut on_experiment: F,
603) -> Result<(), Error>
604where
605    F: FnMut(&Experiment),
606{
607    if params.regular.is_some() || params.path {
608        return crate::regular::search_sequential(unweighted(graph)?, params, on_experiment);
609    }
610    params.validate(graph.num_vertices())?;
611    let mut ws = Workspace::new(graph, params);
612    match params.rng {
613        RngKind::Legacy => {
614            let mut rng = Randu::new(params.seed);
615            for _ in 0..params.experiments {
616                on_experiment(&ws.run(graph, params, &mut rng));
617            }
618        }
619        RngKind::Xoshiro => {
620            for i in 0..params.experiments {
621                ws.reset(params);
622                let mut rng = Xoshiro::for_stream(params.seed as u64, i as u64);
623                on_experiment(&ws.run(graph, params, &mut rng));
624            }
625        }
626    }
627    Ok(())
628}
629
630/// The smaller of `best` and the best value of swapping a subgraph vertex, whose row of the
631/// adjacency matrix is `row`, for each of `cols`, stopping early at `bound`, below which the row
632/// cannot go. With [`scan_row`], this is the search's hot loop.
633#[inline(always)]
634fn row_min<R: AdjacencyRow>(
635    row: R,
636    cols: &[usize],
637    sub_degs: &[i32],
638    degree: i64,
639    bound: i64,
640    best: i64,
641) -> i64 {
642    let mut best = best;
643    for &t in cols {
644        let val = (degree - row.value(t) + i64::from(sub_degs[t])).abs();
645        if val < best {
646            best = val;
647            if best <= bound {
648                break;
649            }
650        }
651    }
652    best
653}
654
655/// Appends to `sub_opt`/`rest_opt` every swap of `vert` for one of `cols` with value `best`, up
656/// to their length, which caps how many are kept, as in `sub_search.c`.
657#[inline(always)]
658#[allow(clippy::too_many_arguments)]
659fn scan_row<R: AdjacencyRow>(
660    row: R,
661    cols: &[usize],
662    sub_degs: &[i32],
663    degree: i64,
664    vert: usize,
665    best: i64,
666    opt_mov: &mut usize,
667    sub_opt: &mut [usize],
668    rest_opt: &mut [usize],
669) {
670    let cap = sub_opt.len().min(rest_opt.len());
671    let mut count = *opt_mov;
672    for &t in cols {
673        if count >= cap {
674            break;
675        }
676        let val = (degree - row.value(t) + i64::from(sub_degs[t])).abs();
677        if val == best {
678            sub_opt[count] = vert;
679            rest_opt[count] = t;
680            count += 1;
681        }
682    }
683    *opt_mov = count;
684}
685
686/// The candidate columns for a move, as `Workspace::list_candidates` lists them in `u_list`: how
687/// many are active (they come first) and how many in all, and the range of their degrees into the
688/// subgraph.
689struct Columns {
690    active: usize,
691    all: usize,
692    active_range: (i64, i64),
693    all_range: (i64, i64),
694}
695
696impl Columns {
697    /// The range of degrees among the first `w_cols` columns: all of them, or the active ones.
698    #[inline]
699    fn range(&self, w_cols: usize) -> (i64, i64) {
700        if w_cols == self.all {
701            self.all_range
702        } else {
703            self.active_range
704        }
705    }
706}
707
708/// The candidate columns bucketed by their degree into the subgraph, so that a row can visit only
709/// the columns whose degree lets a swap reach a given value. Results are exactly those of scanning
710/// the columns in order: buckets keep the columns' order, and ties are listed by position.
711#[derive(Default)]
712struct Buckets {
713    /// Degree of bucket 0.
714    base: i64,
715    start: Vec<u32>,
716    pos: Vec<u32>,
717    fill: Vec<u32>,
718    /// Each column's degree, by position.
719    deg: Vec<i64>,
720    gather: Vec<u32>,
721    /// Whether bucketing is paying off: rows whose moves were collected from buckets, rows tried,
722    /// and the move before which buckets are not built (when their degrees are too crowded for
723    /// the buckets to narrow anything down, building them only costs time).
724    collected: u32,
725    tried: u32,
726    paused_until: usize,
727}
728
729impl Buckets {
730    /// Buckets `cols` by degree, if their degrees span few enough values to pay off; returns
731    /// whether it did.
732    fn build(&mut self, cols: &[usize], sub_degs: &[i32], lo: i64, hi: i64) -> bool {
733        let span = (hi - lo + 1) as usize;
734        if span > 2 * cols.len() + 64 {
735            return false;
736        }
737        self.base = lo;
738        self.start.clear();
739        self.start.resize(span + 1, 0);
740        self.deg.clear();
741        for &t in cols {
742            let d = i64::from(sub_degs[t]);
743            self.deg.push(d);
744            self.start[(d - lo) as usize + 1] += 1;
745        }
746        for b in 0..span {
747            self.start[b + 1] += self.start[b];
748        }
749        self.fill.clear();
750        self.fill.extend_from_slice(&self.start[..span]);
751        self.pos.clear();
752        self.pos.resize(cols.len(), 0);
753        for (p, &d) in self.deg.iter().enumerate() {
754            let b = (d - lo) as usize;
755            self.pos[self.fill[b] as usize] = p as u32;
756            self.fill[b] += 1;
757        }
758        true
759    }
760
761    /// Starts an experiment with bucketing on.
762    fn reset(&mut self) {
763        (self.collected, self.tried, self.paused_until) = (0, 0, 0);
764    }
765
766    /// After a move made with buckets: once enough rows have tried them, pauses bucketing for a
767    /// while if they mostly could not narrow the columns down.
768    fn review(&mut self, j: usize) {
769        if self.tried >= 256 {
770            if self.collected * 2 < self.tried {
771                self.paused_until = j + 1024;
772            }
773            (self.collected, self.tried) = (0, 0);
774        }
775    }
776
777    /// The positions in degree `d`'s bucket, ascending.
778    #[inline]
779    fn bucket(&self, d: i64) -> &[u32] {
780        let b = (d - self.base) as usize;
781        &self.pos[self.start[b] as usize..self.start[b + 1] as usize]
782    }
783
784    /// [`row_min`] over the first `w_cols` columns, whose degrees lie in `range`, visiting buckets
785    /// in order of the least value their swaps can have and stopping once none can beat `best`.
786    #[allow(clippy::too_many_arguments)]
787    fn row_min<R: AdjacencyRow>(
788        &self,
789        row: R,
790        u_list: &[usize],
791        w_cols: usize,
792        (lo, hi): (i64, i64),
793        degree: i64,
794        wmax: i64,
795        bound: i64,
796        mut best: i64,
797    ) -> i64 {
798        // a swap with a column of degree d has value |degree + d - w| for some w in 0..=wmax: 0 is
799        // possible for d in [-degree, -degree + wmax], and the least value grows by 1 per step away
800        let visit = |d: i64, best: &mut i64| -> bool {
801            for &p in self.bucket(d) {
802                let p = p as usize;
803                if p >= w_cols {
804                    break;
805                }
806                let val = (degree + d - row.value(u_list[p])).abs();
807                if val < *best {
808                    *best = val;
809                    if *best <= bound {
810                        return true;
811                    }
812                }
813            }
814            false
815        };
816        let (za, zb) = ((-degree).max(lo), (-degree).saturating_add(wmax).min(hi));
817        let (mut left, mut right) = if za <= zb {
818            for d in za..=zb {
819                if visit(d, &mut best) {
820                    return best;
821                }
822            }
823            (za - 1, zb + 1)
824        } else if -degree > hi {
825            (hi, hi + 1)
826        } else {
827            (lo - 1, lo)
828        };
829        loop {
830            let from_left = if left >= lo {
831                -(degree + left)
832            } else {
833                i64::MAX
834            };
835            let from_right = if right <= hi {
836                degree + right - wmax
837            } else {
838                i64::MAX
839            };
840            let least = from_left.min(from_right);
841            if least == i64::MAX || least >= best {
842                return best;
843            }
844            let d = if from_left <= from_right {
845                left -= 1;
846                left + 1
847            } else {
848                right += 1;
849                right - 1
850            };
851            if visit(d, &mut best) {
852                return best;
853            }
854        }
855    }
856
857    /// [`scan_row`] over the first `w_cols` columns, visiting only the buckets whose swaps can have
858    /// value `best`, and listing those swaps in order of position. Returns false, having done
859    /// nothing, when those buckets hold too many columns for this to pay off.
860    #[allow(clippy::too_many_arguments)]
861    fn collect_row<R: AdjacencyRow>(
862        &mut self,
863        row: R,
864        u_list: &[usize],
865        w_cols: usize,
866        (lo, hi): (i64, i64),
867        degree: i64,
868        wmax: i64,
869        best: i64,
870        vert: usize,
871        opt_mov: &mut usize,
872        sub_opt: &mut [usize],
873        rest_opt: &mut [usize],
874    ) -> bool {
875        // |degree + d - w| = best needs d - w = best - degree or -best - degree, w in 0..=wmax
876        let window = |c: i64| (c.max(lo), c.saturating_add(wmax).min(hi));
877        let (a, b) = (window(-best - degree), window(best - degree));
878        let spans: &[(i64, i64)] = &if a.1 + 1 >= b.0 {
879            [(a.0, b.1), (1, 0)]
880        } else {
881            [a, b]
882        };
883        let total: usize = spans
884            .iter()
885            .filter(|s| s.0 <= s.1)
886            .map(|&(x, y)| {
887                (self.start[(y - self.base) as usize + 1] - self.start[(x - self.base) as usize])
888                    as usize
889            })
890            .sum();
891        self.tried += 1;
892        if total * 4 > w_cols {
893            return false;
894        }
895        self.collected += 1;
896        self.gather.clear();
897        for &(x, y) in spans {
898            for d in x..=y {
899                let b = (d - self.base) as usize;
900                for &p in &self.pos[self.start[b] as usize..self.start[b + 1] as usize] {
901                    if p as usize >= w_cols {
902                        break;
903                    }
904                    self.gather.push(p);
905                }
906            }
907        }
908        self.gather.sort_unstable();
909        let cap = sub_opt.len().min(rest_opt.len());
910        for &p in &self.gather {
911            if *opt_mov >= cap {
912                break;
913            }
914            let p = p as usize;
915            let t = u_list[p];
916            if (degree + self.deg[p] - row.value(t)).abs() == best {
917                sub_opt[*opt_mov] = vert;
918                rest_opt[*opt_mov] = t;
919                *opt_mov += 1;
920            }
921        }
922        true
923    }
924}
925
926fn unweighted<G: SearchGraph>(graph: &G) -> Result<&Graph, Error> {
927    graph
928        .as_graph()
929        .ok_or_else(|| Error::Invalid("regular and path searches need an unweighted graph".into()))
930}
931
932/// Search state. Field names follow `sub_search.c`.
933struct Workspace {
934    /// Number of free (non-fixed) subgraph vertices.
935    v_sub: usize,
936    /// Number of vertices outside the subgraph.
937    v_rest: usize,
938    /// Sum of all degrees (twice the edge count); an upper bound on the objective.
939    e: i64,
940    /// Degree of every vertex with respect to the current subgraph.
941    sub_degs: Vec<i32>,
942    /// Free subgraph vertices and outside vertices, in no particular order.
943    sub_verts: Vec<usize>,
944    rest_verts: Vec<usize>,
945    /// Position of every vertex in `sub_verts` or `rest_verts`.
946    vert_inds: Vec<usize>,
947    /// Membership of the current subgraph (fixed vertices always set) and of the best one.
948    sub_ch: Vec<u8>,
949    opt_ch: Vec<u8>,
950    /// Marks active rows and columns.
951    u_ch: Vec<u8>,
952    /// Candidate columns: active ones first, then the inactive ones.
953    u_list: Vec<usize>,
954    /// Optimal moves found in the current neighborhood.
955    sub_opt: Vec<usize>,
956    rest_opt: Vec<usize>,
957    /// Aspiration moves (with `params.aspiration`), as in `asub_search.c`.
958    sub_asp: Vec<usize>,
959    rest_asp: Vec<usize>,
960    /// Non-fixed vertices; a partial shuffle of it picks each starting subgraph.
961    rand_perm: Vec<usize>,
962    /// With `params.connected`.
963    components: Option<Components>,
964    /// With a region kick (`params.kick_size`): the move until which each vertex may not return,
965    /// whether each vertex is fixed, and the vertices still to be kicked out.
966    banned_until: Vec<usize>,
967    fixed: Vec<bool>,
968    kick_queue: Vec<usize>,
969    /// The tabu tenure, and with one above 1, the move until which each removed vertex may not
970    /// return and each added vertex may not leave.
971    tenure: usize,
972    tabu_in: Vec<usize>,
973    tabu_out: Vec<usize>,
974    /// With `params.full_aspiration`: the outside vertices that may not return yet, rebuilt each move.
975    tabu_cols: Vec<usize>,
976    /// The rows to scan in a move: vertex, candidate columns, row constant and a lower bound on
977    /// the row's best value.
978    rows: Vec<(usize, usize, i64, i64)>,
979    /// The candidate columns' positions bucketed by subgraph degree: bucket `b` (degree
980    /// `all_lo + b`) is `bucket_pos[bucket_start[b]..bucket_start[b + 1]]`, in increasing position.
981    buckets: Buckets,
982}
983
984impl Workspace {
985    fn new<G: SearchGraph>(graph: &G, params: &SearchParams) -> Self {
986        let v = graph.num_vertices();
987        let v_fix = params.fixed.len();
988        let mut ws = Workspace {
989            v_sub: params.size - v_fix,
990            v_rest: v - params.size,
991            // a bound on the conflict: the graph's edge count or total weight, as in the original
992            // programs, unless the target lies above it, when the conflict can reach the target.
993            // The legacy rng keeps the original bound, whose searches then never record a best
994            // subgraph and move at random (see PORTING.md)
995            e: {
996                let bound = graph.objective_bound();
997                if params.edges > bound && params.rng != RngKind::Legacy {
998                    params.edges + 1
999                } else {
1000                    bound
1001                }
1002            },
1003            sub_degs: vec![0; v],
1004            sub_verts: vec![0; params.size - v_fix],
1005            rest_verts: vec![0; v - params.size],
1006            vert_inds: vec![0; v],
1007            sub_ch: vec![0; v],
1008            opt_ch: vec![0; v],
1009            u_ch: vec![0; v],
1010            u_list: vec![0; v - params.size],
1011            sub_opt: vec![0; v],
1012            rest_opt: vec![0; v],
1013            sub_asp: if params.aspiration || params.full_aspiration {
1014                vec![0; v]
1015            } else {
1016                Vec::new()
1017            },
1018            rest_asp: if params.aspiration || params.full_aspiration {
1019                vec![0; v]
1020            } else {
1021                Vec::new()
1022            },
1023            rand_perm: Vec::with_capacity(v - v_fix),
1024            components: params.connected.then(|| Components::new(v)),
1025            banned_until: Vec::new(),
1026            fixed: Vec::new(),
1027            kick_queue: Vec::new(),
1028            tenure: params.resolved_tabu_tenure(v),
1029            tabu_cols: Vec::new(),
1030            tabu_in: Vec::new(),
1031            tabu_out: Vec::new(),
1032            rows: Vec::with_capacity(params.size),
1033            buckets: Buckets::default(),
1034        };
1035        if ws.tenure > 1 {
1036            ws.tabu_in = vec![0; v];
1037            ws.tabu_out = vec![0; v];
1038        }
1039        if params.kick_size > 0 {
1040            ws.banned_until = vec![0; v];
1041            ws.fixed = vec![false; v];
1042            for &f in &params.fixed {
1043                ws.fixed[f] = true;
1044            }
1045        }
1046        ws.reset(params);
1047        ws
1048    }
1049
1050    /// For a region kick: the `size` free subgraph vertices nearest a random free subgraph vertex,
1051    /// itself included, found by breadth-first search from it (fewer if it reaches no more). Each
1052    /// layer of the search is visited in random order, so that among vertices equally far from the
1053    /// center none is favored: in a clique, for instance, all are at distance 1.
1054    fn region<G: SearchGraph, R: SearchRng>(
1055        &self,
1056        graph: &G,
1057        size: usize,
1058        rng: &mut R,
1059    ) -> Vec<usize> {
1060        let center = self.sub_verts[rng.below(self.v_sub as u32) as usize];
1061        let mut seen = std::collections::HashSet::from([center]);
1062        let (mut layer, mut out) = (vec![center], vec![center]);
1063        while out.len() < size && !layer.is_empty() {
1064            let mut next = Vec::new();
1065            for &u in &layer {
1066                for &w in graph.neighbors(u) {
1067                    let w = w as usize;
1068                    if seen.insert(w) {
1069                        next.push(w);
1070                    }
1071                }
1072            }
1073            for i in (1..next.len()).rev() {
1074                let j = rng.below(i as u32 + 1) as usize;
1075                next.swap(i, j);
1076            }
1077            out.extend(
1078                next.iter()
1079                    .copied()
1080                    .filter(|&w| self.sub_ch[w] != 0 && !self.fixed[w])
1081                    .take(size - out.len()),
1082            );
1083            layer = next;
1084        }
1085        out
1086    }
1087
1088    /// For a region kick: the best vertex to swap in for `sub_vert`, by the usual move value, among
1089    /// the outside vertices not banned at move `j`; ties are broken at random.
1090    fn best_swap_in<G: SearchGraph, R: SearchRng>(
1091        &self,
1092        graph: &G,
1093        new_min_val: i64,
1094        sub_vert: usize,
1095        j: usize,
1096        rng: &mut R,
1097    ) -> Option<usize> {
1098        let degree = new_min_val - i64::from(self.sub_degs[sub_vert]);
1099        let (mut best, mut count, mut choice) = (i64::MAX, 0u32, None);
1100        for &r in &self.rest_verts[..self.v_rest] {
1101            if self.banned_until[r] > j {
1102                continue;
1103            }
1104            let val = (degree + i64::from(self.sub_degs[r]) - graph.edge_value(sub_vert, r)).abs();
1105            if val < best {
1106                (best, count, choice) = (val, 1, Some(r));
1107            } else if val == best {
1108                count += 1;
1109                if rng.below(count) == 0 {
1110                    choice = Some(r);
1111                }
1112            }
1113        }
1114        choice
1115    }
1116
1117    /// Lists the aspiration moves: swaps involving the two vertices just swapped (`rest_vert` now
1118    /// inside the subgraph, `sub_vert` now outside) that would beat the best value so far,
1119    /// `g_opt_val`. At most `v` are kept. Mirrors `asub_search.c`.
1120    fn aspiration_moves<G: SearchGraph>(
1121        &mut self,
1122        graph: &G,
1123        new_min_val: i64,
1124        g_opt_val: i64,
1125        sub_vert: usize,
1126        rest_vert: usize,
1127    ) -> usize {
1128        let cap = self.sub_asp.len();
1129        let mut asp_mov = 0;
1130        // swap rest_vert back out for any outside vertex
1131        let degree = new_min_val - i64::from(self.sub_degs[rest_vert]);
1132        let row = graph.adjacency_row(rest_vert);
1133        for k in 0..self.v_rest {
1134            let vert = self.rest_verts[k];
1135            let val = (degree - row.value(vert) + i64::from(self.sub_degs[vert])).abs();
1136            if val < g_opt_val && asp_mov < cap {
1137                self.sub_asp[asp_mov] = rest_vert;
1138                self.rest_asp[asp_mov] = vert;
1139                asp_mov += 1;
1140            }
1141        }
1142        // swap sub_vert back in for any subgraph vertex
1143        let degree = new_min_val + i64::from(self.sub_degs[sub_vert]);
1144        let row = graph.adjacency_row(sub_vert);
1145        for k in 0..self.v_sub {
1146            let vert = self.sub_verts[k];
1147            if vert == rest_vert {
1148                continue;
1149            }
1150            let val = (degree - row.value(vert) - i64::from(self.sub_degs[vert])).abs();
1151            if val < g_opt_val && asp_mov < cap {
1152                self.sub_asp[asp_mov] = vert;
1153                self.rest_asp[asp_mov] = sub_vert;
1154                asp_mov += 1;
1155            }
1156        }
1157        asp_mov
1158    }
1159
1160    /// Lists the full aspiration moves (with `params.full_aspiration`): the swaps the tabu tenure
1161    /// forbids at move `j` that would beat the best value so far, `g_opt_val`. Those are each
1162    /// subgraph vertex that may not leave yet with every outside vertex, and each outside vertex
1163    /// that may not return yet with every subgraph vertex. Rows are skipped by the same kind of
1164    /// bound as in [`Workspace::bound_rows`]. At most `v` are kept.
1165    fn full_aspiration_moves<G: SearchGraph>(
1166        &mut self,
1167        graph: &G,
1168        new_min_val: i64,
1169        g_opt_val: i64,
1170        j: usize,
1171    ) -> usize {
1172        let cap = self.sub_asp.len();
1173        let mut asp_mov = 0;
1174        // the few outside vertices that may not return yet, and the degree ranges among all outside
1175        // vertices and among those, for bounds like `bound_rows`'
1176        let (mut all_lo, mut all_hi, mut tabu_lo, mut tabu_hi) =
1177            (i64::MAX, i64::MIN, i64::MAX, i64::MIN);
1178        let mut tabu_cols = std::mem::take(&mut self.tabu_cols);
1179        tabu_cols.clear();
1180        for l in 0..self.v_rest {
1181            let t = self.rest_verts[l];
1182            let d = i64::from(self.sub_degs[t]);
1183            (all_lo, all_hi) = (all_lo.min(d), all_hi.max(d));
1184            if self.tabu_in[t] > j {
1185                tabu_cols.push(t);
1186                (tabu_lo, tabu_hi) = (tabu_lo.min(d), tabu_hi.max(d));
1187            }
1188        }
1189        for k in 0..self.v_sub {
1190            let s = self.sub_verts[k];
1191            let tabu_row = self.tabu_out[s] > j;
1192            if !tabu_row && tabu_cols.is_empty() {
1193                continue;
1194            }
1195            let degree = new_min_val - i64::from(self.sub_degs[s]);
1196            let (lo, hi) = if tabu_row {
1197                (all_lo, all_hi)
1198            } else {
1199                (tabu_lo, tabu_hi)
1200            };
1201            let (low, high) = (degree + lo - graph.max_row_value(s), degree + hi);
1202            let bound = if high < 0 {
1203                -high
1204            } else if low > 0 {
1205                low
1206            } else {
1207                0
1208            };
1209            #[cfg(test)]
1210            let bound = if NO_ROW_SKIPPING.load(std::sync::atomic::Ordering::Relaxed) {
1211                0
1212            } else {
1213                bound
1214            };
1215            if bound >= g_opt_val {
1216                continue;
1217            }
1218            let row = graph.adjacency_row(s);
1219            let mut consider = |t: usize, asp_mov: &mut usize| {
1220                let val = (degree - row.value(t) + i64::from(self.sub_degs[t])).abs();
1221                if val < g_opt_val && *asp_mov < cap {
1222                    self.sub_asp[*asp_mov] = s;
1223                    self.rest_asp[*asp_mov] = t;
1224                    *asp_mov += 1;
1225                }
1226            };
1227            if tabu_row {
1228                for &t in &self.rest_verts[..self.v_rest] {
1229                    consider(t, &mut asp_mov);
1230                }
1231            } else {
1232                for &t in &tabu_cols {
1233                    consider(t, &mut asp_mov);
1234                }
1235            }
1236        }
1237        self.tabu_cols = tabu_cols;
1238        asp_mov
1239    }
1240
1241    /// Restores the state of a fresh workspace.
1242    fn reset(&mut self, params: &SearchParams) {
1243        self.sub_ch.fill(0);
1244        self.opt_ch.fill(0);
1245        for &f in &params.fixed {
1246            self.sub_ch[f] = 1;
1247        }
1248        self.rand_perm.clear();
1249        self.rand_perm
1250            .extend((0..self.sub_ch.len()).filter(|&i| self.sub_ch[i] == 0));
1251    }
1252
1253    /// One experiment. Mirrors the body of the experiment loop in `sub_search.c` (or, with
1254    /// `params.aspiration`, `asub_search.c`) statement by statement, so that random numbers are
1255    /// drawn in exactly the same order. Each move chooses a swap, makes it, and then finds the
1256    /// best swaps for the next move: listing the candidate columns, bounding the rows, and
1257    /// collecting the swaps of least conflict.
1258    fn run<G: SearchGraph, R: SearchRng>(
1259        &mut self,
1260        graph: &G,
1261        params: &SearchParams,
1262        rng: &mut R,
1263    ) -> Experiment {
1264        let mut trace = params
1265            .record_trace
1266            .then(|| Vec::with_capacity(params.max_moves));
1267        // signed difference between the subgraph's edge count (or weight) and the target
1268        let mut new_min_val = self.start_experiment(graph, params, rng);
1269        let mut g_opt_val = self.e;
1270        let mut old_min_val = self.e;
1271        let (mut opt_mov, mut asp_mov) = (0usize, 0usize);
1272        let mut success = false;
1273        let mut j = 0;
1274        while j < params.max_moves {
1275            let (sub_vert, rest_vert) =
1276                self.choose_move(graph, params, j, new_min_val, opt_mov, asp_mov, rng);
1277            let rest_col = self.vert_inds[rest_vert];
1278            new_min_val += self.apply_swap(graph, sub_vert, rest_vert, j);
1279
1280            let mut obj_val = new_min_val.abs();
1281            if let Some(c) = self.components.as_mut() {
1282                let members = params.fixed.iter().chain(&self.sub_verts).copied();
1283                obj_val += c.extra(members, &self.sub_ch, |u| graph.neighbors(u));
1284            }
1285            if let Some(t) = trace.as_mut() {
1286                t.push(obj_val.min(u32::MAX as i64) as u32);
1287            }
1288            if obj_val < g_opt_val {
1289                g_opt_val = obj_val;
1290                self.opt_ch.copy_from_slice(&self.sub_ch);
1291            }
1292            if obj_val == 0 {
1293                success = true;
1294                break;
1295            }
1296
1297            let cols = self.list_candidates(params, j, sub_vert, rest_col);
1298            // if the edge count changed, every row gets a full scan
1299            if new_min_val != old_min_val {
1300                for k in 0..self.v_sub {
1301                    self.u_ch[self.sub_verts[k]] = 1;
1302                }
1303            }
1304            self.bound_rows(graph, new_min_val, j, rest_vert, &cols);
1305            opt_mov = self.collect_best_moves(graph, j, &cols);
1306            // with tenure 1 the full criterion allows the same swaps as the original's, whose code
1307            // (and order of moves) it then keeps
1308            if params.full_aspiration && self.tenure > 1 {
1309                asp_mov = self.full_aspiration_moves(graph, new_min_val, g_opt_val, j);
1310            } else if params.aspiration || params.full_aspiration {
1311                asp_mov = self.aspiration_moves(graph, new_min_val, g_opt_val, sub_vert, rest_vert);
1312            }
1313            for k in 0..cols.active {
1314                self.u_ch[self.u_list[k]] = 0;
1315            }
1316            old_min_val = new_min_val;
1317            j += 1;
1318        }
1319
1320        let vertices = (0..graph.num_vertices())
1321            .filter(|&k| self.opt_ch[k] != 0)
1322            .collect();
1323        // return the free subgraph vertices to the outside for the next experiment
1324        for k in 0..self.v_sub {
1325            self.sub_ch[self.sub_verts[k]] = 0;
1326        }
1327        Experiment {
1328            best_conflict: g_opt_val,
1329            moves: j,
1330            success,
1331            vertices,
1332            trace,
1333        }
1334    }
1335
1336    /// Starts an experiment: a random subgraph, every vertex's degree into it, the outside
1337    /// vertices listed, and the kick, tabu and bucket state cleared. Returns the signed difference
1338    /// between the subgraph's edge count (or weight) and the target.
1339    #[inline]
1340    fn start_experiment<G: SearchGraph, R: SearchRng>(
1341        &mut self,
1342        graph: &G,
1343        params: &SearchParams,
1344        rng: &mut R,
1345    ) -> i64 {
1346        let v = graph.num_vertices();
1347        self.sub_degs.fill(0);
1348        self.u_ch.fill(0);
1349
1350        // generate a new random subgraph
1351        let mut j = self.rand_perm.len();
1352        for k in 0..self.v_sub {
1353            let index = rng.below(j as u32) as usize;
1354            let vert = self.rand_perm[index];
1355            j -= 1;
1356            self.rand_perm[index] = self.rand_perm[j];
1357            self.rand_perm[j] = vert;
1358            self.sub_ch[vert] = 1;
1359            self.sub_verts[k] = vert;
1360            self.vert_inds[vert] = k;
1361        }
1362
1363        // vertex degrees within the subgraph; list the outside vertices
1364        let mut l = 0;
1365        for j in 0..v {
1366            if self.sub_ch[j] != 0 {
1367                for &x in graph.neighbors(j) {
1368                    self.sub_degs[x as usize] += graph.neighbor_value(j, x as usize) as i32;
1369                }
1370            } else {
1371                self.vert_inds[j] = l;
1372                self.rest_verts[l] = j;
1373                l += 1;
1374            }
1375        }
1376
1377        if params.kick_size > 0 {
1378            self.banned_until.fill(0);
1379            self.kick_queue.clear();
1380        }
1381        if self.tenure > 1 {
1382            self.tabu_in.fill(0);
1383            self.tabu_out.fill(0);
1384        }
1385        self.buckets.reset();
1386
1387        (0..v)
1388            .filter(|&j| self.sub_ch[j] != 0)
1389            .map(|j| i64::from(self.sub_degs[j]))
1390            .sum::<i64>()
1391            / 2
1392            - params.edges
1393    }
1394
1395    /// Chooses the swap for move `j`: a region kick's next move, a random (diversifying) move, an
1396    /// aspiration move, or one of the `opt_mov` best moves.
1397    #[inline]
1398    #[allow(clippy::too_many_arguments)]
1399    fn choose_move<G: SearchGraph, R: SearchRng>(
1400        &mut self,
1401        graph: &G,
1402        params: &SearchParams,
1403        j: usize,
1404        new_min_val: i64,
1405        opt_mov: usize,
1406        asp_mov: usize,
1407        rng: &mut R,
1408    ) -> (usize, usize) {
1409        let kick = params.kick_size > 0;
1410        // with kicks on, a region kick starts each diversification cycle after the first, whose
1411        // random moves are kept (so a search shorter than div_freq moves is the same either way)
1412        if kick && j > 0 && params.div_dur > 0 && j.is_multiple_of(params.div_freq) {
1413            self.kick_queue = self.region(graph, params.kick_size, rng);
1414        }
1415        while let Some(s) = self.kick_queue.pop() {
1416            if self.sub_ch[s] != 0 {
1417                if let Some(r) = self.best_swap_in(graph, new_min_val, s, j, rng) {
1418                    self.banned_until[s] = j + params.kick_ban;
1419                    return (s, r);
1420                }
1421                break;
1422            }
1423        }
1424        if ((!kick || j < params.div_freq) && j % params.div_freq < params.div_dur) || opt_mov == 0
1425        {
1426            let s = self.sub_verts[rng.below(self.v_sub as u32) as usize];
1427            let r = self.rest_verts[rng.below(self.v_rest as u32) as usize];
1428            (s, r)
1429        } else if asp_mov > 0 {
1430            let index = rng.below(asp_mov as u32) as usize;
1431            (self.sub_asp[index], self.rest_asp[index])
1432        } else {
1433            let index = rng.below(opt_mov as u32) as usize;
1434            (self.sub_opt[index], self.rest_opt[index])
1435        }
1436    }
1437
1438    /// Swaps `sub_vert` out of the subgraph and `rest_vert` in at move `j`: degrees, the marks of
1439    /// vertices adjacent to exactly one of the two, membership, tabu stamps and the vertex lists.
1440    /// Returns the change in the edge count (or weight).
1441    #[inline]
1442    fn apply_swap<G: SearchGraph>(
1443        &mut self,
1444        graph: &G,
1445        sub_vert: usize,
1446        rest_vert: usize,
1447        j: usize,
1448    ) -> i64 {
1449        let sub_row = self.vert_inds[sub_vert];
1450        let rest_col = self.vert_inds[rest_vert];
1451        let change = i64::from(self.sub_degs[rest_vert])
1452            - i64::from(self.sub_degs[sub_vert])
1453            - graph.edge_value(sub_vert, rest_vert);
1454
1455        // update subgraph degrees; mark vertices adjacent to exactly one of the two swapped
1456        for &x in graph.neighbors(sub_vert) {
1457            let x = x as usize;
1458            self.sub_degs[x] -= graph.neighbor_value(sub_vert, x) as i32;
1459            self.u_ch[x] = 1;
1460        }
1461        for &x in graph.neighbors(rest_vert) {
1462            let x = x as usize;
1463            self.sub_degs[x] += graph.neighbor_value(rest_vert, x) as i32;
1464            self.u_ch[x] = 1 - self.u_ch[x];
1465        }
1466
1467        self.sub_ch[sub_vert] = 0;
1468        self.sub_ch[rest_vert] = 1;
1469        if self.tenure > 1 {
1470            self.tabu_in[sub_vert] = j + self.tenure;
1471            self.tabu_out[rest_vert] = j + self.tenure;
1472        }
1473
1474        self.sub_verts[sub_row] = rest_vert;
1475        self.vert_inds[rest_vert] = sub_row;
1476        self.rest_verts[rest_col] = sub_vert;
1477        self.vert_inds[sub_vert] = rest_col;
1478        change
1479    }
1480
1481    /// Lists the candidate columns for the next move in `u_list`: the active ones (adjacent to
1482    /// exactly one of the two vertices just swapped) first, then the others, leaving out the vertex
1483    /// just swapped out (at `rest_col`) and any a region kick or the tabu tenure bans, and notes
1484    /// the range of their subgraph degrees. The inactive ones fill the buffer from its end, then
1485    /// move up to follow the active ones, in the same order as if they had been counted first.
1486    #[inline]
1487    fn list_candidates(
1488        &mut self,
1489        params: &SearchParams,
1490        j: usize,
1491        sub_vert: usize,
1492        rest_col: usize,
1493    ) -> Columns {
1494        let (kick, tenure) = (params.kick_size > 0, self.tenure);
1495        let v_rest = self.v_rest;
1496        let mut cols = Columns {
1497            active: 0,
1498            all: 0,
1499            active_range: (i64::MAX, i64::MIN),
1500            all_range: (i64::MAX, i64::MIN),
1501        };
1502        self.u_ch[sub_vert] = 0;
1503        let mut temp = v_rest;
1504        for k in 0..v_rest {
1505            let vert = self.rest_verts[k];
1506            if k == rest_col
1507                || (kick && self.banned_until[vert] > j)
1508                || (tenure > 1 && self.tabu_in[vert] > j)
1509            {
1510                if tenure > 1 {
1511                    self.u_ch[vert] = 0;
1512                }
1513                continue;
1514            }
1515            let d = i64::from(self.sub_degs[vert]);
1516            cols.all_range = (cols.all_range.0.min(d), cols.all_range.1.max(d));
1517            if self.u_ch[vert] != 0 {
1518                self.u_list[cols.active] = vert;
1519                cols.active += 1;
1520                self.u_ch[vert] = 0;
1521                cols.active_range = (cols.active_range.0.min(d), cols.active_range.1.max(d));
1522            } else {
1523                temp -= 1;
1524                self.u_list[temp] = vert;
1525            }
1526        }
1527        cols.all = cols.active + (v_rest - temp);
1528        self.u_list.copy_within(temp..v_rest, cols.active);
1529        cols
1530    }
1531
1532    /// Lists in `rows` the subgraph vertices whose swaps the next move may make, other than the
1533    /// one just swapped in and any the tabu tenure holds: each with its candidate columns (all of
1534    /// them for rows marked for a full scan, else the active ones), the constant of its swaps'
1535    /// values, and a lower bound on its best value. Swapping `vert` for `t` has value
1536    /// |degree - w + d|, with d = sub_degs[t] in the columns' range and w, the edge's value, from 0
1537    /// to the row's largest.
1538    #[inline]
1539    fn bound_rows<G: SearchGraph>(
1540        &mut self,
1541        graph: &G,
1542        new_min_val: i64,
1543        j: usize,
1544        rest_vert: usize,
1545        cols: &Columns,
1546    ) {
1547        self.u_ch[rest_vert] = 0;
1548        self.rows.clear();
1549        for k in 0..self.v_sub {
1550            let vert = self.sub_verts[k];
1551            if vert == rest_vert {
1552                continue;
1553            }
1554            if self.tenure > 1 && self.tabu_out[vert] > j {
1555                self.u_ch[vert] = 0;
1556                continue;
1557            }
1558            let w_cols = if self.u_ch[vert] != 0 {
1559                self.u_ch[vert] = 0;
1560                cols.all
1561            } else {
1562                cols.active
1563            };
1564            if w_cols == 0 {
1565                continue;
1566            }
1567            let (lo, hi) = cols.range(w_cols);
1568            let degree = new_min_val - i64::from(self.sub_degs[vert]);
1569            let (low, high) = (degree + lo - graph.max_row_value(vert), degree + hi);
1570            let bound = if high < 0 {
1571                -high
1572            } else if low > 0 {
1573                low
1574            } else {
1575                0
1576            };
1577            #[cfg(test)]
1578            let bound = if NO_ROW_SKIPPING.load(std::sync::atomic::Ordering::Relaxed) {
1579                0
1580            } else {
1581                bound
1582            };
1583            self.rows.push((vert, w_cols, degree, bound));
1584        }
1585    }
1586
1587    /// Collects the optimal moves (at most v of them) into `sub_opt`/`rest_opt` and returns how
1588    /// many: exactly the ones a scan of every row in order would. It first finds the best value,
1589    /// scanning the most promising row first and skipping rows that cannot beat it, then lists the
1590    /// moves that reach it, in row order. When the columns' degrees span a narrow enough range,
1591    /// they are bucketed by degree, and each row visits only the buckets that can hold its best
1592    /// moves.
1593    #[inline]
1594    fn collect_best_moves<G: SearchGraph>(&mut self, graph: &G, j: usize, cols: &Columns) -> usize {
1595        let m = cols.all;
1596        let bucketed = m > 0
1597            && j >= self.buckets.paused_until
1598            && self.buckets.build(
1599                &self.u_list[..m],
1600                &self.sub_degs,
1601                cols.all_range.0,
1602                cols.all_range.1,
1603            );
1604        #[cfg(test)]
1605        let bucketed = bucketed && !NO_ROW_SKIPPING.load(std::sync::atomic::Ordering::Relaxed);
1606
1607        let mut opt_val = self.e;
1608        if let Some(first) = (0..self.rows.len()).min_by_key(|&i| self.rows[i].3) {
1609            for i in std::iter::once(first).chain((0..self.rows.len()).filter(|&i| i != first)) {
1610                let (vert, w_cols, degree, bound) = self.rows[i];
1611                if bound < opt_val {
1612                    let row = graph.adjacency_row(vert);
1613                    opt_val = if bucketed {
1614                        self.buckets.row_min(
1615                            row,
1616                            &self.u_list,
1617                            w_cols,
1618                            cols.range(w_cols),
1619                            degree,
1620                            graph.max_row_value(vert),
1621                            bound,
1622                            opt_val,
1623                        )
1624                    } else {
1625                        row_min(
1626                            row,
1627                            &self.u_list[..w_cols],
1628                            &self.sub_degs,
1629                            degree,
1630                            bound,
1631                            opt_val,
1632                        )
1633                    };
1634                }
1635            }
1636        }
1637
1638        let mut opt_mov = 0;
1639        for i in 0..self.rows.len() {
1640            let (vert, w_cols, degree, bound) = self.rows[i];
1641            if bound > opt_val {
1642                continue;
1643            }
1644            let row = graph.adjacency_row(vert);
1645            let collected = bucketed
1646                && self.buckets.collect_row(
1647                    row,
1648                    &self.u_list,
1649                    w_cols,
1650                    cols.range(w_cols),
1651                    degree,
1652                    graph.max_row_value(vert),
1653                    opt_val,
1654                    vert,
1655                    &mut opt_mov,
1656                    &mut self.sub_opt,
1657                    &mut self.rest_opt,
1658                );
1659            if !collected {
1660                scan_row(
1661                    row,
1662                    &self.u_list[..w_cols],
1663                    &self.sub_degs,
1664                    degree,
1665                    vert,
1666                    opt_val,
1667                    &mut opt_mov,
1668                    &mut self.sub_opt,
1669                    &mut self.rest_opt,
1670                );
1671            }
1672        }
1673        if bucketed {
1674            self.buckets.review(j);
1675        }
1676        opt_mov
1677    }
1678}
1679
1680#[cfg(test)]
1681mod tests {
1682    use super::*;
1683
1684    fn cycle(n: usize) -> Graph {
1685        Graph::from_edges(n, (0..n).map(|i| (i, (i + 1) % n))).unwrap()
1686    }
1687
1688    #[test]
1689    fn finds_induced_paths_in_a_cycle() {
1690        let g = cycle(30);
1691        let mut p = SearchParams::new(5, 4);
1692        p.experiments = 8;
1693        p.max_moves = 500;
1694        p.div_freq = 50;
1695        for rng in [RngKind::Xoshiro, RngKind::Legacy] {
1696            p.rng = rng;
1697            let r = search(&g, &p).unwrap();
1698            assert_eq!(r.successes(), 8, "{rng:?}");
1699            for e in &r.experiments {
1700                assert_eq!(e.vertices.len(), 5);
1701                assert_eq!(g.induced_edge_count(&e.vertices), 4);
1702            }
1703        }
1704    }
1705
1706    #[test]
1707    fn keeps_fixed_vertices() {
1708        let g = cycle(20);
1709        let mut p = SearchParams::new(4, 0);
1710        p.fixed = vec![3, 11];
1711        let r = search(&g, &p).unwrap();
1712        for e in r.experiments.iter().filter(|e| e.success) {
1713            assert!(e.vertices.contains(&3) && e.vertices.contains(&11));
1714            assert_eq!(g.induced_edge_count(&e.vertices), 0);
1715        }
1716        assert!(r.successes() > 0);
1717    }
1718
1719    #[test]
1720    fn settings_resolve_by_kind_of_search() {
1721        assert_eq!(
1722            search_settings(None, None, false, false).unwrap(),
1723            (DEFAULT_KICK_SIZE, AUTO_TABU_TENURE)
1724        );
1725        assert_eq!(search_settings(None, None, true, false).unwrap(), (0, 1));
1726        assert_eq!(search_settings(None, None, false, true).unwrap(), (0, 1));
1727        assert_eq!(
1728            search_settings(Some(16), Some(7), false, true).unwrap(),
1729            (16, 7)
1730        );
1731        assert_eq!(
1732            search_settings(Some(0), Some(1), true, false).unwrap(),
1733            (0, 1)
1734        );
1735        assert!(search_settings(Some(4), None, true, false).is_err());
1736        assert!(search_settings(None, Some(AUTO_TABU_TENURE), true, false).is_err());
1737        assert!(search_settings(None, Some(3), true, false).is_err());
1738    }
1739
1740    #[test]
1741    fn tabu_tenure_defaults_and_resolution() {
1742        assert_eq!(SearchParams::new(30, 0).tabu_tenure, AUTO_TABU_TENURE);
1743        // a tenth of the size or an eightieth of the rest, whichever is smaller, from 1 to 20
1744        assert_eq!(SearchParams::new(200, 0).resolved_tabu_tenure(2000), 20);
1745        assert_eq!(
1746            SearchParams::new(1080, 0).resolved_tabu_tenure(85320),
1747            MAX_AUTO_TABU_TENURE
1748        );
1749        assert_eq!(SearchParams::new(200, 0).resolved_tabu_tenure(500), 3);
1750        assert_eq!(SearchParams::new(72, 0).resolved_tabu_tenure(2048), 7);
1751        assert_eq!(SearchParams::new(15, 0).resolved_tabu_tenure(2000), 1);
1752        assert_eq!(SearchParams::new(30, 0).resolved_tabu_tenure(100), 1);
1753        let mut p = SearchParams::new(45, 0);
1754        p.tabu_tenure = 7;
1755        assert_eq!(p.resolved_tabu_tenure(2000), 7);
1756        // results saved before the tenure existed used 1
1757        assert_eq!(default_tabu_tenure(), 1);
1758    }
1759
1760    #[test]
1761    fn automatic_tenure_is_one_for_small_subgraphs() {
1762        let g = cycle(60);
1763        let mut p = SearchParams::new(12, 4);
1764        p.experiments = 8;
1765        p.max_moves = 600;
1766        let auto = search(&g, &p).unwrap().experiments;
1767        p.tabu_tenure = 1;
1768        assert_eq!(auto, search(&g, &p).unwrap().experiments);
1769    }
1770
1771    #[test]
1772    fn long_tenures_still_find_subgraphs() {
1773        let g = cycle(120);
1774        for tenure in [AUTO_TABU_TENURE, 2, 8] {
1775            let mut p = SearchParams::new(40, 20);
1776            p.experiments = 8;
1777            p.max_moves = 3000;
1778            p.tabu_tenure = tenure;
1779            let r = search(&g, &p).unwrap();
1780            assert!(r.successes() > 0, "tenure {tenure}");
1781            for e in r.experiments.iter().filter(|e| e.success) {
1782                assert_eq!(g.induced_edge_count(&e.vertices), 20);
1783            }
1784        }
1785    }
1786
1787    #[test]
1788    fn parallel_and_sequential_xoshiro_agree() {
1789        let g = cycle(40);
1790        let mut p = SearchParams::new(7, 3);
1791        p.experiments = 16;
1792        p.record_trace = true;
1793        let parallel = search(&g, &p).unwrap().experiments;
1794        let mut sequential = Vec::new();
1795        search_sequential(&g, &p, |e| sequential.push(e.clone())).unwrap();
1796        assert_eq!(parallel, sequential);
1797        assert!(
1798            parallel
1799                .iter()
1800                .all(|e| e.trace.as_ref().unwrap().len() == e.moves + usize::from(e.success))
1801        );
1802    }
1803
1804    #[test]
1805    fn skipping_rows_changes_no_result() {
1806        // every search makes the same moves whether or not it skips the rows the bounds rule out
1807        // (other tests running meanwhile may also scan every row, which changes nothing either)
1808        let n = 150;
1809        let pairs = (0..n).flat_map(|i| (i + 1..n).map(move |j| (i, j)));
1810        let g = Graph::from_edges(n, pairs.clone().filter(|&(i, j)| (i * 31 + j * 17) % 5 < 2))
1811            .unwrap();
1812        let w = WeightedGraph::from_weighted_edges(
1813            n,
1814            pairs
1815                .filter(|&(i, j)| (i * 13 + j * 7) % 3 != 0)
1816                .map(|(i, j)| (i, j, ((i * j) % 9 + 1) as u32)),
1817        )
1818        .unwrap();
1819        for case in [
1820            (
1821                20,
1822                1_000_000,
1823                DEFAULT_KICK_SIZE,
1824                AUTO_TABU_TENURE,
1825                RngKind::Xoshiro,
1826            ), // densest
1827            (20, 0, DEFAULT_KICK_SIZE, AUTO_TABU_TENURE, RngKind::Xoshiro), // sparsest
1828            (30, 180, 0, 1, RngKind::Xoshiro),
1829            (30, 180, 16, 5, RngKind::Xoshiro),
1830            (40, 560, DEFAULT_KICK_SIZE, 8, RngKind::Xoshiro),
1831            (40, 600, 0, 1, RngKind::Legacy),
1832        ]
1833        .into_iter()
1834        .flat_map(|case| [(case, false), (case, true)])
1835        {
1836            let ((size, edges, kick, tenure, rng), full_aspiration) = case;
1837            let mut p = SearchParams::new(size, edges);
1838            p.full_aspiration = full_aspiration;
1839            p.experiments = 8;
1840            p.max_moves = 1500;
1841            p.div_freq = 300;
1842            p.div_dur = 8;
1843            p.kick_size = kick;
1844            p.tabu_tenure = tenure;
1845            p.rng = rng;
1846            p.record_trace = true;
1847            let run = || {
1848                (
1849                    search(&g, &p).unwrap().experiments,
1850                    search(&w, &p).unwrap().experiments,
1851                )
1852            };
1853            let skipping = run();
1854            NO_ROW_SKIPPING.store(true, std::sync::atomic::Ordering::Relaxed);
1855            let full = run();
1856            NO_ROW_SKIPPING.store(false, std::sync::atomic::Ordering::Relaxed);
1857            assert_eq!(
1858                skipping, full,
1859                "size {size}, edges {edges}, full aspiration {full_aspiration}"
1860            );
1861        }
1862    }
1863
1864    #[test]
1865    fn densest_ties_go_to_the_best_exact_score() {
1866        // with resolution 1 every positive score becomes weight 1, so every edge ties; the
1867        // exact scores tell {2, 3} apart as the heaviest pair and {0, 1} as the lightest
1868        let scores = [(0, 1, 1.0), (2, 3, 2.0), (0, 2, 1.5), (1, 3, 1.25)];
1869        let (w, _) = WeightedGraph::from_scores(4, scores, 1).unwrap();
1870        let mut p = SearchParams::new(2, 1);
1871        p.experiments = 20;
1872        let result = search(&w, &p).unwrap();
1873        assert!(result.experiments.iter().all(|e| e.success));
1874        let pick = |highest| {
1875            result.experiments[result.best_by_score(&w, highest).unwrap()]
1876                .vertices
1877                .clone()
1878        };
1879        assert_eq!((pick(true), pick(false)), (vec![2, 3], vec![0, 1]));
1880        // without scores, the earliest of the tied experiments
1881        let plain =
1882            WeightedGraph::from_weighted_edges(4, scores.map(|(u, v, _)| (u, v, 1))).unwrap();
1883        assert_eq!(result.best_by_score(&plain, true), Some(0));
1884    }
1885
1886    #[test]
1887    fn full_aspiration_is_the_original_with_tenure_one_and_differs_with_longer() {
1888        let n = 120;
1889        let g = Graph::from_edges(
1890            n,
1891            (0..n)
1892                .flat_map(|i| (i + 1..n).map(move |j| (i, j)))
1893                .filter(|&(i, j)| (i * 29 + j * 13) % 7 < 3),
1894        )
1895        .unwrap();
1896        let mut p = SearchParams::new(30, 190);
1897        p.experiments = 8;
1898        p.max_moves = 2000;
1899        p.div_freq = 300;
1900        p.div_dur = 8;
1901        p.tabu_tenure = 1;
1902        let run = |p: &SearchParams| search(&g, p).unwrap().experiments;
1903        let (mut limited, mut full) = (p.clone(), p.clone());
1904        limited.aspiration = true;
1905        full.full_aspiration = true;
1906        // with tenure 1 the only tabu swaps involve the two vertices just swapped
1907        assert_eq!(run(&limited), run(&full));
1908        // with a longer tenure it considers more swaps, and every result is still what it reports
1909        limited.tabu_tenure = 6;
1910        full.tabu_tenure = 6;
1911        let result = run(&full);
1912        assert_ne!(run(&limited), result);
1913        for e in &result {
1914            let edges = g.induced_edge_count(&e.vertices) as i64;
1915            assert_eq!((edges - 190).abs(), e.best_conflict);
1916        }
1917        // the degree search has no aspiration
1918        let mut regular = full.clone();
1919        regular.regular = Some(Regular {
1920            degree: 3,
1921            two_phase: false,
1922        });
1923        assert!(search(&g, &regular).is_err());
1924    }
1925
1926    #[test]
1927    fn connected_searches_succeed_only_on_connected_subgraphs() {
1928        // two triangles and a 6-cycle: 6 vertices spanning 6 edges, all of degree 2, are either
1929        // both triangles or the 6-cycle, and only the 6-cycle is connected
1930        let g = Graph::from_edges(
1931            12,
1932            [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3)]
1933                .into_iter()
1934                .chain((6..12).map(|i| (i, 6 + (i - 5) % 6))),
1935        )
1936        .unwrap();
1937        let hexagon: Vec<usize> = (6..12).collect();
1938        let regular = |two_phase| {
1939            Some(Regular {
1940                degree: 2,
1941                two_phase,
1942            })
1943        };
1944        for target in [None, regular(false), regular(true)] {
1945            for rng in [RngKind::Xoshiro, RngKind::Legacy] {
1946                let mut p = SearchParams::new(6, 6);
1947                p.regular = target;
1948                p.rng = rng;
1949                p.experiments = 30;
1950                p.max_moves = 500;
1951                p.div_freq = 50;
1952                p.record_trace = true;
1953                let plain = search(&g, &p).unwrap();
1954                p.connected = true;
1955                let connected = search(&g, &p).unwrap();
1956                let label = format!("{target:?}, {rng:?}");
1957                assert!(connected.successes() > 0, "{label}");
1958                for e in &connected.experiments {
1959                    assert!(
1960                        !e.success || e.vertices == hexagon,
1961                        "{label}: {:?}",
1962                        e.vertices
1963                    );
1964                    // a two-phase search's trace counts edges, not regularity, in its first phase
1965                    if !target.is_some_and(|r| r.two_phase) {
1966                        let lowest = *e.trace.as_ref().unwrap().iter().min().unwrap();
1967                        assert_eq!(i64::from(lowest), e.best_conflict, "{label}");
1968                    }
1969                }
1970                assert!(
1971                    plain
1972                        .experiments
1973                        .iter()
1974                        .any(|e| e.success && e.vertices != hexagon),
1975                    "{label}: the plain search also finds the two triangles"
1976                );
1977            }
1978        }
1979    }
1980
1981    #[test]
1982    fn kicks_favor_no_vertex_among_equally_near_ones() {
1983        // in a clique every member is at distance 1 from every other, so a kick of 5 should draw
1984        // members from all over it, not the lowest-numbered ones
1985        let n = 64;
1986        let complete =
1987            Graph::from_edges(n, (0..n).flat_map(|u| (u + 1..n).map(move |v| (u, v)))).unwrap();
1988        let mut p = SearchParams::new(32, 0);
1989        p.kick_size = 5;
1990        let mut ws = Workspace::new(&complete, &p);
1991        for (k, v) in (0..32).map(|v| v * 2).enumerate() {
1992            ws.sub_ch[v] = 1;
1993            ws.sub_verts[k] = v;
1994        }
1995        let mut rng = Xoshiro::new(1);
1996        let mut drawn = vec![0; n];
1997        for _ in 0..400 {
1998            let region = ws.region(&complete, p.kick_size, &mut rng);
1999            assert_eq!(region.len(), 5);
2000            for v in region {
2001                assert_eq!(v % 2, 0, "only members of the subgraph");
2002                drawn[v] += 1;
2003            }
2004        }
2005        // 2000 draws over 32 members: each about 62 times; all of them drawn many times
2006        assert!((0..32).all(|k| drawn[2 * k] > 20), "{drawn:?}");
2007    }
2008
2009    #[test]
2010    fn region_kicks() {
2011        // the 6-cube: independent sets of 32 (the even-weight half) and 4-cycles, with kicks on
2012        let n = 6;
2013        let cube = Graph::from_edges(
2014            1 << n,
2015            (0..1usize << n)
2016                .flat_map(|u| (0..n).map(move |b| (u, u ^ (1 << b))))
2017                .filter(|&(u, w)| u < w),
2018        )
2019        .unwrap();
2020        for (size, edges) in [(32, 0), (16, 32), (4, 4)] {
2021            let mut p = SearchParams::new(size, edges);
2022            p.experiments = 20;
2023            p.max_moves = 2000;
2024            p.div_freq = 100;
2025            p.div_dur = 4;
2026            p.kick_size = 6;
2027            let r = search(&cube, &p).unwrap();
2028            assert!(r.successes() > 0, "{size} {edges}");
2029            for e in r.experiments.iter().filter(|e| e.success) {
2030                assert_eq!(cube.induced_edge_count(&e.vertices), edges as usize);
2031            }
2032            // sequential and parallel runs still agree, and fixed vertices stay
2033            let mut out = Vec::new();
2034            search_sequential(&cube, &p, |e| out.push(e.clone())).unwrap();
2035            assert_eq!(out, r.experiments);
2036            p.fixed = vec![0];
2037            assert!(
2038                search(&cube, &p)
2039                    .unwrap()
2040                    .experiments
2041                    .iter()
2042                    .all(|e| e.vertices.contains(&0))
2043            );
2044        }
2045        // kicks change the search: the same seed gives different experiments
2046        let mut p = SearchParams::new(32, 0);
2047        p.experiments = 4;
2048        p.max_moves = 1000;
2049        p.div_freq = 10; // kicks from move 10 on, before these searches succeed
2050        p.kick_size = 0;
2051        let plain = search(&cube, &p).unwrap();
2052        p.kick_size = 6;
2053        assert_ne!(plain.experiments, search(&cube, &p).unwrap().experiments);
2054        // regular and path searches ignore the kick size
2055        p.path = true;
2056        let kicked = search(&cube, &p).unwrap();
2057        p.kick_size = 0;
2058        assert_eq!(kicked.experiments, search(&cube, &p).unwrap().experiments);
2059    }
2060
2061    #[test]
2062    fn validates_parameters() {
2063        let g = cycle(10);
2064        let mut p = SearchParams::new(10, 3);
2065        assert!(matches!(
2066            search(&g, &p),
2067            Err(Error::InvalidSubgraphSize(10))
2068        ));
2069        p.size = 4;
2070        p.div_freq = 0;
2071        assert!(matches!(
2072            search(&g, &p),
2073            Err(Error::InvalidDiversificationFrequency(0))
2074        ));
2075        p.div_freq = 5;
2076        p.fixed = vec![2, 2];
2077        assert!(matches!(search(&g, &p), Err(Error::DuplicateVertex(2))));
2078    }
2079
2080    #[test]
2081    fn targets_above_the_total_still_find_the_closest_subgraphs() {
2082        // a 30-cycle has 30 edges, so 40 among 10 vertices is out of reach: the closest is an
2083        // induced path with 9, at conflict 31
2084        let g = cycle(30);
2085        let mut p = SearchParams::new(10, 40);
2086        p.experiments = 8;
2087        let r = search(&g, &p).unwrap();
2088        let best = r
2089            .experiments
2090            .iter()
2091            .min_by_key(|e| e.best_conflict)
2092            .unwrap();
2093        assert_eq!(best.best_conflict, 31);
2094        assert_eq!(best.vertices.len(), 10);
2095        assert_eq!(g.induced_edge_count(&best.vertices), 9);
2096        // the same in a weighted path whose total weight is 25: 3 vertices weigh at most 10
2097        let w = WeightedGraph::from_weighted_edges(6, (0..5).map(|i| (i, i + 1, 5))).unwrap();
2098        let mut p = SearchParams::new(3, 100);
2099        p.experiments = 8;
2100        let r = search(&w, &p).unwrap();
2101        let best = r
2102            .experiments
2103            .iter()
2104            .min_by_key(|e| e.best_conflict)
2105            .unwrap();
2106        assert_eq!(best.best_conflict, 90);
2107        assert_eq!(best.vertices.len(), 3);
2108    }
2109
2110    #[test]
2111    fn kicks_start_after_the_first_cycle() {
2112        assert_eq!(SearchParams::new(4, 4).kick_size, DEFAULT_KICK_SIZE);
2113        // within the first div_freq moves a search with kicks is the same as one without
2114        let n = 6;
2115        let cube = Graph::from_edges(
2116            1 << n,
2117            (0..1usize << n)
2118                .flat_map(|u| (0..n).map(move |b| (u, u ^ (1 << b))))
2119                .filter(|&(u, w)| u < w),
2120        )
2121        .unwrap();
2122        let mut p = SearchParams::new(16, 32);
2123        p.experiments = 20;
2124        p.max_moves = 100;
2125        p.div_freq = 100;
2126        p.kick_size = 0;
2127        let plain = search(&cube, &p).unwrap();
2128        p.kick_size = 6;
2129        assert_eq!(search(&cube, &p).unwrap().experiments, plain.experiments);
2130        // and regular and path searches ignore the kick size
2131        let mut p = SearchParams::new(10, 0);
2132        p.path = true;
2133        p.kick_size = 4;
2134        assert!(search(&cycle(30), &p).unwrap().successes() > 0);
2135    }
2136}