Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
io.h
Go to the documentation of this file.
1// Copyright 2010-2024 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};
52template <class Graph>
53std::string GraphToString(const Graph& graph, GraphToStringFormat format);
54
55// Writes a graph to the ".g" file format described above. If "directed" is
56// true, all arcs are written to the file. If it is false, the graph is expected
57// to be undirected (i.e. the number of arcs a->b is equal to the number of arcs
58// b->a for all nodes a,b); and only the arcs a->b where a<=b are written. Note
59// however that in this case, the symmetry of the graph is not fully checked
60// (only the parity of the number of non-self arcs is).
61//
62// "num_nodes_with_color" is optional. If it is not empty, then the color
63// information will be written to the header of the .g file. See ReadGraphFile.
64//
65// This method is the reverse of ReadGraphFile (with the same value for
66// "directed").
67template <class Graph>
68absl::Status WriteGraphToFile(const Graph& graph, const std::string& filename,
69 bool directed,
70 absl::Span<const int> num_nodes_with_color);
71
72// Implementations of the templated methods.
73
74template <class Graph>
75std::string GraphToString(const Graph& graph, GraphToStringFormat format) {
76 std::string out;
77 std::vector<uint64_t> adj;
78 for (const typename Graph::NodeIndex node : graph.AllNodes()) {
79 if (format == PRINT_GRAPH_ARCS) {
80 for (const typename Graph::ArcIndex arc : graph.OutgoingArcs(node)) {
81 if (!out.empty()) out += '\n';
82 absl::StrAppend(&out, static_cast<uint64_t>(node), "->",
83 static_cast<uint64_t>(graph.Head(arc)));
84 }
85 } else { // PRINT_GRAPH_ADJACENCY_LISTS[_SORTED]
86 adj.clear();
87 for (const typename Graph::ArcIndex arc : graph.OutgoingArcs(node)) {
88 adj.push_back(graph.Head(arc));
89 }
91 std::sort(adj.begin(), adj.end());
92 }
93 if (node != 0) out += '\n';
94 absl::StrAppend(&out, static_cast<uint64_t>(node), ": ",
95 absl::StrJoin(adj, " "));
96 }
97 }
98 return out;
99}
100
101template <class Graph>
102absl::Status WriteGraphToFile(const Graph& graph, const std::string& filename,
103 bool directed,
104 absl::Span<const int> num_nodes_with_color) {
105 FILE* f = fopen(filename.c_str(), "w");
106 if (f == nullptr) {
107 return absl::Status(absl::StatusCode::kInvalidArgument,
108 "Could not open file: '" + filename + "'");
109 }
110 // In undirected mode, we must count the self-arcs separately. All other arcs
111 // should be duplicated.
112 int num_self_arcs = 0;
113 if (!directed) {
114 for (const typename Graph::NodeIndex node : graph.AllNodes()) {
115 for (const typename Graph::ArcIndex arc : graph.OutgoingArcs(node)) {
116 if (graph.Head(arc) == node) ++num_self_arcs;
117 }
118 }
119 if ((graph.num_arcs() - num_self_arcs) % 2 != 0) {
120 fclose(f);
121 return absl::Status(absl::StatusCode::kInvalidArgument,
122 "WriteGraphToFile() called with directed=false"
123 " and with a graph with an odd number of (non-self)"
124 " arcs!");
125 }
126 }
127 absl::FPrintF(
128 f, "%d %d", static_cast<int64_t>(graph.num_nodes()),
129 static_cast<int64_t>(directed ? graph.num_arcs()
130 : (graph.num_arcs() + num_self_arcs) / 2));
131 if (!num_nodes_with_color.empty()) {
132 if (std::accumulate(num_nodes_with_color.begin(),
133 num_nodes_with_color.end(), 0) != graph.num_nodes() ||
134 *std::min_element(num_nodes_with_color.begin(),
135 num_nodes_with_color.end()) <= 0) {
136 return absl::Status(absl::StatusCode::kInvalidArgument,
137 "WriteGraphToFile() called with invalid coloring.");
138 }
139 absl::FPrintF(f, " %d", num_nodes_with_color.size());
140 for (int i = 0; i < num_nodes_with_color.size() - 1; ++i) {
141 absl::FPrintF(f, " %d", static_cast<int64_t>(num_nodes_with_color[i]));
142 }
143 }
144 absl::FPrintF(f, "\n");
145
146 for (const typename Graph::NodeIndex node : graph.AllNodes()) {
147 for (const typename Graph::ArcIndex arc : graph.OutgoingArcs(node)) {
148 const typename Graph::NodeIndex head = graph.Head(arc);
149 if (directed || head >= node) {
150 absl::FPrintF(f, "%d %d\n", static_cast<int64_t>(node),
151 static_cast<uint64_t>(head));
152 }
153 }
154 }
155
156 if (fclose(f) != 0) {
157 return absl::Status(absl::StatusCode::kInternal,
158 "Could not close file '" + filename + "'");
159 }
160
161 return ::absl::OkStatus();
162}
163
164} // namespace util
165
166#endif // UTIL_GRAPH_IO_H_
GraphType graph
int arc
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 io.h:102
GraphToStringFormat
Returns a string representation of a graph.
Definition io.h:41
@ PRINT_GRAPH_ADJACENCY_LISTS_SORTED
Ditto, but the adjacency lists are sorted.
Definition io.h:50
@ PRINT_GRAPH_ADJACENCY_LISTS
Definition io.h:47
@ PRINT_GRAPH_ARCS
One arc per line, eg. "3->1".
Definition io.h:43
ListGraph Graph
Defining the simplest Graph interface as Graph for convenience.
Definition graph.h:2407
std::string GraphToString(const Graph &graph, GraphToStringFormat format)
Implementations of the templated methods.
Definition io.h:75
int head