Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
fz.cc
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// This is the skeleton for the official flatzinc interpreter. Much
15// of the functionalities are fixed (name of parameters, format of the
16// input): see http://www.minizinc.org/downloads/doc-1.6/flatzinc-spec.pdf
17
18#include <cstdlib>
19#include <cstring>
20#if defined(__GNUC__) // Linux or Mac OS X.
21#include <signal.h>
22#endif // __GNUC__
23
24#include <iostream>
25#include <ostream>
26#include <string>
27#include <vector>
28
29#include "absl/flags/flag.h"
30#include "absl/log/check.h"
31#include "absl/log/initialize.h"
32#include "absl/strings/match.h"
33#include "absl/strings/str_split.h"
34#include "absl/strings/string_view.h"
35#include "absl/time/time.h"
38#include "ortools/base/path.h"
39#include "ortools/base/timer.h"
44
45constexpr bool kOrToolsMode = true;
46
47ABSL_FLAG(double, time_limit, 0, "time limit in seconds.");
48ABSL_FLAG(bool, search_all_solutions, false, "Search for all solutions.");
49ABSL_FLAG(bool, display_all_solutions, false,
50 "Display all improving solutions.");
51ABSL_FLAG(bool, free_search, false,
52 "If false, the solver must follow the defined search."
53 "If true, other search are allowed.");
54ABSL_FLAG(int, threads, 0, "Number of threads the solver will use.");
55ABSL_FLAG(bool, statistics, false, "Print solver statistics after search.");
56ABSL_FLAG(bool, read_from_stdin, false,
57 "Read the FlatZinc from stdin, not from a file.");
58ABSL_FLAG(int, fz_seed, 0, "Random seed");
59ABSL_FLAG(std::string, fz_model_name, "stdin",
60 "Define problem name when reading from stdin.");
61ABSL_FLAG(std::string, params, "", "SatParameters as a text proto.");
62ABSL_FLAG(bool, fz_logging, false,
63 "Print logging information from the flatzinc interpreter.");
64ABSL_FLAG(bool, ortools_mode, kOrToolsMode,
65 "Display solutions in the flatzinc format");
66
67namespace operations_research {
68namespace fz {
69
70std::vector<char*> FixAndParseParameters(int* argc, char*** argv) {
71 char all_param[] = "--search_all_solutions";
72 char print_solutions[] = "--display_all_solutions";
73 char free_param[] = "--free_search";
74 char threads_param[] = "--threads";
75 char logging_param[] = "--fz_logging";
76 char statistics_param[] = "--statistics";
77 char seed_param[] = "--fz_seed";
78 char time_param[] = "--time_limit";
79 bool use_time_param = false;
80 bool set_free_search = false;
81 for (int i = 1; i < *argc; ++i) {
82 if (strcmp((*argv)[i], "-a") == 0) {
83 (*argv)[i] = all_param;
84 }
85 if (strcmp((*argv)[i], "-i") == 0) {
86 (*argv)[i] = print_solutions;
87 }
88 if (strcmp((*argv)[i], "-f") == 0) {
89 (*argv)[i] = free_param;
90 set_free_search = true;
91 }
92 if (strcmp((*argv)[i], "-p") == 0) {
93 (*argv)[i] = threads_param;
94 }
95 if (strcmp((*argv)[i], "-l") == 0) {
96 (*argv)[i] = logging_param;
97 }
98 if (strcmp((*argv)[i], "-s") == 0) {
99 (*argv)[i] = statistics_param;
100 }
101 if (strcmp((*argv)[i], "-r") == 0) {
102 (*argv)[i] = seed_param;
103 }
104 if (strcmp((*argv)[i], "-t") == 0) {
105 (*argv)[i] = time_param;
106 use_time_param = true;
107 }
108 if (kOrToolsMode) {
109 if (strcmp((*argv)[i], "-v") == 0) {
110 (*argv)[i] = logging_param;
111 }
112 }
113 }
114 const char kUsage[] =
115 "Usage: see flags.\nThis program parses and solve a flatzinc problem.";
116
117 absl::SetProgramUsageMessage(kUsage);
118 const std::vector<char*> residual_flags =
119 absl::ParseCommandLine(*argc, *argv);
120 absl::InitializeLog();
121
122 // Fix time limit if -t was used.
123 if (use_time_param) {
124 absl::SetFlag(&FLAGS_time_limit, absl::GetFlag(FLAGS_time_limit) / 1000.0);
125 }
126
127 // Define the default number of workers to 1 if -f was used.
128 if (set_free_search && absl::GetFlag(FLAGS_threads) == 0) {
129 absl::SetFlag(&FLAGS_threads, 1);
130 }
131
132 return residual_flags;
133}
134
135Model ParseFlatzincModel(const std::string& input, bool input_is_filename,
136 SolverLogger* logger, absl::Duration* parse_duration) {
137 WallTimer timer;
138 timer.Start();
139
140 // Check the extension.
141 if (input_is_filename && !absl::EndsWith(input, ".fzn")) {
142 LOG(FATAL) << "Unrecognized flatzinc file: `" << input << "'";
143 }
144
145 // Read model.
146 const std::string problem_name = input_is_filename
147 ? std::string(file::Stem(input))
148 : absl::GetFlag(FLAGS_fz_model_name);
149 Model model(problem_name);
150 if (input_is_filename) {
151 CHECK(ParseFlatzincFile(input, &model));
152 } else {
153 CHECK(ParseFlatzincString(input, &model));
154 }
155
156 *parse_duration = timer.GetDuration();
157 SOLVER_LOG(logger, "File ", (input_is_filename ? input : "stdin"),
158 " parsed in ", absl::ToInt64Milliseconds(*parse_duration), " ms");
159 SOLVER_LOG(logger, "");
160
161 // Print statistics.
162 ModelStatistics stats(model, logger);
163 stats.BuildStatistics();
164 stats.PrintStatistics();
165 return model;
166}
167
168void LogInFlatzincFormat(const std::string& multi_line_input) {
169 if (multi_line_input.empty()) {
170 std::cout << std::endl;
171 return;
172 }
173 const absl::string_view flatzinc_prefix =
174 absl::GetFlag(FLAGS_ortools_mode) ? "%% " : "";
175 const std::vector<absl::string_view> lines =
176 absl::StrSplit(multi_line_input, '\n');
177 for (const absl::string_view& line : lines) {
178 std::cout << flatzinc_prefix << line << std::endl;
179 }
180}
181
182} // namespace fz
183} // namespace operations_research
184
185int main(int argc, char** argv) {
186 // Flatzinc specifications require single dash parameters (-a, -f, -p).
187 // We need to fix parameters before parsing them.
188 const std::vector<char*> residual_flags =
190 // We allow piping model through stdin.
191 std::string input;
192 if (absl::GetFlag(FLAGS_read_from_stdin)) {
193 std::string currentLine;
194 while (std::getline(std::cin, currentLine)) {
195 input.append(currentLine);
196 }
197 } else {
198 if (residual_flags.empty()) {
199 LOG(ERROR) << "Usage: " << argv[0] << " <file>";
200 return EXIT_FAILURE;
201 }
202 input = residual_flags.back();
203 }
204
206 if (absl::GetFlag(FLAGS_ortools_mode)) {
207 logger.EnableLogging(absl::GetFlag(FLAGS_fz_logging));
208 // log_to_stdout is disabled later.
210 } else {
211 logger.EnableLogging(true);
212 logger.SetLogToStdOut(true);
213 }
214
215 absl::Duration parse_duration;
218 input, !absl::GetFlag(FLAGS_read_from_stdin), &logger,
219 &parse_duration);
221
223 parameters.display_all_solutions = absl::GetFlag(FLAGS_display_all_solutions);
224 parameters.search_all_solutions = absl::GetFlag(FLAGS_search_all_solutions);
225 parameters.use_free_search = absl::GetFlag(FLAGS_free_search);
226 parameters.log_search_progress =
227 absl::GetFlag(FLAGS_fz_logging) || !absl::GetFlag(FLAGS_ortools_mode);
228 parameters.random_seed = absl::GetFlag(FLAGS_fz_seed);
229 parameters.display_statistics = absl::GetFlag(FLAGS_statistics);
230 parameters.number_of_threads = absl::GetFlag(FLAGS_threads);
231 parameters.max_time_in_seconds =
232 absl::GetFlag(FLAGS_time_limit) - absl::ToInt64Seconds(parse_duration);
233 parameters.ortools_mode = absl::GetFlag(FLAGS_ortools_mode);
234
235 operations_research::SolverLogger solution_logger;
236 solution_logger.SetLogToStdOut(true);
237 solution_logger.EnableLogging(parameters.ortools_mode);
238
240 absl::GetFlag(FLAGS_params),
241 &logger, &solution_logger);
242 return EXIT_SUCCESS;
243}
absl::Duration GetDuration() const
Definition timer.h:49
void Start()
When Start() is called multiple times, only the most recent is used.
Definition timer.h:32
void EnableLogging(bool enable)
Definition logging.h:46
void SetLogToStdOut(bool enable)
Should all messages be displayed on stdout ?
Definition logging.h:52
void AddInfoLoggingCallback(std::function< void(const std::string &message)> callback)
Definition logging.cc:29
void PrintStatistics() const
--— Model statistics --—
Definition model.cc:1134
ABSL_FLAG(double, time_limit, 0, "time limit in seconds.")
int main(int argc, char **argv)
Definition fz.cc:185
constexpr bool kOrToolsMode
Definition fz.cc:45
time_limit
Definition solve.cc:22
absl::string_view Stem(absl::string_view path)
Definition path.cc:129
void LogInFlatzincFormat(const std::string &multi_line_input)
Definition fz.cc:168
Model ParseFlatzincModel(const std::string &input, bool input_is_filename, SolverLogger *logger, absl::Duration *parse_duration)
Definition fz.cc:135
bool ParseFlatzincString(const std::string &input, Model *model)
Definition parser.cc:67
bool ParseFlatzincFile(const std::string &filename, Model *model)
--— public parsing API --—
Definition parser.cc:42
std::vector< char * > FixAndParseParameters(int *argc, char ***argv)
Definition fz.cc:70
void SolveFzWithCpModelProto(const fz::Model &fz_model, const fz::FlatzincSatParameters &p, const std::string &sat_params, SolverLogger *logger, SolverLogger *solution_logger)
Solves the given flatzinc model using the CP-SAT solver.
void ProcessFloatingPointOVariablesAndObjective(fz::Model *fz_model)
In SWIG mode, we don't want anything besides these top-level includes.
static int input(yyscan_t yyscanner)
static const char kUsage[]
#define SOLVER_LOG(logger,...)
Definition logging.h:109