Format all examples/cpp

This commit is contained in:
Mizux Seiha
2020-09-23 11:45:03 +02:00
parent bd1488ee03
commit ea95fb1c40
17 changed files with 112 additions and 107 deletions

4
.clang-format Normal file
View File

@@ -0,0 +1,4 @@
---
Language: Cpp
BasedOnStyle: Google
...

View File

@@ -90,10 +90,9 @@ class RandomDemand {
// Service time (proportional to demand) + transition time callback.
class ServiceTimePlusTransition {
public:
ServiceTimePlusTransition(
int64 time_per_demand_unit,
RoutingNodeEvaluator2 demand,
RoutingNodeEvaluator2 transition_time);
ServiceTimePlusTransition(int64 time_per_demand_unit,
RoutingNodeEvaluator2 demand,
RoutingNodeEvaluator2 transition_time);
int64 Compute(RoutingIndexManager::NodeIndex from,
RoutingIndexManager::NodeIndex to) const;
@@ -106,9 +105,9 @@ class ServiceTimePlusTransition {
// Stop service time + transition time callback.
class StopServiceTimePlusTransition {
public:
StopServiceTimePlusTransition(
int64 stop_time, const LocationContainer& location_container,
RoutingNodeEvaluator2 transition_time);
StopServiceTimePlusTransition(int64 stop_time,
const LocationContainer& location_container,
RoutingNodeEvaluator2 transition_time);
int64 Compute(RoutingIndexManager::NodeIndex from,
RoutingIndexManager::NodeIndex to) const;

View File

@@ -16,8 +16,8 @@
#include <cstdlib>
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_format.h"
#include "examples/cpp/parse_dimacs_assignment.h"
#include "examples/cpp/print_dimacs_assignment.h"

View File

@@ -723,7 +723,8 @@ void SolveDobble(int num_cards, int num_symbols, int num_symbols_per_card) {
// Main decision builder that regroups the first solution decision
// builder and the combination of local search operators and
// filters.
LocalSearchFilterManager* filter_manager = solver.RevAlloc(new LocalSearchFilterManager(filters));
LocalSearchFilterManager* filter_manager =
solver.RevAlloc(new LocalSearchFilterManager(filters));
DecisionBuilder* const final_db = solver.MakeLocalSearchPhase(
all_card_symbol_vars, build_db,
solver.MakeLocalSearchPhaseParameters(

View File

@@ -22,6 +22,7 @@
#include <map>
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"

View File

@@ -24,9 +24,9 @@
#include "absl/strings/str_format.h"
#include "examples/cpp/fap_parser.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/constraint_solver/constraint_solver.h"
namespace operations_research {

View File

@@ -97,8 +97,8 @@ void GolombRuler(int size) {
if (response.status() == CpSolverStatus::OPTIMAL) {
const int64 result = SolutionIntegerValue(response, ticks.back());
const int64 num_failures = response.num_conflicts();
printf("N = %d, optimal length = %lld (conflicts:%lld, time=%f s)\n", size, result,
num_failures, response.wall_time());
printf("N = %d, optimal length = %lld (conflicts:%lld, time=%f s)\n", size,
result, num_failures, response.wall_time());
if (size - 1 < kKnownSolutions) {
CHECK_EQ(result, kBestSolutions[size - 1]);
}

View File

@@ -62,7 +62,7 @@ void MagicSquare(int size) {
// Sum on columns.
for (int i = 0; i < size; ++i) {
builder.AddEquality(LinearExpr::Sum(transposed[i]), sum);
builder.AddEquality(LinearExpr::Sum(transposed[i]), sum);
}
// Sum on diagonals.
@@ -75,7 +75,7 @@ void MagicSquare(int size) {
const CpSolverResponse response = SolveCpModel(builder.Build(), &model);
if (response.status() == CpSolverStatus::OPTIMAL) {
for (int n = 0; n < size; ++n) {
for (int n = 0; n < size; ++n) {
std::string output;
for (int m = 0; m < size; ++m) {
absl::StrAppendFormat(&output, "%3d ",
@@ -89,8 +89,8 @@ void MagicSquare(int size) {
LOG(INFO) << CpSolverResponseStats(response);
}
} // namespace sat
} // namespace sat
} // namespace sat
} // namespace operations_research
int main(int argc, char **argv) {
absl::SetFlag(&FLAGS_logtostderr, true);

View File

@@ -12,6 +12,7 @@
// limitations under the License.
#include "ortools/graph/max_flow.h"
#include "ortools/base/logging.h"
namespace operations_research {

View File

@@ -12,6 +12,7 @@
// limitations under the License.
#include "ortools/graph/min_cost_flow.h"
#include "ortools/base/logging.h"
namespace operations_research {

View File

@@ -478,9 +478,10 @@ class NetworkRoutingSolver {
for (int demand_index = 0; demand_index < num_demands; ++demand_index) {
paths.clear();
const Demand &demand = demands_array_[demand_index];
CHECK(DijkstraShortestPath(num_nodes_, demand.source, demand.destination,
[this](int x, int y) { return HasArc(x, y); },
kDisconnectedDistance, &paths));
CHECK(DijkstraShortestPath(
num_nodes_, demand.source, demand.destination,
[this](int x, int y) { return HasArc(x, y); }, kDisconnectedDistance,
&paths));
all_min_path_lengths_.push_back(paths.size() - 1);
}

View File

@@ -19,9 +19,9 @@
#include <vector>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "examples/cpp/opb_reader.h"

View File

@@ -63,7 +63,8 @@ void PrintSolution(const std::vector<std::vector<int>> &data,
const int sum = data[i][j];
first_line += h_arc ? " -----" : " ";
second_line += v_arc ? "|" : " ";
second_line += sum == -1 ? " " : absl::StrFormat(" %d ", sum).c_str();
second_line +=
sum == -1 ? " " : absl::StrFormat(" %d ", sum).c_str();
third_line += v_arc ? "| " : " ";
}
const bool termination = v_arcs[num_columns][i];
@@ -153,8 +154,7 @@ void SlitherLink(const std::vector<std::vector<int>> &data) {
for (int x = 0; x < num_columns; ++x) {
for (int y = 0; y < num_rows; ++y) {
if (data[y][x] == -1)
continue;
if (data[y][x] == -1) continue;
std::vector<BoolVar> neighbors;
const int top_arc = undirected_horizontal_arc(x, y);
neighbors.push_back(horizontal_arcs[2 * top_arc]);
@@ -243,8 +243,8 @@ void SlitherLink(const std::vector<std::vector<int>> &data) {
LOG(INFO) << CpSolverResponseStats(response);
}
} // namespace sat
} // namespace operations_research
} // namespace sat
} // namespace operations_research
int main() {
std::cout << "Tiny problem" << std::endl;

View File

@@ -221,8 +221,7 @@ void SecondModel(int num_teams) {
for (int team = 0; team < num_teams; ++team) {
std::vector<BoolVar> possible_opponents;
for (int other = 0; other < num_teams; ++other) {
if (team == other)
continue;
if (team == other) continue;
possible_opponents.push_back(fixtures[d][team][other]);
possible_opponents.push_back(fixtures[d][other][team]);
}
@@ -233,8 +232,7 @@ void SecondModel(int num_teams) {
// Each fixture happens once per season.
for (int team = 0; team < num_teams; ++team) {
for (int other = 0; other < num_teams; ++other) {
if (team == other)
continue;
if (team == other) continue;
std::vector<BoolVar> possible_days;
for (int d = 0; d < num_days; ++d) {
possible_days.push_back(fixtures[d][team][other]);
@@ -246,8 +244,7 @@ void SecondModel(int num_teams) {
// Meet each opponent once per season.
for (int team = 0; team < num_teams; ++team) {
for (int other = 0; other < num_teams; ++other) {
if (team == other)
continue;
if (team == other) continue;
std::vector<BoolVar> first_half;
std::vector<BoolVar> second_half;
for (int d = 0; d < matches_per_day; ++d) {
@@ -265,8 +262,7 @@ void SecondModel(int num_teams) {
for (int d = 0; d < num_days; ++d) {
for (int team = 0; team < num_teams; ++team) {
for (int other = 0; other < num_teams; ++other) {
if (team == other)
continue;
if (team == other) continue;
builder.AddImplication(fixtures[d][team][other], at_home[d][team]);
builder.AddImplication(fixtures[d][team][other],
Not(at_home[d][other]));
@@ -313,8 +309,8 @@ void SecondModel(int num_teams) {
LOG(INFO) << CpSolverResponseStats(response);
}
} // namespace sat
} // namespace operations_research
} // namespace sat
} // namespace operations_research
static const char kUsage[] =
"Usage: see flags.\nThis program runs a sports scheduling problem."

View File

@@ -620,15 +620,15 @@ int main(int argc, char** argv) {
#endif // USE_GLOP
#if defined(USE_XPRESS)
if (FLAGS_colgen_solver == "xpress") {
solver_type = operations_research::MPSolver::XPRESS_LINEAR_PROGRAMMING;
//solver_type = operations_research::MPSolver::CPLEX_LINEAR_PROGRAMMING;
found = true;
solver_type = operations_research::MPSolver::XPRESS_LINEAR_PROGRAMMING;
// solver_type = operations_research::MPSolver::CPLEX_LINEAR_PROGRAMMING;
found = true;
}
#endif
#if defined(USE_CPLEX)
if (FLAGS_colgen_solver == "cplex") {
solver_type = operations_research::MPSolver::CPLEX_LINEAR_PROGRAMMING;
found = true;
solver_type = operations_research::MPSolver::CPLEX_LINEAR_PROGRAMMING;
found = true;
}
#endif
if (!found) {

View File

@@ -26,9 +26,9 @@
#include "google/protobuf/text_format.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/random.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/random.h"
#include "ortools/linear_solver/linear_solver.h"
DEFINE_int32(verbose, 0, "Verbosity level.");
@@ -41,34 +41,35 @@ namespace operations_research {
typedef struct {
double x{0};
double y{0};
} Location;
} Location;
typedef struct {
int f{-1};
int c{-1};
MPVariable* x{nullptr};
} Edge;
} Edge;
static double Distance(const Location& src, const Location& dst) {
return sqrt((src.x-dst.x)*(src.x-dst.x) + (src.y-dst.y)*(src.y-dst.y));
return sqrt((src.x - dst.x) * (src.x - dst.x) +
(src.y - dst.y) * (src.y - dst.y));
}
static void UncapacitatedFacilityLocation(int32 facilities,
int32 clients, double fix_cost,
static void UncapacitatedFacilityLocation(
int32 facilities, int32 clients, double fix_cost,
MPSolver::OptimizationProblemType optimization_problem_type) {
LOG(INFO) << "Starting " << __func__;
// Local Constants
const int32 kXMax = 1000;
const int32 kYMax = 1000;
const double kMaxDistance = 6*sqrt((kXMax*kYMax))/facilities;
const double kMaxDistance = 6 * sqrt((kXMax * kYMax)) / facilities;
const int kStrLen = 1024;
// char buffer for names
char name_buffer[kStrLen+1];
char name_buffer[kStrLen + 1];
name_buffer[kStrLen] = '\0';
LOG(INFO) << "Facilities/Clients/Fix cost/MaxDist: " << facilities << "/"
<< clients << "/" << fix_cost << "/" << kMaxDistance;
// Setting up facilities and demand points
MTRandom randomizer(/*fixed seed*/20191029);
MTRandom randomizer(/*fixed seed*/ 20191029);
std::vector<Location> facility(facilities);
std::vector<Location> client(clients);
for (int i = 0; i < facilities; ++i) {
@@ -96,8 +97,8 @@ static void UncapacitatedFacilityLocation(int32 facilities,
// Add binary facilities variables
std::vector<MPVariable*> xf{};
for (int f = 0; f < facilities; ++f) {
snprintf(name_buffer, kStrLen, "x[%d](%g,%g)", f,
facility[f].x, facility[f].y);
snprintf(name_buffer, kStrLen, "x[%d](%g,%g)", f, facility[f].x,
facility[f].y);
MPVariable* x = solver.MakeBoolVar(name_buffer);
xf.push_back(x);
objective->SetCoefficient(x, fix_cost);
@@ -106,16 +107,17 @@ static void UncapacitatedFacilityLocation(int32 facilities,
// Build edge variables
std::vector<Edge> edges;
for (int c = 0; c < clients; ++c) {
snprintf(name_buffer, kStrLen, "R-Client[%d](%g,%g)", c,
client[c].x, client[c].y);
MPConstraint* client_constraint = solver.MakeRowConstraint(/* lb */1,
/* ub */infinity, name_buffer);
snprintf(name_buffer, kStrLen, "R-Client[%d](%g,%g)", c, client[c].x,
client[c].y);
MPConstraint* client_constraint =
solver.MakeRowConstraint(/* lb */ 1,
/* ub */ infinity, name_buffer);
for (int f = 0; f < facilities; ++f) {
double distance = Distance(facility[f], client[c]);
if (distance > kMaxDistance) continue;
Edge edge{};
snprintf(name_buffer, kStrLen, "x[%d,%d]", f, c);
edge.x = solver.MakeNumVar(/* lb */0, /*ub */1, name_buffer);
edge.x = solver.MakeNumVar(/* lb */ 0, /*ub */ 1, name_buffer);
edge.f = f;
edge.c = c;
edges.push_back(edge);
@@ -124,18 +126,19 @@ static void UncapacitatedFacilityLocation(int32 facilities,
client_constraint->SetCoefficient(edge.x, 1);
// add constraint (2)
snprintf(name_buffer, kStrLen, "R-Edge[%d,%d]", f, c);
MPConstraint* edge_constraint = solver.MakeRowConstraint(/* lb */0,
/* ub */infinity, name_buffer);
MPConstraint* edge_constraint =
solver.MakeRowConstraint(/* lb */ 0,
/* ub */ infinity, name_buffer);
edge_constraint->SetCoefficient(edge.x, -1);
edge_constraint->SetCoefficient(xf[f], 1);
}
}// End adding all edge variables
} // End adding all edge variables
LOG(INFO) << "Number of variables = " << solver.NumVariables();
LOG(INFO) << "Number of constraints = " << solver.NumConstraints();
// display on screen LP if small enough
if (clients <= 10 && facilities <= 10) {
std::string lp_string{};
solver.ExportModelAsLpFormat(/* obfuscate */false, &lp_string);
solver.ExportModelAsLpFormat(/* obfuscate */ false, &lp_string);
std::cout << "LP-Model:\n" << lp_string << std::endl;
}
// Set options and solve
@@ -147,41 +150,41 @@ static void UncapacitatedFacilityLocation(int32 facilities,
if (result_status != MPSolver::OPTIMAL) {
LOG(FATAL) << "The problem does not have an optimal solution!";
} else {
LOG(INFO) << "Optimal objective value = " << objective->Value();
if (FLAGS_verbose) {
std::vector<std::vector<int>> solution(facilities);
for (auto& edge : edges) {
if (edge.x->solution_value() < 0.5) continue;
solution[edge.f].push_back(edge.c);
}
std::cout << "\tSolution:\n";
for (int f = 0; f < facilities; ++f) {
if (solution[f].size() < 1) continue;
assert(xf[f]->solution_value() > 0.5);
snprintf(name_buffer, kStrLen, "\t Facility[%d](%g,%g):", f,
facility[f].x, facility[f].y);
std::cout << name_buffer;
int i = 1;
for (auto c : solution[f]) {
snprintf(name_buffer, kStrLen, " Client[%d](%g,%g)", c,
client[c].x, client[c].y);
if(i++ >= 5) {
std::cout << "\n\t\t";
i = 1;
}
std::cout << name_buffer;
LOG(INFO) << "Optimal objective value = " << objective->Value();
if (FLAGS_verbose) {
std::vector<std::vector<int>> solution(facilities);
for (auto& edge : edges) {
if (edge.x->solution_value() < 0.5) continue;
solution[edge.f].push_back(edge.c);
}
std::cout << "\tSolution:\n";
for (int f = 0; f < facilities; ++f) {
if (solution[f].size() < 1) continue;
assert(xf[f]->solution_value() > 0.5);
snprintf(name_buffer, kStrLen, "\t Facility[%d](%g,%g):", f,
facility[f].x, facility[f].y);
std::cout << name_buffer;
int i = 1;
for (auto c : solution[f]) {
snprintf(name_buffer, kStrLen, " Client[%d](%g,%g)", c, client[c].x,
client[c].y);
if (i++ >= 5) {
std::cout << "\n\t\t";
i = 1;
}
std::cout << name_buffer;
}
std::cout << "\n";
}
std::cout << "\n";
}
}
std::cout << "\n";
LOG(INFO) << "";
LOG(INFO) << "Advanced usage:";
LOG(INFO) << "Problem solved in " << solver.DurationSinceConstruction()
<< " milliseconds";
LOG(INFO) << "Problem solved in " << solver.iterations() << " iterations";
LOG(INFO) << "Problem solved in " << solver.nodes()
<< " branch-and-bound nodes";
std::cout << "\n";
LOG(INFO) << "";
LOG(INFO) << "Advanced usage:";
LOG(INFO) << "Problem solved in " << solver.DurationSinceConstruction()
<< " milliseconds";
LOG(INFO) << "Problem solved in " << solver.iterations() << " iterations";
LOG(INFO) << "Problem solved in " << solver.nodes()
<< " branch-and-bound nodes";
}
}
@@ -189,46 +192,46 @@ void RunAllExamples(int32 facilities, int32 clients, double fix_cost) {
#if defined(USE_CBC)
LOG(INFO) << "---- Integer programming example with CBC ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::CBC_MIXED_INTEGER_PROGRAMMING);
MPSolver::CBC_MIXED_INTEGER_PROGRAMMING);
#endif
#if defined(USE_GLPK)
LOG(INFO) << "---- Integer programming example with GLPK ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING);
MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING);
#endif
#if defined(USE_SCIP)
LOG(INFO) << "---- Integer programming example with SCIP ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING);
MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING);
#endif
#if defined(USE_GUROBI)
LOG(INFO) << "---- Integer programming example with Gurobi ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::GUROBI_MIXED_INTEGER_PROGRAMMING);
MPSolver::GUROBI_MIXED_INTEGER_PROGRAMMING);
#endif // USE_GUROBI
#if defined(USE_CPLEX)
LOG(INFO) << "---- Integer programming example with CPLEX ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::CPLEX_MIXED_INTEGER_PROGRAMMING);
MPSolver::CPLEX_MIXED_INTEGER_PROGRAMMING);
#endif // USE_CPLEX
LOG(INFO) << "---- Integer programming example with CP-SAT ----";
UncapacitatedFacilityLocation(facilities, clients, fix_cost,
MPSolver::SAT_INTEGER_PROGRAMMING);
MPSolver::SAT_INTEGER_PROGRAMMING);
}
} // namespace operations_research
} // namespace operations_research
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
gflags::SetUsageMessage(
std::string("This program solve a (randomly generated)\n") +
std::string("Uncapacitated Facility Location Problem. Sample Usage:\n"));
std::string("This program solve a (randomly generated)\n") +
std::string("Uncapacitated Facility Location Problem. Sample Usage:\n"));
gflags::ParseCommandLineFlags(&argc, &argv, true);
CHECK_LT(0, FLAGS_facilities) << "Specify an instance size greater than 0.";
CHECK_LT(0, FLAGS_clients) << "Specify a non-null client size.";
CHECK_LT(0, FLAGS_fix_cost) << "Specify a non-null client size.";
FLAGS_logtostderr = 1;
operations_research::RunAllExamples(FLAGS_facilities, FLAGS_clients,
FLAGS_fix_cost);
FLAGS_fix_cost);
return EXIT_SUCCESS;
}

View File

@@ -17,14 +17,12 @@ void Solve() {
const IntVar start_p1 = cp_model.NewIntVar(Domain(500, 800));
const IntVar duration_p1 = cp_model.NewIntVar(Domain(1, 360));
const IntVar end_p1 = cp_model.NewIntVar(Domain(500, 1000));
const IntervalVar p1 =
cp_model.NewIntervalVar(start_p1, duration_p1, end_p1);
const IntervalVar p1 = cp_model.NewIntervalVar(start_p1, duration_p1, end_p1);
const IntVar start_p2 = cp_model.NewIntVar(Domain(500, 800));
const IntVar duration_p2 = cp_model.NewIntVar(Domain(1, 360));
const IntVar end_p2 = cp_model.NewIntVar(Domain(500, 1000));
const IntervalVar p2 =
cp_model.NewIntervalVar(start_p2, duration_p2, end_p2);
const IntervalVar p2 = cp_model.NewIntervalVar(start_p2, duration_p2, end_p2);
cp_model.AddEquality(LinearExpr::Sum({duration_p1, duration_p2}), 360);
cp_model.AddLessOrEqual(end_p1, start_p2);