FastMcsplit 0.0.2__tar.gz → 0.0.3__tar.gz

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.
Files changed (46) hide show
  1. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/PKG-INFO +14 -2
  2. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/README.md +24 -5
  3. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/args/ParseArgs.hpp +5 -0
  4. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/GreedySearchMatching.hpp +8 -6
  5. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Reductions/R1.hpp +1 -1
  6. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Reductions/R3.hpp +2 -4
  7. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/SearchMatching.hpp +19 -3
  8. fastmcsplit-0.0.3/header/SearchTimeout.hpp +44 -0
  9. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/pyproject.toml +1 -1
  10. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/python/FastMcsplit.egg-info/PKG-INFO +14 -2
  11. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/python/FastMcsplit.egg-info/SOURCES.txt +1 -0
  12. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/python/README.md +13 -1
  13. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/python/fastmcsplit/__init__.py +1 -1
  14. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/python/fastmcsplit/api.py +14 -5
  15. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/python/native.cpp +16 -9
  16. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/setup.py +2 -1
  17. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/tests/test_python_api.py +51 -0
  18. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/MANIFEST.in +0 -0
  19. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/docs/pypi.md +0 -0
  20. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/docs/testpypi.md +0 -0
  21. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/EdgeAttr.hpp +0 -0
  22. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Graph.hpp +0 -0
  23. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Node.hpp +0 -0
  24. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/NodeAttr.hpp +0 -0
  25. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/NodeClasses/NodeClass.hpp +0 -0
  26. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/NodeClasses/NodeClassCompute.hpp +0 -0
  27. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/NodeNeighbor.hpp +0 -0
  28. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Parser/ParseCSVFile.hpp +0 -0
  29. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Parser/ParseFile.hpp +0 -0
  30. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Parser/ParseGFUFile.hpp +0 -0
  31. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Parser/ParseGRFFile.hpp +0 -0
  32. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Parser/ParseLADFile.hpp +0 -0
  33. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Parser/Parser.hpp +0 -0
  34. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Reductions/R2.hpp +0 -0
  35. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Reductions/R4.hpp +0 -0
  36. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Reductions/R5.hpp +0 -0
  37. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Reductions/R6.hpp +0 -0
  38. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Reductions/R8.hpp +0 -0
  39. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/Reductions/r_utils.hpp +0 -0
  40. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/define.hpp +0 -0
  41. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/time_utils.hpp +0 -0
  42. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/header/utils.hpp +0 -0
  43. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/python/FastMcsplit.egg-info/dependency_links.txt +0 -0
  44. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/python/FastMcsplit.egg-info/requires.txt +0 -0
  45. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/python/FastMcsplit.egg-info/top_level.txt +0 -0
  46. {fastmcsplit-0.0.2 → fastmcsplit-0.0.3}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: FastMcsplit
3
- Version: 0.0.2
3
+ Version: 0.0.3
4
4
  Summary: Native C++ maximum common induced subgraph solver for Python and NetworkX
5
5
  Author: Wilfried Agbeto, Camille Coti, Vladimir Reinharz
6
6
  Classifier: Development Status :: 5 - Production/Stable
@@ -117,6 +117,7 @@ The same keyword options work with all three interfaces.
117
117
  | `adaptive_rewards` | `False` | Use adaptive rewards as described in the C++ documentation. |
118
118
  | `heuristic` | `0` | Vertex ordering, name or ID below. |
119
119
  | `disabled_reductions` | `()` | Disable rules, e.g. `("R1", "R4")` or `(1, 4)`. R8 is currently inactive in the Python binding. |
120
+ | `timeout` | `1800` | Search budget in whole seconds, including greedy search; `0` disables it. |
120
121
  | `verbose` | `False` | Native diagnostic output to the process stdout. |
121
122
 
122
123
  Reward names: `capacity_diversity` (1), `pair_diversity` (2), `class_count` (3),
@@ -149,8 +150,19 @@ Every interface returns a `Result` containing one mapping:
149
150
  - `runtime`: native conversion/preprocessing/search time in seconds; excludes Python conversion.
150
151
  - `explored_nodes`: exact-search node count; zero in approximate-only mode.
151
152
  - `method`: `"exact"` or `"approximate"`.
153
+ - `timed_out`: whether the search budget expired; the best feasible mapping is returned.
152
154
 
153
- There is no timeout or cancellation option. Parallel edges are limited to
155
+
156
+ A timed out exact search has `optimal=False` unless its mapping reaches the
157
+ initial upper bound. For example:
158
+
159
+ ```python
160
+ result = fastmcsplit.solve(pattern, target, timeout=60)
161
+ if result.timed_out:
162
+ print("Time limit reached:", result.size)
163
+ ```
164
+
165
+ Parallel edges are limited to
154
166
  255 per direction, or 127 undirected loops per vertex.
155
167
 
156
168
  [solver]: https://gitlab.info.uqam.ca/agbeto.kossi_wilfried/fastmcsplit/-/blob/FastMcSplit/README.md
