Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
graph_io.h
Go to the documentation of this file.
1// Copyright 2010-2025 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14// A collections of i/o utilities for the Graph classes in ./graph.h.
15
16#ifndef UTIL_GRAPH_IO_H_
17#define UTIL_GRAPH_IO_H_
18
19#include <algorithm>
20#include <cstdint>
21#include <memory>
22#include <numeric>
23#include <string>
24#include <vector>
25
26#include "absl/status/status.h"
27#include "absl/status/statusor.h"
28#include "absl/strings/numbers.h"
29#include "absl/strings/str_cat.h"
30#include "absl/strings/str_format.h"
31#include "absl/strings/str_join.h"
32#include "absl/strings/str_split.h"
33#include "absl/types/span.h"
35#include "ortools/graph/graph.h"
37
38namespace util {
39
40// Returns a string representation of a graph.
42 // One arc per line, eg. "3->1".
44
45 // One space-separated adjacency list per line, eg. "3: 5 1 3 1".
46 // Nodes with no outgoing arc get an empty list.
48
49 // Ditto, but the adjacency lists are sorted.
51
52 // Dot format, can be visualized with Graphviz.
54};
55template <class Graph>
56std::string GraphToString(const Graph& graph, GraphToStringFormat format);
57
58// Writes a graph to the ".g" file format described above. If "directed" is
59// true, all arcs are written to the file. If it is false, the graph is expected
60// to be undirected (i.e. the number of arcs a->b is equal to the number of arcs
61// b->a for all nodes a,b); and only the arcs a->b where a<=b are written. Note
62// however that in this case, the symmetry of the graph is not fully checked
63// (only the parity of the number of non-self arcs is).
64//
65// "num_nodes_with_color" is optional. If it is not empty, then the color
66// information will be written to the header of the .g file. See ReadGraphFile.
67//
68// This method is the reverse of ReadGraphFile (with the same value for
69// "directed").
70template <class Graph>
71absl::Status WriteGraphToFile(const Graph& graph, const std::string& filename,
72 bool directed,
73 absl::Span<const int> num_nodes_with_color);
74
75// Implementations of the templated methods.
76
77template <class Graph>
78std::string GraphToString(const Graph& graph, GraphToStringFormat format) {
79 std::string out;
80 if (format == PRINT_GRAPH_DOT) {
81 absl::StrAppend(&out, "digraph {\n");
82 for (const auto arc : graph.AllForwardArcs()) {
83 absl::StrAppend(&out, " ", static_cast<int64_t>(graph.Tail(arc)), "->",
84 static_cast<int64_t>(graph.Head(arc)), ";\n");
85 }
86 absl::StrAppend(&out, "}\n");
87 return out;
88 }
89 std::vector<uint64_t> adj;
90 for (const typename Graph::NodeIndex node : graph.AllNodes()) {
91 if (format == PRINT_GRAPH_ARCS) {
92 for (const typename Graph::ArcIndex arc : graph.OutgoingArcs(node)) {
93 if (!out.empty()) out += '\n';
94 absl::StrAppend(&out, static_cast<uint64_t>(node), "->",
95 static_cast<uint64_t>(graph.Head(arc)));
96 }
97 } else { // PRINT_GRAPH_ADJACENCY_LISTS[_SORTED]
98 adj.clear();
99 for (const typename Graph::ArcIndex arc : graph.OutgoingArcs(node)) {
100 adj.push_back(graph.Head(arc));
101 }
103 std::sort(adj.begin(), adj.end());
104 }
105 if (node != 0) out += '\n';
106 absl::StrAppend(&out, static_cast<uint64_t>(node), ": ",
107 absl::StrJoin(adj, " "));
108 }
109 }
110 return out;
111}
112
113template <class Graph>
114absl::Status WriteGraphToFile(const Graph& graph, const std::string& filename,
115 bool directed,
116 absl::Span<const int> num_nodes_with_color) {
117 FILE* f = fopen(filename.c_str(), "w");
118 if (f == nullptr) {
119 return absl::Status(absl::StatusCode::kInvalidArgument,
120 "Could not open file: '" + filename + "'");
121 }
122 // In undirected mode, we must count the self-arcs separately. All other arcs
123 // should be duplicated.
124 int num_self_arcs = 0;
125 if (!directed) {
126 for (const typename Graph::NodeIndex node : graph.AllNodes()) {
127 for (const typename Graph::ArcIndex arc : graph.OutgoingArcs(node)) {
128 if (graph.Head(arc) == node) ++num_self_arcs;
129 }
130 }
131 if ((graph.num_arcs() - num_self_arcs) % 2 != 0) {
132 fclose(f);
133 return absl::Status(absl::StatusCode::kInvalidArgument,
134 "WriteGraphToFile() called with directed=false"
135 " and with a graph with an odd number of (non-self)"
136 " arcs!");
137 }
138 }
139 absl::FPrintF(
140 f, "%d %d", static_cast<int64_t>(graph.num_nodes()),
141 static_cast<int64_t>(directed ? graph.num_arcs()
142 : (graph.num_arcs() + num_self_arcs) / 2));
143 if (!num_nodes_with_color.empty()) {
144 if (std::accumulate(num_nodes_with_color.begin(),
145 num_nodes_with_color.end(), 0) != graph.num_nodes() ||
146 *std::min_element(num_nodes_with_color.begin(),
147 num_nodes_with_color.end()) <= 0) {
148 return absl::Status(absl::StatusCode::kInvalidArgument,
149 "WriteGraphToFile() called with invalid coloring.");
150 }
151 absl::FPrintF(f, " %d", num_nodes_with_color.size());
152 for (int i = 0; i < num_nodes_with_color.size() - 1; ++i) {
153 absl::FPrintF(f, " %d", static_cast<int64_t>(num_nodes_with_color[i]));
154 }
155 }
156 absl::FPrintF(f, "\n");
157
158 for (const typename Graph::NodeIndex node : graph.AllNodes()) {
159 for (const typename Graph::ArcIndex arc : graph.OutgoingArcs(node)) {
160 const typename Graph::NodeIndex head = graph.Head(arc);
161 if (directed || head >= node) {
162 absl::FPrintF(f, "%d %d\n", static_cast<int64_t>(node),
163 static_cast<uint64_t>(head));
164 }
165 }
166 }
167
168 if (fclose(f) != 0) {
169 return absl::Status(absl::StatusCode::kInternal,
170 "Could not close file '" + filename + "'");
171 }
172
173 return ::absl::OkStatus();
174}
175
176} // namespace util
177
178#endif // UTIL_GRAPH_IO_H_
A collections of i/o utilities for the Graph classes in ./graph.h.
absl::Status WriteGraphToFile(const Graph &graph, const std::string &filename, bool directed, absl::Span< const int > num_nodes_with_color)
Definition graph_io.h:114
GraphToStringFormat
Returns a string representation of a graph.
Definition graph_io.h:41
@ PRINT_GRAPH_ADJACENCY_LISTS_SORTED
Ditto, but the adjacency lists are sorted.
Definition graph_io.h:50
@ PRINT_GRAPH_ADJACENCY_LISTS
Definition graph_io.h:47
@ PRINT_GRAPH_ARCS
One arc per line, eg. "3->1".
Definition graph_io.h:43
@ PRINT_GRAPH_DOT
Dot format, can be visualized with Graphviz.
Definition graph_io.h:53
ListGraph Graph
Defining the simplest Graph interface as Graph for convenience.
Definition graph.h:2456
std::string GraphToString(const Graph &graph, GraphToStringFormat format)
Implementations of the templated methods.
Definition graph_io.h:78