21 #include "absl/memory/memory.h"
22 #include "absl/status/status.h"
23 #include "absl/strings/str_format.h"
24 #include "absl/strings/str_join.h"
25 #include "absl/time/clock.h"
26 #include "absl/time/time.h"
35 ABSL_FLAG(
bool, minimize_permutation_support_size,
false,
36 "Tweak the algorithm to try and minimize the support size"
37 " of the generators produced. This may negatively impact the"
38 " performance, but works great on the sat_holeXXX benchmarks"
39 " to reduce the support size.");
47 void SwapFrontAndBack(std::vector<int>* v) {
52 bool PartitionsAreCompatibleAfterPartIndex(
const DynamicPartition& p1,
53 const DynamicPartition& p2,
55 const int num_parts = p1.NumParts();
56 if (p2.NumParts() != num_parts)
return false;
57 for (
int p = part_index; p < num_parts; ++p) {
58 if (p1.SizeOfPart(p) != p2.SizeOfPart(p) ||
59 p1.ParentOfPart(p) != p2.ParentOfPart(p)) {
75 bool ListMapsToList(
const List& l1,
const List& l2,
76 const DynamicPermutation& permutation,
77 std::vector<bool>* tmp_node_mask) {
78 int num_elements_delta = 0;
80 for (
const int mapped_x : l2) {
82 (*tmp_node_mask)[mapped_x] =
true;
84 for (
const int x : l1) {
86 const int mapped_x = permutation.ImageOf(x);
87 if (!(*tmp_node_mask)[mapped_x]) {
91 (*tmp_node_mask)[mapped_x] =
false;
93 if (num_elements_delta != 0) match =
false;
96 for (
const int x : l2) (*tmp_node_mask)[x] =
false;
104 tmp_dynamic_permutation_(NumNodes()),
105 tmp_node_mask_(NumNodes(), false),
106 tmp_degree_(NumNodes(), 0),
107 tmp_nodes_with_degree_(NumNodes() + 1) {
109 time_limit_ = &dummy_time_limit_;
110 tmp_partition_.
Reset(NumNodes());
117 reverse_adj_list_index_.assign(graph.
num_nodes() + 2, 0);
118 for (
const int node : graph.
AllNodes()) {
120 ++reverse_adj_list_index_[graph.
Head(arc) + 2];
126 std::partial_sum(reverse_adj_list_index_.begin() + 2,
127 reverse_adj_list_index_.end(),
128 reverse_adj_list_index_.begin() + 2);
132 flattened_reverse_adj_lists_.assign(graph.
num_arcs(), -1);
133 for (
const int node : graph.
AllNodes()) {
135 flattened_reverse_adj_lists_[reverse_adj_list_index_[graph.
Head(arc) +
144 for (
const int i : flattened_reverse_adj_lists_)
DCHECK_NE(i, -1);
152 const int image = permutation.
ImageOf(base);
153 if (image == base)
continue;
154 if (!ListMapsToList(graph_[base], graph_[image], permutation,
159 if (!reverse_adj_list_index_.empty()) {
163 const int image = permutation.
ImageOf(base);
164 if (image == base)
continue;
165 if (!ListMapsToList(TailsOfIncomingArcsTo(base),
166 TailsOfIncomingArcsTo(image), permutation,
179 inline void IncrementCounterForNonSingletons(
const T&
nodes,
181 std::vector<int>* node_count,
182 std::vector<int>* nodes_seen,
183 int64_t* num_operations) {
184 *num_operations +=
nodes.end() -
nodes.begin();
185 for (
const int node :
nodes) {
187 const int count = ++(*node_count)[node];
188 if (count == 1) nodes_seen->push_back(node);
196 std::vector<int>& tmp_nodes_with_nonzero_degree = tmp_stack_;
205 int64_t num_operations = 0;
218 std::vector<bool> adjacency_directions(1,
true);
219 if (!reverse_adj_list_index_.empty()) {
220 adjacency_directions.push_back(
false);
222 for (
int part_index = first_unrefined_part_index;
225 for (
const bool outgoing_adjacency : adjacency_directions) {
228 if (outgoing_adjacency) {
230 IncrementCounterForNonSingletons(
231 graph_[node], *partition, &tmp_degree_,
232 &tmp_nodes_with_nonzero_degree, &num_operations);
236 IncrementCounterForNonSingletons(
237 TailsOfIncomingArcsTo(node), *partition, &tmp_degree_,
238 &tmp_nodes_with_nonzero_degree, &num_operations);
243 num_operations += 3 + tmp_nodes_with_nonzero_degree.size();
244 for (
const int node : tmp_nodes_with_nonzero_degree) {
245 const int degree = tmp_degree_[node];
246 tmp_degree_[node] = 0;
247 max_degree =
std::max(max_degree, degree);
248 tmp_nodes_with_degree_[degree].push_back(node);
250 tmp_nodes_with_nonzero_degree.clear();
253 for (
int degree = 1; degree <= max_degree; ++degree) {
256 num_operations += 1 + 3 * tmp_nodes_with_degree_[degree].size();
257 partition->
Refine(tmp_nodes_with_degree_[degree]);
258 tmp_nodes_with_degree_[degree].clear();
267 static_cast<double>(num_operations));
272 const int original_num_parts = partition->
NumParts();
273 partition->
Refine(std::vector<int>(1, node));
277 if (new_singletons !=
nullptr) {
278 new_singletons->clear();
279 for (
int p = original_num_parts; p < partition->
NumParts(); ++p) {
283 if (!tmp_node_mask_[parent] && parent < original_num_parts &&
285 tmp_node_mask_[parent] =
true;
293 for (
int p = original_num_parts; p < partition->
NumParts(); ++p) {
300 void MergeNodeEquivalenceClassesAccordingToPermutation(
303 for (
int c = 0; c < perm.
NumCycles(); ++c) {
306 for (
const int e : perm.
Cycle(c)) {
308 const int removed_representative =
310 if (sorted_representatives !=
nullptr && removed_representative != -1) {
311 sorted_representatives->
Remove(removed_representative);
331 void GetAllOtherRepresentativesInSamePartAs(
332 int representative_node,
const DynamicPartition& partition,
333 const DenseDoublyLinkedList& representatives_sorted_by_index_in_partition,
334 MergingPartition* node_equivalence_classes,
335 std::vector<int>* pruned_other_nodes) {
336 pruned_other_nodes->clear();
337 const int part_index = partition.PartOf(representative_node);
339 int repr = representative_node;
341 DCHECK_EQ(repr, node_equivalence_classes->GetRoot(repr));
342 repr = representatives_sorted_by_index_in_partition.Prev(repr);
343 if (repr < 0 || partition.PartOf(repr) != part_index)
break;
344 pruned_other_nodes->push_back(repr);
347 repr = representative_node;
349 DCHECK_EQ(repr, node_equivalence_classes->GetRoot(repr));
350 repr = representatives_sorted_by_index_in_partition.Next(repr);
351 if (repr < 0 || partition.PartOf(repr) != part_index)
break;
352 pruned_other_nodes->push_back(repr);
360 std::vector<int> expected_output;
361 for (
const int e : partition.ElementsInPart(part_index)) {
362 if (node_equivalence_classes->GetRoot(e) != representative_node) {
363 expected_output.push_back(e);
366 node_equivalence_classes->KeepOnlyOneNodePerPart(&expected_output);
367 for (
int& x : expected_output) x = node_equivalence_classes->GetRoot(x);
368 std::sort(expected_output.begin(), expected_output.end());
369 std::vector<int> sorted_output = *pruned_other_nodes;
370 std::sort(sorted_output.begin(), sorted_output.end());
371 DCHECK_EQ(absl::StrJoin(expected_output,
" "),
372 absl::StrJoin(sorted_output,
" "));
378 std::vector<int>* node_equivalence_classes_io,
379 std::vector<std::unique_ptr<SparsePermutation>>* generators,
380 std::vector<int>* factorized_automorphism_group_size,
386 factorized_automorphism_group_size->clear();
387 if (node_equivalence_classes_io->size() != NumNodes()) {
388 return absl::Status(absl::StatusCode::kInvalidArgument,
389 "Invalid 'node_equivalence_classes_io'.");
399 return absl::Status(absl::StatusCode::kDeadlineExceeded,
400 "During the initial refinement.");
402 VLOG(4) <<
"Base partition: "
406 std::vector<std::vector<int>> permutations_displacing_node(NumNodes());
407 std::vector<int> potential_root_image_nodes;
430 struct InvariantDiveState {
432 int num_parts_before_refinement;
434 InvariantDiveState(
int node,
int num_parts)
435 : invariant_node(node), num_parts_before_refinement(num_parts) {}
437 std::vector<InvariantDiveState> invariant_dive_stack;
444 for (
int invariant_node = 0; invariant_node < NumNodes(); ++invariant_node) {
448 invariant_dive_stack.push_back(
449 InvariantDiveState(invariant_node, base_partition.
NumParts()));
451 VLOG(4) <<
"Invariant dive: invariant node = " << invariant_node
452 <<
"; partition after: "
455 return absl::Status(absl::StatusCode::kDeadlineExceeded,
456 "During the invariant dive.");
467 while (!invariant_dive_stack.empty()) {
471 const int root_node = invariant_dive_stack.back().invariant_node;
472 const int base_num_parts =
473 invariant_dive_stack.back().num_parts_before_refinement;
474 invariant_dive_stack.pop_back();
477 VLOG(4) <<
"Backtracking invariant dive: root node = " << root_node
502 GetAllOtherRepresentativesInSamePartAs(
503 root_node, base_partition, representatives_sorted_by_index_in_partition,
504 &node_equivalence_classes, &potential_root_image_nodes);
505 DCHECK(!potential_root_image_nodes.empty());
506 IF_STATS_ENABLED(stats_.invariant_unroll_time.StopTimerAndAddElapsedTime());
510 while (!potential_root_image_nodes.empty()) {
512 VLOG(4) <<
"Potential (pruned) images of root node " << root_node
513 <<
" left: [" << absl::StrJoin(potential_root_image_nodes,
" ")
515 const int root_image_node = potential_root_image_nodes.back();
516 VLOG(4) <<
"Trying image of root node: " << root_image_node;
518 std::unique_ptr<SparsePermutation> permutation =
519 FindOneSuitablePermutation(root_node, root_image_node,
520 &base_partition, &image_partition,
521 *generators, permutations_displacing_node);
523 if (permutation !=
nullptr) {
528 MergeNodeEquivalenceClassesAccordingToPermutation(
529 *permutation, &node_equivalence_classes,
530 &representatives_sorted_by_index_in_partition);
535 SwapFrontAndBack(&potential_root_image_nodes);
537 &potential_root_image_nodes);
538 SwapFrontAndBack(&potential_root_image_nodes);
541 const int permutation_index =
static_cast<int>(generators->size());
542 for (
const int node : permutation->Support()) {
543 permutations_displacing_node[node].push_back(permutation_index);
548 generators->push_back(std::move(permutation));
551 potential_root_image_nodes.pop_back();
557 factorized_automorphism_group_size->push_back(
565 return absl::Status(absl::StatusCode::kDeadlineExceeded,
566 "Some automorphisms were found, but probably not all.");
568 return ::absl::OkStatus();
579 int part_index,
int* base_node,
int* image_node) {
593 if (absl::GetFlag(FLAGS_minimize_permutation_support_size)) {
595 for (
const int node : base_partition.
ElementsInPart(part_index)) {
596 if (image_partition.
PartOf(node) == part_index) {
597 *image_node = *base_node = node;
608 if (image_partition.
PartOf(*base_node) == part_index) {
609 *image_node = *base_node;
619 std::unique_ptr<SparsePermutation>
620 GraphSymmetryFinder::FindOneSuitablePermutation(
621 int root_node,
int root_image_node, DynamicPartition* base_partition,
622 DynamicPartition* image_partition,
623 const std::vector<std::unique_ptr<SparsePermutation>>&
624 generators_found_so_far,
625 const std::vector<std::vector<int>>& permutations_displacing_node) {
631 DCHECK(search_states_.empty());
634 std::vector<int> base_singletons;
635 std::vector<int> image_singletons;
638 int min_potential_mismatching_part_index;
639 std::vector<int> next_potential_image_nodes;
643 search_states_.emplace_back(
645 base_partition->NumParts(),
646 base_partition->NumParts());
648 search_states_.back().remaining_pruned_image_nodes.assign(1, root_image_node);
653 while (!search_states_.empty()) {
665 const SearchState& ss = search_states_.back();
666 const int image_node = ss.first_image_node >= 0
667 ? ss.first_image_node
668 : ss.remaining_pruned_image_nodes.back();
672 DCHECK_EQ(ss.num_parts_before_trying_to_map_base_node,
673 image_partition->NumParts());
682 VLOG(4) << ss.DebugString();
699 bool compatible =
true;
702 compatible = PartitionsAreCompatibleAfterPartIndex(
703 *base_partition, *image_partition,
704 ss.num_parts_before_trying_to_map_base_node);
705 u.AlsoUpdate(compatible ? &stats_.quick_compatibility_success_time
706 : &stats_.quick_compatibility_fail_time);
708 bool partitions_are_full_match =
false;
712 &stats_.dynamic_permutation_refinement_time);
713 tmp_dynamic_permutation_.
AddMappings(base_singletons, image_singletons);
716 min_potential_mismatching_part_index =
717 ss.min_potential_mismatching_part_index;
718 partitions_are_full_match = ConfirmFullMatchOrFindNextMappingDecision(
719 *base_partition, *image_partition, tmp_dynamic_permutation_,
720 &min_potential_mismatching_part_index, &next_base_node,
722 u.AlsoUpdate(partitions_are_full_match
723 ? &stats_.map_election_std_full_match_time
724 : &stats_.map_election_std_mapping_time);
726 if (compatible && partitions_are_full_match) {
727 DCHECK_EQ(min_potential_mismatching_part_index,
728 base_partition->NumParts());
734 bool is_automorphism =
true;
738 u.AlsoUpdate(is_automorphism ? &stats_.automorphism_test_success_time
739 : &stats_.automorphism_test_fail_time);
741 if (is_automorphism) {
745 std::unique_ptr<SparsePermutation> sparse_permutation(
747 VLOG(4) <<
"Automorphism found: " << sparse_permutation->DebugString();
748 const int base_num_parts =
749 search_states_[0].num_parts_before_trying_to_map_base_node;
750 base_partition->UndoRefineUntilNumPartsEqual(base_num_parts);
751 image_partition->UndoRefineUntilNumPartsEqual(base_num_parts);
752 tmp_dynamic_permutation_.
Reset();
753 search_states_.clear();
755 search_time_updater.AlsoUpdate(&stats_.search_time_success);
756 return sparse_permutation;
762 VLOG(4) <<
"Permutation candidate isn't a valid automorphism.";
763 if (base_partition->NumParts() == NumNodes()) {
774 int non_singleton_part = 0;
777 while (base_partition->SizeOfPart(non_singleton_part) == 1) {
778 ++non_singleton_part;
779 DCHECK_LT(non_singleton_part, base_partition->NumParts());
783 1e-9 *
static_cast<double>(non_singleton_part));
787 GetBestMapping(*base_partition, *image_partition, non_singleton_part,
788 &next_base_node, &next_image_node);
803 while (!search_states_.empty()) {
804 SearchState*
const last_ss = &search_states_.back();
805 image_partition->UndoRefineUntilNumPartsEqual(
806 last_ss->num_parts_before_trying_to_map_base_node);
807 if (last_ss->first_image_node >= 0) {
820 const int part = image_partition->PartOf(last_ss->first_image_node);
821 last_ss->remaining_pruned_image_nodes.reserve(
822 image_partition->SizeOfPart(part));
823 last_ss->remaining_pruned_image_nodes.push_back(
824 last_ss->first_image_node);
825 for (
const int e : image_partition->ElementsInPart(part)) {
826 if (e != last_ss->first_image_node) {
827 last_ss->remaining_pruned_image_nodes.push_back(e);
832 PruneOrbitsUnderPermutationsCompatibleWithPartition(
833 *image_partition, generators_found_so_far,
834 permutations_displacing_node[last_ss->first_image_node],
835 &last_ss->remaining_pruned_image_nodes);
837 SwapFrontAndBack(&last_ss->remaining_pruned_image_nodes);
838 DCHECK_EQ(last_ss->remaining_pruned_image_nodes.back(),
839 last_ss->first_image_node);
840 last_ss->first_image_node = -1;
842 last_ss->remaining_pruned_image_nodes.pop_back();
843 if (!last_ss->remaining_pruned_image_nodes.empty())
break;
845 VLOG(4) <<
"Backtracking one level up.";
846 base_partition->UndoRefineUntilNumPartsEqual(
847 last_ss->num_parts_before_trying_to_map_base_node);
852 search_states_.pop_back();
861 VLOG(4) <<
" Deepening the search.";
862 search_states_.emplace_back(
863 next_base_node, next_image_node,
864 base_partition->NumParts(),
865 min_potential_mismatching_part_index);
873 search_time_updater.AlsoUpdate(&stats_.search_time_fail);
878 GraphSymmetryFinder::TailsOfIncomingArcsTo(
int node)
const {
880 flattened_reverse_adj_lists_.begin() + reverse_adj_list_index_[node],
881 flattened_reverse_adj_lists_.begin() + reverse_adj_list_index_[node + 1]);
884 void GraphSymmetryFinder::PruneOrbitsUnderPermutationsCompatibleWithPartition(
885 const DynamicPartition& partition,
886 const std::vector<std::unique_ptr<SparsePermutation>>& permutations,
887 const std::vector<int>& permutation_indices, std::vector<int>*
nodes) {
888 VLOG(4) <<
" Pruning [" << absl::StrJoin(*
nodes,
", ") <<
"]";
895 if (
nodes->size() <= 1)
return;
900 std::vector<int>& tmp_nodes_on_support =
902 DCHECK(tmp_nodes_on_support.empty());
906 for (
const int p : permutation_indices) {
907 const SparsePermutation& permutation = *permutations[p];
910 bool compatible =
true;
911 for (
int c = 0; c < permutation.NumCycles(); ++c) {
912 const SparsePermutation::Iterator cycle = permutation.Cycle(c);
914 partition.SizeOfPart(partition.PartOf(*cycle.begin()))) {
919 if (!compatible)
continue;
922 for (
int c = 0; c < permutation.NumCycles(); ++c) {
924 for (
const int node : permutation.Cycle(c)) {
925 if (partition.PartOf(node) != part) {
930 part = partition.PartOf(node);
934 if (!compatible)
continue;
937 MergeNodeEquivalenceClassesAccordingToPermutation(permutation,
938 &tmp_partition_,
nullptr);
939 for (
const int node : permutation.Support()) {
940 if (!tmp_node_mask_[node]) {
941 tmp_node_mask_[node] =
true;
942 tmp_nodes_on_support.push_back(node);
951 for (
const int node : tmp_nodes_on_support) {
952 tmp_node_mask_[node] =
false;
955 tmp_nodes_on_support.clear();
956 VLOG(4) <<
" Pruned: [" << absl::StrJoin(*
nodes,
", ") <<
"]";
959 bool GraphSymmetryFinder::ConfirmFullMatchOrFindNextMappingDecision(
960 const DynamicPartition& base_partition,
961 const DynamicPartition& image_partition,
962 const DynamicPermutation& current_permutation_candidate,
963 int* min_potential_mismatching_part_index_io,
int* next_base_node,
964 int* next_image_node)
const {
965 *next_base_node = -1;
966 *next_image_node = -1;
970 if (!absl::GetFlag(FLAGS_minimize_permutation_support_size)) {
974 for (
const int loose_node : current_permutation_candidate.LooseEnds()) {
975 DCHECK_GT(base_partition.ElementsInSamePartAs(loose_node).size(), 1);
976 *next_base_node = loose_node;
977 const int root = current_permutation_candidate.RootOf(loose_node);
979 if (image_partition.PartOf(root) == base_partition.PartOf(loose_node)) {
982 *next_image_node = root;
986 if (*next_base_node != -1) {
991 .ElementsInPart(base_partition.PartOf(*next_base_node))
1007 const int initial_min_potential_mismatching_part_index =
1008 *min_potential_mismatching_part_index_io;
1009 for (; *min_potential_mismatching_part_index_io < base_partition.NumParts();
1010 ++*min_potential_mismatching_part_index_io) {
1011 const int p = *min_potential_mismatching_part_index_io;
1012 if (base_partition.SizeOfPart(p) != 1 &&
1013 base_partition.FprintOfPart(p) != image_partition.FprintOfPart(p)) {
1014 GetBestMapping(base_partition, image_partition, p, next_base_node,
1019 const int parent = base_partition.ParentOfPart(p);
1020 if (parent < initial_min_potential_mismatching_part_index &&
1021 base_partition.SizeOfPart(parent) != 1 &&
1022 base_partition.FprintOfPart(parent) !=
1023 image_partition.FprintOfPart(parent)) {
1024 GetBestMapping(base_partition, image_partition, parent, next_base_node,
1033 for (
int p = 0; p < base_partition.NumParts(); ++p) {
1034 if (base_partition.SizeOfPart(p) != 1) {
1035 CHECK_EQ(base_partition.FprintOfPart(p),
1036 image_partition.FprintOfPart(p));
1043 std::string GraphSymmetryFinder::SearchState::DebugString()
const {
1044 return absl::StrFormat(
1045 "SearchState{ base_node=%d, first_image_node=%d,"
1046 " remaining_pruned_image_nodes=[%s],"
1047 " num_parts_before_trying_to_map_base_node=%d }",
1048 base_node, first_image_node,
1049 absl::StrJoin(remaining_pruned_image_nodes,
" "),
1050 num_parts_before_trying_to_map_base_node);
#define DCHECK_NE(val1, val2)
#define CHECK_EQ(val1, val2)
#define DCHECK_GT(val1, val2)
#define DCHECK_LT(val1, val2)
#define DCHECK(condition)
#define DCHECK_EQ(val1, val2)
#define VLOG(verboselevel)
IterablePart ElementsInPart(int i) const
void Refine(const std::vector< int > &distinguished_subset)
const std::vector< int > & ElementsInHierarchicalOrder() const
int SizeOfPart(int part) const
void UndoRefineUntilNumPartsEqual(int original_num_parts)
IterablePart ElementsInSamePartAs(int i) const
int PartOf(int element) const
int ParentOfPart(int part) const
std::string DebugString(DebugStringSorting sorting) const
const int NumParts() const
std::unique_ptr< SparsePermutation > CreateSparsePermutation() const
std::string DebugString() const
const std::vector< int > & AllMappingsSrc() const
void UndoLastMappings(std::vector< int > *undone_mapping_src)
void AddMappings(const std::vector< int > &src, const std::vector< int > &dst)
void RecursivelyRefinePartitionByAdjacency(int first_unrefined_part_index, DynamicPartition *partition)
bool IsGraphAutomorphism(const DynamicPermutation &permutation) const
void DistinguishNodeInPartition(int node, DynamicPartition *partition, std::vector< int > *new_singletons_or_null)
absl::Status FindSymmetries(std::vector< int > *node_equivalence_classes_io, std::vector< std::unique_ptr< SparsePermutation > > *generators, std::vector< int > *factorized_automorphism_group_size, TimeLimit *time_limit=nullptr)
GraphSymmetryFinder(const Graph &graph, bool is_undirected)
int NumNodesInSamePartAs(int node)
void Reset(int num_nodes)
int MergePartsOf(int node1, int node2)
int FillEquivalenceClasses(std::vector< int > *node_equivalence_classes)
void KeepOnlyOneNodePerPart(std::vector< int > *nodes)
Iterator Cycle(int i) const
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
bool LimitReached()
Returns true when the external limit is true, or the deterministic time is over the deterministic lim...
void AdvanceDeterministicTime(double deterministic_duration)
Advances the deterministic time.
ArcIndexType num_arcs() const
NodeIndexType num_nodes() const
IntegerRange< NodeIndex > AllNodes() const
NodeIndexType Head(ArcIndexType arc) const
BeginEndWrapper< OutgoingArcIterator > OutgoingArcs(NodeIndexType node) const
SharedTimeLimit * time_limit
ABSL_FLAG(bool, minimize_permutation_support_size, false, "Tweak the algorithm to try and minimize the support size" " of the generators produced. This may negatively impact the" " performance, but works great on the sat_holeXXX benchmarks" " to reduce the support size.")
void swap(IdMap< K, V > &a, IdMap< K, V > &b)
Collection of objects used to extend the Constraint Solver library.
DisabledScopedTimeDistributionUpdater ScopedTimeDistributionUpdater
bool GraphIsSymmetric(const Graph &graph)
#define IF_STATS_ENABLED(instructions)
std::vector< int >::const_iterator begin() const