@@ -72,6 +72,7 @@ The program prints the best mapping as `(pattern_vertex, target_vertex)` pairs.
72
72
  | `-C, --connected` | Search for a connected common induced subgraph. Disabled by default. |
73
73
  | `-B, --big-first` | Try large solution sizes first. Disabled by default. |
74
74
  | `-g, --greedy` | Run the greedy heuristic before the exact search. Disabled by default. |
75
+ | `-t, --timeout SECONDS` | Limit greedy and exact search time in whole seconds. Default: 0 (unlimited). |
75
76
  | `-v, --verbose` | Print graph statistics, solution size, and timings. Disabled by default. |
76
77
  | `-V, --version` | Show version information. |
77
78
  | `-H, --help` | Show the complete help. |
@@ -80,6 +81,11 @@ The program prints the best mapping as `(pattern_vertex, target_vertex)` pairs.
80
81
  ./build/bin/Release/FastMcSplit -H
81
82
  ```
82
83
 
84
+ The timeout starts after graph preprocessing and covers both greedy and exact
85
+ search. For example, `-t 60` sets a 60-second search budget. On expiration,
86
+ the program prints the best mapping found followed by `status = TIMEOUT`;
87
+ this mapping is not guaranteed optimal.
88
+
83
89
  ### Reward strategies (`-R`)
84
90
 
85
91
  Rewards increase the scores of the last matched pattern and target vertices to guide later search choices. Without `-R` or `-A`, no reward bonus is applied. With `-R` alone, the selected strategy remains fixed.
@@ -117,14 +123,12 @@ Disabled by default. With `-A`, the solver starts from the strategy supplied by
117
123
 
118
124
  ### Vertex-ordering heuristics (`-h`)
119
125
 
120
- The default is heuristic 0; `-h` accepts 0 or 1. These heuristics apply to sparse, unlabelled target graphs. Dense targets (density greater than 0.5) and labelled instances use dedicated orderings. The solver can also prioritize a remaining vertex equivalent to the last matched pattern vertex before applying these orderings.
121
-
122
- Otherwise, the solver first considers active bidomains minimizing $\max(|P_C|,|T_C|)$. Within those bidomains, it selects a pattern vertex using the following criteria, in priority order:
126
+ The default is heuristic 0; `-h` accepts 0 or 1.
123
127
 
124
128
  | Value | Selection criteria |
125
129
  |---|---|
126
- | `0` (default) | Highest accumulated reward score, then highest degree, then smallest vertex ID. |
127
- | `1` | Highest accumulated reward score, then highest degree, then most neighbours touched by current matches, then largest bidomain index and vertex ID. |
130
+ | `0` (default) | Highest accumulated reward score (if `-R` and `-A` is used), then highest degree, then smallest vertex ID. |
131
+ | `1` | Highest accumulated reward score (if `-R` and `-A` is used), then highest degree, then most neighbours touched by current matches, then largest bidomain index and vertex ID. |
128
132
 
129
133
  ```bash
130
134
  ./build/bin/Release/FastMcSplit -F ulad -R 4 -h 1 p.txt t.txt
@@ -197,3 +201,18 @@ a
197
201
  ```
198
202
 
199
203
  In the current implementation, use `-F gfu` for undirected graphs and `-F ugfu` for directed graphs.
204
+
205
+ ## Datasets
206
+
207
+ FastMcSplit was compared to the following solvers:
208
+
209
+ - [McSplitDAL](https://github.com/KaiqiangYu/SIGMOD25-MCSS/tree/main/McSplitDAL)
210
+ - [RRSplit](https://github.com/KaiqiangYu/SIGMOD25-MCSS/tree/main/RRSplit)
211
+ - [SymSplit](https://github.com/mcsolver/symsplit)
212
+
213
+ The datasets are available in the [datasets](datasets/) folder.
214
+
215
+ ## Complete proofs
216
+
217
+ Complete proofs of the reduction rules are available in the
218
+ [supplementary document](supplementary/Complete_proofs.pdf).
@@ -54,6 +54,7 @@ class ParseArgs
54
54
  static bool W_REDUCTIONS[8];
55
55
  static int REWARD_STRATEGY;
56
56
  static int HEURISTIC;
57
+ static int TIMEOUT;
57
58
  public:
58
59
  ParseArgs();
59
60
  ~ParseArgs();
@@ -83,6 +84,7 @@ class ParseArgs
83
84
  static bool DO_REDUCTION(int r_id);
84
85
  static int get_REWARD_STRATEGY();
85
86
  static int get_HEURISTIC();
87
+ static int getTIMEOUT();
86
88
  };
87
89
 
88
90
  #define HELP_TEXT "\
@@ -161,6 +163,9 @@ Options:\n\
161
163
  Run the greedy algorithm before the exact search. The greedy incumbent is\n\
162
164
  used as an initial lower bound and may also select the target ordering\n\
163
165
  used by the exact solver.\n\
166
+ \n\
167
+ -t, --timeout SECONDS\n\
168
+ Search time limit, including greedy search (0 disables it; default: 0).\n\
164
169
  \n\
165
170
  -G, --get-all-solution\n\
166
171
  Request all solutions. Note: the current executable primarily reports the\n\
@@ -205,7 +205,7 @@ namespace FastMcSplit
205
205
  */
206
206
  void explore_greedy(const node_id_t k, node_id_t prev_ub=0)
207
207
  {
208
- if((use_node_budget && restart_nodes >= node_budget)
208
+ if(this->abort_requested() || (use_node_budget && restart_nodes >= node_budget)
209
209
  || k == this->pattern.size()) return;
210
210
 
211
211
  node_id_t ub=this->compute_bound_0(prev_ub);
@@ -268,6 +268,7 @@ namespace FastMcSplit
268
268
  std::vector<node_id_t> invalid_target_nodes;
269
269
  for(node_id_tn target_node : targets)
270
270
  {
271
+ if(this->abort_requested()) break;
271
272
  partionning_out target_result;
272
273
  this->K=k;
273
274
  this->partition_target_nodes(
@@ -380,7 +381,7 @@ namespace FastMcSplit
380
381
  int count_n = 0;
381
382
  for(node_id_t pattern_node : pattern_starts)
382
383
  {
383
- if(count_n > N) break;
384
+ if(this->abort_requested() || count_n > N) break;
384
385
  auto targets=diversified_targets(
385
386
  pattern_node,
386
387
  initial_target_candidates(pattern_node),
@@ -390,9 +391,9 @@ namespace FastMcSplit
390
391
  {
391
392
  search_from_seed(pattern_node,target_node,local_budget,1);
392
393
  restarts++;
393
- if(this->max_size==initial_upper_bound) break;
394
+ if(this->abort_requested() || this->max_size==initial_upper_bound) break;
394
395
  }
395
- if(this->max_size==initial_upper_bound) break;
396
+ if(this->abort_requested() || this->max_size==initial_upper_bound) break;
396
397
 
397
398
  count_n++;
398
399
  }
@@ -427,7 +428,7 @@ namespace FastMcSplit
427
428
  // else if(this->pattern.size() > 2000)
428
429
  // start_limit=std::min<size_t>(100,start_limit);
429
430
 
430
- for(size_t i=0; i<start_limit; ++i)
431
+ for(size_t i=0; i<start_limit && !this->abort_requested(); ++i)
431
432
  {
432
433
  node_id_t pattern_node=pattern_starts[i];
433
434
  node_id_tn target_node=first_target(pattern_node);
@@ -442,7 +443,7 @@ namespace FastMcSplit
442
443
  false
443
444
  );
444
445
  restarts++;
445
- if(this->max_size==initial_upper_bound) break;
446
+ if(this->abort_requested() || this->max_size==initial_upper_bound) break;
446
447
  }
447
448
 
448
449
  publish_incumbent();
@@ -497,6 +498,7 @@ namespace FastMcSplit
497
498
  use_node_budget(true),
498
499
  explore_unmatched_branch(true)
499
500
  {
501
+ this->set_abort_flag(exact_solver_.get_abort_flag());
500
502
  this->set_target_ordering(target_ordering_);
501
503
  }
502
504
 
@@ -205,7 +205,7 @@ namespace FastMcSplit::Reductions
205
205
  }
206
206
  else if(count==1)
207
207
  {
208
- //removes v nodes in lemme 4
208
+ //removes v nodes
209
209
  removeNodes(
210
210
  node_id,
211
211
  neigh_id,
@@ -6,8 +6,8 @@ namespace FastMcSplit::Reductions
6
6
  {
7
7
  /**
8
8
  * @class R3
9
- * @brief FR: Implementation de la reduction R3, associee au lemme 8.
10
- * EN: Implementation of reduction R3, associated with Lemma 8.
9
+ * @brief FR: Implementation de la reduction R3.
10
+ * EN: Implementation of reduction R3.
11
11
  *
12
12
  * FR: R3 traite les cas presque forces lorsque la classe pattern selectionnee
13
13
  * contient un seul noeud et que le partitionnement pattern laisse zero ou un
@@ -23,8 +23,6 @@ namespace FastMcSplit::Reductions
23
23
  * "do not match the pattern node" branch is useless or whether some nodes
24
24
  * must be temporarily excluded.
25
25
  *
26
- * @note FR: Mapping papier/code: lemme 8 -> classe `R3`.
27
- * EN: Paper/code mapping: Lemma 8 -> class `R3`.
28
26
  */
29
27
  class R3
30
28
  {
@@ -22,6 +22,7 @@
22
22
  #include <Reductions/r_utils.hpp>
23
23
  #include <numeric>
24
24
  #include <memory>
25
+ #include <atomic>
25
26
 
26
27
  namespace FastMcSplit
27
28
  {
@@ -50,6 +51,7 @@ namespace FastMcSplit
50
51
  node_id_t num_nodes_in_candidats; /**< FR: Nombre de voisins encore candidats apres partitionnement. EN: Number of neighbors still candidate after partitioning. */
51
52
  node_id_t cc_count;
52
53
  node_id_t old_class_size;
54
+ node_id_t num_discared_nodes;
53
55
  };
54
56
 
55
57
  /**
@@ -62,6 +64,11 @@ namespace FastMcSplit
62
64
  class SearchMatching
63
65
  {
64
66
  protected:
67
+ const std::atomic<bool>* abort_flag=nullptr;
68
+ bool abort_requested() const
69
+ {
70
+ return abort_flag && abort_flag->load(std::memory_order_relaxed);
71
+ }
65
72
  /**
66
73
  * @brief FR: Explore recursivement l'arbre de recherche.
67
74
  * EN: Recursively explores the search tree.
@@ -72,7 +79,7 @@ namespace FastMcSplit
72
79
  */
73
80
  void explore(const node_id_t k, node_id_t prev_ub=0)
74
81
  {
75
- if(k == pattern.size()) return;
82
+ if(abort_requested() || k == pattern.size()) return;
76
83
  // Bound phase: if even the optimistic completion cannot beat the
77
84
  // incumbent or the current goal, the whole subtree is useless.
78
85
  node_id_t ub = compute_bound_for_current_reward_strategy(prev_ub);
@@ -192,6 +199,7 @@ namespace FastMcSplit
192
199
  partionning_out t_result;
193
200
  for (auto& d_id : idx)
194
201
  {
202
+ if(abort_requested()) break;
195
203
  t_n_id = domain[d_id];
196
204
  if(t_n_id == -1) continue;
197
205
  if(r6.verify(p_n_id,t_n_id,p_class_equiv)) continue;
@@ -239,7 +247,8 @@ namespace FastMcSplit
239
247
  do_r4 &&
240
248
  p_result.cc_count == t_result.cc_count &&
241
249
  p_result.cc_count == p_result.old_class_size &&
242
- t_result.cc_count == t_result.old_class_size
250
+ t_result.cc_count == t_result.old_class_size &&
251
+ t_result.num_discared_nodes == 0
243
252
  )
244
253
  {
245
254
  not_explore_without_node=true;
@@ -594,6 +603,7 @@ namespace FastMcSplit
594
603
  result.num_nodes_in_candidats=0;
595
604
  result.old_class_size=0;
596
605
  result.cc_count=0;
606
+ result.num_discared_nodes=0;
597
607
  //
598
608
  const Node* node=pattern[p_node_id];
599
609
  //
@@ -1039,6 +1049,7 @@ namespace FastMcSplit
1039
1049
  result.num_nodes_in_candidats=0;
1040
1050
  result.cc_count=0;
1041
1051
  result.old_class_size=0;
1052
+ result.num_discared_nodes=0;
1042
1053
  //
1043
1054
  const Node* node=target[t_node_id];
1044
1055
  //
@@ -1137,6 +1148,7 @@ namespace FastMcSplit
1137
1148
  else
1138
1149
  {
1139
1150
  result.old_class_size=target.size();
1151
+ result.num_discared_nodes++;
1140
1152
  }
1141
1153
  //
1142
1154
  if(!present)
@@ -1149,6 +1161,8 @@ namespace FastMcSplit
1149
1161
  assert(node_info.domain_ind > curr_class.t_domain_ind_end);
1150
1162
  //
1151
1163
  if(t_not_in_solution_constraints[neigh_id]>0) result.valid=false;
1164
+ //
1165
+ result.num_discared_nodes++;
1152
1166
  }
1153
1167
  //
1154
1168
  //
@@ -2072,6 +2086,8 @@ namespace FastMcSplit
2072
2086
  return best_node;
2073
2087
  };
2074
2088
  public:
2089
+ void set_abort_flag(const std::atomic<bool>* flag) { abort_flag=flag; }
2090
+ const std::atomic<bool>* get_abort_flag() const { return abort_flag; }
2075
2091
  //friend class SearchMatchingTester;
2076
2092
  /** @name Graphes et domaines partages
2077
2093
  * FR: References vers les structures construites dans `FastMcSplit.cpp`.
@@ -2359,7 +2375,7 @@ namespace FastMcSplit
2359
2375
  for (goal_size = upper_bound; goal_size >= max_size; goal_size--)
2360
2376
  {
2361
2377
  explore(0);
2362
- if(goal_size==max_size) break;
2378
+ if(abort_requested() || goal_size==max_size) break;
2363
2379
  }
2364
2380
  }
2365
2381
  else
@@ -0,0 +1,44 @@
1
+ #ifndef SEARCH_TIMEOUT_HPP
2
+ #define SEARCH_TIMEOUT_HPP
3
+ #include <atomic>
4
+ #include <chrono>
5
+ #include <condition_variable>
6
+ #include <mutex>
7
+ #include <thread>
8
+
9
+ namespace FastMcSplit
10
+ {
11
+ // Owns the watchdog; destruction always wakes and joins it, even on exceptions.
12
+ class SearchTimeout
13
+ {
14
+ std::mutex mutex;
15
+ std::condition_variable cv;
16
+ bool finished=false;
17
+ std::thread worker;
18
+ public:
19
+ std::atomic<bool> expired{false};
20
+
21
+ explicit SearchTimeout(int seconds)
22
+ {
23
+ if(seconds<=0) return;
24
+ const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(seconds);
25
+ worker=std::thread([this,deadline] {
26
+ std::unique_lock<std::mutex> lock(mutex);
27
+ if(!cv.wait_until(lock,deadline,[this] { return finished; }))
28
+ expired.store(true,std::memory_order_relaxed);
29
+ });
30
+ }
31
+ void finish()
32
+ {
33
+ if(!worker.joinable()) return;
34
+ {
35
+ std::lock_guard<std::mutex> lock(mutex);
36
+ finished=true;
37
+ }
38
+ cv.notify_all();
39
+ worker.join();
40
+ }
41
+ ~SearchTimeout() { finish(); }
42
+ };
43
+ }
44
+ #endif
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "FastMcsplit"
7
- version = "0.0.2"
7
+ version = "0.0.3"
8
8
  description = "Native C++ maximum common induced subgraph solver for Python and NetworkX"
9
9
  readme = "python/README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: FastMcsplit
3
- Version: 0.0.2
3
+ Version: 0.0.3
4
4
  Summary: Native C++ maximum common induced subgraph solver for Python and NetworkX
5
5
  Author: Wilfried Agbeto, Camille Coti, Vladimir Reinharz
6
6
  Classifier: Development Status :: 5 - Production/Stable
@@ -117,6 +117,7 @@ The same keyword options work with all three interfaces.
117
117
  | `adaptive_rewards` | `False` | Use adaptive rewards as described in the C++ documentation. |
118
118
  | `heuristic` | `0` | Vertex ordering, name or ID below. |
119
119
  | `disabled_reductions` | `()` | Disable rules, e.g. `("R1", "R4")` or `(1, 4)`. R8 is currently inactive in the Python binding. |
120
+ | `timeout` | `1800` | Search budget in whole seconds, including greedy search; `0` disables it. |
120
121
  | `verbose` | `False` | Native diagnostic output to the process stdout. |
121
122
 
122
123
  Reward names: `capacity_diversity` (1), `pair_diversity` (2), `class_count` (3),
@@ -149,8 +150,19 @@ Every interface returns a `Result` containing one mapping:
149
150
  - `runtime`: native conversion/preprocessing/search time in seconds; excludes Python conversion.
150
151
  - `explored_nodes`: exact-search node count; zero in approximate-only mode.
151
152
  - `method`: `"exact"` or `"approximate"`.
153
+ - `timed_out`: whether the search budget expired; the best feasible mapping is returned.
152
154
 
153
- There is no timeout or cancellation option. Parallel edges are limited to
155
+
156
+ A timed out exact search has `optimal=False` unless its mapping reaches the
157
+ initial upper bound. For example:
158
+
159
+ ```python
160
+ result = fastmcsplit.solve(pattern, target, timeout=60)
161
+ if result.timed_out:
162
+ print("Time limit reached:", result.size)
163
+ ```
164
+
165
+ Parallel edges are limited to
154
166
  255 per direction, or 127 undirected loops per vertex.
155
167
 
156
168
  [solver]: https://gitlab.info.uqam.ca/agbeto.kossi_wilfried/fastmcsplit/-/blob/FastMcSplit/README.md
@@ -12,6 +12,7 @@ header/Node.hpp
12
12
  header/NodeAttr.hpp
13
13
  header/NodeNeighbor.hpp
14
14
  header/SearchMatching.hpp
15
+ header/SearchTimeout.hpp
15
16
  header/define.hpp
16
17
  header/time_utils.hpp
17
18
  header/utils.hpp
@@ -98,6 +98,7 @@ The same keyword options work with all three interfaces.
98
98
  | `adaptive_rewards` | `False` | Use adaptive rewards as described in the C++ documentation. |
99
99
  | `heuristic` | `0` | Vertex ordering, name or ID below. |
100
100
  | `disabled_reductions` | `()` | Disable rules, e.g. `("R1", "R4")` or `(1, 4)`. R8 is currently inactive in the Python binding. |
101
+ | `timeout` | `1800` | Search budget in whole seconds, including greedy search; `0` disables it. |
101
102
  | `verbose` | `False` | Native diagnostic output to the process stdout. |
102
103
 
103
104
  Reward names: `capacity_diversity` (1), `pair_diversity` (2), `class_count` (3),
@@ -130,8 +131,19 @@ Every interface returns a `Result` containing one mapping:
130
131
  - `runtime`: native conversion/preprocessing/search time in seconds; excludes Python conversion.
131
132
  - `explored_nodes`: exact-search node count; zero in approximate-only mode.
132
133
  - `method`: `"exact"` or `"approximate"`.
134
+ - `timed_out`: whether the search budget expired; the best feasible mapping is returned.
133
135
 
134
- There is no timeout or cancellation option. Parallel edges are limited to
136
+
137
+ A timed out exact search has `optimal=False` unless its mapping reaches the
138
+ initial upper bound. For example:
139
+
140
+ ```python
141
+ result = fastmcsplit.solve(pattern, target, timeout=60)
142
+ if result.timed_out:
143
+ print("Time limit reached:", result.size)
144
+ ```
145
+
146
+ Parallel edges are limited to
135
147
  255 per direction, or 127 undirected loops per vertex.
136
148
 
137
149
  [solver]: https://gitlab.info.uqam.ca/agbeto.kossi_wilfried/fastmcsplit/-/blob/FastMcSplit/README.md
@@ -1,5 +1,5 @@
1
1
  """Maximum common induced subgraphs using the native FastMcSplit engine."""
2
2
  from .api import Result, approximate, solve, solve_csv, solve_files
3
3
 
4
- __version__ = "0.0.2"
4
+ __version__ = "0.0.3"
5
5
  __all__ = ["Result", "solve", "solve_csv", "solve_files", "approximate"]
@@ -13,7 +13,7 @@ from . import _native
13
13
  class Result:
14
14
  """One feasible induced mapping from pattern nodes to target nodes.
15
15
 
16
- ``optimal`` is true after exact search, or when the approximation reaches
16
+ ``optimal`` is true after completed exact search, or when the solution reaches
17
17
  the initial upper bound. ``runtime`` is native time in seconds; it excludes
18
18
  Python conversion. ``explored_nodes`` counts exact-search nodes only.
19
19
  """
@@ -24,6 +24,7 @@ class Result:
24
24
  runtime: float
25
25
  explored_nodes: int
26
26
  method: str
27
+ timed_out: bool = False
27
28
 
28
29
  @property
29
30
  def size(self) -> int:
@@ -107,7 +108,11 @@ def _colors(values: list, equal: Callable | None) -> list[int]:
107
108
  def _solve(pattern: _Graph, target: _Graph, *, method="exact", connected=False,
108
109
  greedy=False, big_first=False, reward_strategy=None,
109
110
  adaptive_rewards=False, heuristic=0, disabled_reductions=(),
110
- verbose=False, node_label_eq_fn=None, edge_label_eq_fn=None) -> Result:
111
+ verbose=False, timeout=1800, node_label_eq_fn=None, edge_label_eq_fn=None) -> Result:
112
+ if type(timeout) is not int:
113
+ raise TypeError("timeout must be an integer number of seconds")
114
+ if not 0 <= timeout <= 2**31-1:
115
+ raise ValueError("timeout must be between 0 and 2**31-1 (0 disables the limit)")
111
116
  if method not in ("exact", "approximate"):
112
117
  raise ValueError("method must be 'exact' or 'approximate'")
113
118
  for name, value in (("connected", connected), ("greedy", greedy),
@@ -139,7 +144,7 @@ def _solve(pattern: _Graph, target: _Graph, *, method="exact", connected=False,
139
144
  encode(target, nc[pn:], ec[pe:]), pattern.directed,
140
145
  method == "approximate", greedy, connected, big_first,
141
146
  verbose, adaptive_rewards, reward, ordering, mask,
142
- len(set(nc)) > 1 or any(e[2] is not None for e in pattern.edges + target.edges))
147
+ len(set(nc)) > 1 or any(e[2] is not None for e in pattern.edges + target.edges), timeout)
143
148
  mapping = {pattern.nodes[u]: target.nodes[v] for u, v in raw.pop("pairs")}
144
149
  return Result(mapping=mapping, method=method, **raw)
145
150
 
@@ -168,19 +173,23 @@ def _networkx(graph, node_label_key, edge_label_key):
168
173
  def solve(pattern, target, *, node_label_key=None, edge_label_key=None,
169
174
  node_label_eq_fn=None, edge_label_eq_fn=None, method="exact",
170
175
  connected=False, greedy=False, big_first=False, reward_strategy=None,
171
- adaptive_rewards=False, heuristic=0, disabled_reductions=(), verbose=False) -> Result:
176
+ adaptive_rewards=False, heuristic=0, disabled_reductions=(), verbose=False,
177
+ timeout=1800) -> Result:
172
178
  """Find one maximum common induced subgraph of two NetworkX graphs.
173
179
 
174
180
  All four NetworkX graph classes are supported. Original node objects are
175
181
  preserved in ``result.mapping``. Labels are ignored unless a key is supplied.
176
182
  Use ``method='approximate'`` to skip the exact search entirely.
183
+ ``timeout`` limits search to 1800 seconds by default; 0 disables the limit.
184
+ Expiration returns the incumbent with ``result.timed_out=True``.
177
185
  """
178
186
  return _solve(_networkx(pattern, node_label_key, edge_label_key),
179
187
  _networkx(target, node_label_key, edge_label_key),
180
188
  node_label_eq_fn=node_label_eq_fn, edge_label_eq_fn=edge_label_eq_fn,
181
189
  method=method, connected=connected, greedy=greedy, big_first=big_first,
182
190
  reward_strategy=reward_strategy, adaptive_rewards=adaptive_rewards,
183
- heuristic=heuristic, disabled_reductions=disabled_reductions, verbose=verbose)
191
+ heuristic=heuristic, disabled_reductions=disabled_reductions, verbose=verbose,
192
+ timeout=timeout)
184
193
 
185
194
 
186
195
  def approximate(pattern, target, **options) -> Result:
@@ -13,6 +13,7 @@
13
13
  #include <vector>
14
14
  #include <Graph.hpp>
15
15
  #include <SearchMatching.hpp>
16
+ #include <SearchTimeout.hpp>
16
17
  #include <GreedySearchMatching.hpp>
17
18
  #include <NodeClasses/NodeClassCompute.hpp>
18
19
 
@@ -204,13 +205,14 @@ struct Output {
204
205
  node_id_t upper_bound=0;
205
206
  size_t nodes=0;
206
207
  bool optimal=false;
208
+ bool timed_out=false;
207
209
  double runtime=0;
208
210
  };
209
211
 
210
212
  template<class Comparator>
211
213
  Output run(Graph& p, Graph& t, bool approximate, bool greedy, bool connected,
212
214
  bool big_first, bool verbose, bool adaptive, int reward, int heuristic,
213
- const std::array<bool,8>& rules, bool labelled) {
215
+ const std::array<bool,8>& rules, bool labelled, int timeout_seconds) {
214
216
  Output result;
215
217
  if (!p.size() || !t.size()) { result.optimal=true; return result; }
216
218
  std::vector<NodeClasses::NodeClass> classes;
@@ -238,22 +240,27 @@ Output run(Graph& p, Graph& t, bool approximate, bool greedy, bool connected,
238
240
  intervals,te,tel,pe,pel,dominations,
239
241
  rules[0],rules[1],rules[2],rules[3],rules[4],rules[5],rules[6],0*rules[7],
240
242
  connected,big_first,labelled,verbose,adaptive,reward,heuristic);
243
+ SearchTimeout timeout(timeout_seconds);
244
+ solver.set_abort_flag(&timeout.expired);
241
245
  if (greedy || approximate) GreedySearchMatching<Comparator>(solver).search(result.upper_bound);
242
246
  if (!approximate) solver.search_matching(result.upper_bound);
247
+ timeout.finish();
248
+ result.timed_out=timeout.expired.load(std::memory_order_relaxed);
243
249
  result.mapping=solver.max_sol;
244
250
  result.nodes=solver.num_nodes;
245
- result.optimal=!approximate || result.mapping.size()==result.upper_bound;
251
+ result.optimal=(!approximate && !result.timed_out) || result.mapping.size()==result.upper_bound;
246
252
  return result;
247
253
  }
248
254
 
249
255
  PyObject* solve_native(PyObject*, PyObject* args) {
250
256
  PyObject *p_object,*t_object;
251
257
  int directed,approximate,greedy,connected,big_first,verbose,adaptive,reward,heuristic,mask,labelled;
252
- if (!PyArg_ParseTuple(args,"OOpppppppiiip",&p_object,&t_object,&directed,
253
- &approximate,&greedy,&connected,&big_first,&verbose,&adaptive,&reward,&heuristic,&mask,&labelled)) return nullptr;
258
+ int timeout_seconds=1800;
259
+ if (!PyArg_ParseTuple(args,"OOpppppppiiip|i",&p_object,&t_object,&directed,
260
+ &approximate,&greedy,&connected,&big_first,&verbose,&adaptive,&reward,&heuristic,&mask,&labelled,&timeout_seconds)) return nullptr;
254
261
  try {
255
262
  Input p=read_input(p_object),t=read_input(t_object);
256
- if (reward<0 || reward>4 || heuristic<0 || heuristic>1 || mask<0 || mask>255)
263
+ if (reward<0 || reward>4 || heuristic<0 || heuristic>1 || mask<0 || mask>255 || timeout_seconds<0)
257
264
  throw std::invalid_argument("Invalid native solver option");
258
265
  std::array<bool,8> rules;
259
266
  for (unsigned i=0;i<8;++i) rules[i]=!(mask&(1<<i));
@@ -266,9 +273,9 @@ PyObject* solve_native(PyObject*, PyObject* args) {
266
273
  NativeGraph pg(p.colors.size()),tg(t.colors.size());
267
274
  build_graph(pg,p,directed); build_graph(tg,t,directed);
268
275
  if (directed) result=run<CompareEdgeAttr>(pg.graph,tg.graph,approximate,greedy,
269
- connected,big_first,verbose,adaptive,reward,heuristic,rules,labelled);
276
+ connected,big_first,verbose,adaptive,reward,heuristic,rules,labelled,timeout_seconds);
270
277
  else result=run<CompareUndirectedEdgeAttr>(pg.graph,tg.graph,approximate,greedy,
271
- connected,big_first,verbose,adaptive,reward,heuristic,rules,labelled);
278
+ connected,big_first,verbose,adaptive,reward,heuristic,rules,labelled,timeout_seconds);
272
279
  result.runtime=std::chrono::duration<double>(std::chrono::steady_clock::now()-start).count();
273
280
  } catch (...) { failure=std::current_exception(); }
274
281
  PyEval_RestoreThread(state);
@@ -280,9 +287,9 @@ PyObject* solve_native(PyObject*, PyObject* args) {
280
287
  if (!pair) throw PythonError{};
281
288
  PyList_SET_ITEM(pairs.value,i,pair);
282
289
  }
283
- return Py_BuildValue("{s:O,s:I,s:n,s:O,s:d}","pairs",pairs.value,
290
+ return Py_BuildValue("{s:O,s:I,s:n,s:O,s:d,s:O}","pairs",pairs.value,
284
291
  "upper_bound",result.upper_bound,"explored_nodes",static_cast<Py_ssize_t>(result.nodes),
285
- "optimal",result.optimal?Py_True:Py_False,"runtime",result.runtime);
292
+ "optimal",result.optimal?Py_True:Py_False,"runtime",result.runtime,"timed_out",result.timed_out?Py_True:Py_False);
286
293
  } catch (const PythonError&) { return nullptr; }
287
294
  catch (const std::bad_alloc&) { return PyErr_NoMemory(); }
288
295
  catch (const std::invalid_argument& e) { PyErr_SetString(PyExc_ValueError,e.what()); }
@@ -11,5 +11,6 @@ setup(ext_modules=[Extension(
11
11
  sources=["python/native.cpp"],
12
12
  include_dirs=["header", "args"],
13
13
  language="c++",
14
- extra_compile_args=["-std=c++17", "-O3"],
14
+ extra_compile_args=["-std=c++17", "-O3", "-pthread"],
15
+ extra_link_args=["-pthread"],
15
16
  )])
@@ -249,3 +249,54 @@ def test_custom_edge_equivalence():
249
249
  t.add_edge("a", "b", color="red")
250
250
  assert fm.solve(p, t, edge_label_key="color").size == 1
251
251
  assert fm.solve(p, t, edge_label_key="color", edge_label_eq_fn=lambda a,b: a.lower() == b.lower()).size == 2
252
+
253
+
254
+ @pytest.mark.parametrize("timeout", [-1, 2**31, True, None, 1.5, "60"])
255
+ def test_invalid_timeout(timeout):
256
+ with pytest.raises((TypeError, ValueError), match="timeout"):
257
+ fm.solve_csv("0", "0", timeout=timeout)
258
+
259
+
260
+ def test_timeout_default_forwarded(monkeypatch, tmp_path):
261
+ from fastmcsplit import api
262
+ budgets = []
263
+ def native(*args):
264
+ budgets.append(args[-1])
265
+ return dict(pairs=[], optimal=True, upper_bound=0, runtime=0,
266
+ explored_nodes=0, timed_out=False)
267
+ monkeypatch.setattr(api._native, "solve", native)
268
+ fm.solve_csv("0", "0")
269
+ fm.solve(nx.Graph(), nx.Graph())
270
+ fm.approximate(nx.Graph(), nx.Graph())
271
+ graph_file = tmp_path / "empty.lad"
272
+ graph_file.write_text("0")
273
+ fm.solve_files(graph_file, graph_file, format="lad")
274
+ fm.solve_csv("0", "0", timeout=0)
275
+ assert budgets == [1800, 1800, 1800, 1800, 0]
276
+
277
+
278
+ @pytest.mark.parametrize("timeout", [0, 1800])
279
+ def test_search_finishes_before_timeout(timeout):
280
+ result = fm.solve(nx.path_graph(4), nx.path_graph(5), timeout=timeout)
281
+ assert result.optimal and result.size == 4 and not result.timed_out
282
+
283
+
284
+ @pytest.mark.parametrize("options", [{}, {"big_first": True}, {"greedy": True},
285
+ {"method": "approximate"}])
286
+ def test_timeout_returns_feasible_incumbent(options):
287
+ import time
288
+ # Dense independent random graphs keep both exact and diversified greedy
289
+ # search busy, while remaining small enough for quick preprocessing.
290
+ n = 600 if options.get("method") == "approximate" else 180
291
+ p = nx.gnp_random_graph(n, 0.5, seed=123, directed=True)
292
+ t = nx.gnp_random_graph(n, 0.5, seed=456, directed=True)
293
+ start = time.monotonic()
294
+ result = fm.solve(p, t, timeout=1, **options)
295
+ elapsed = time.monotonic() - start
296
+ assert result.timed_out and not result.optimal
297
+ assert result.size > 0
298
+ assert valid(p, t, result.mapping)
299
+ assert result.size <= result.upper_bound
300
+ assert 0.9 <= elapsed < 10
301
+ if options.get("method") == "approximate":
302
+ assert result.explored_nodes == 0
File without changes
File without changes
File without changes
File without changes