diff --git a/examples/cpp/costas_array.cc b/examples/cpp/costas_array.cc index 748f385835..e87c755e48 100644 --- a/examples/cpp/costas_array.cc +++ b/examples/cpp/costas_array.cc @@ -20,7 +20,7 @@ // This example contains two separate implementations. CostasHard() // uses hard constraints, whereas CostasSoft() uses a minimizer to // minimize the number of duplicates. -#include +#include #include #include #include "base/callback.h" @@ -359,7 +359,7 @@ void CostasSoft(const int dim) { if (collector->solution_count() > 0) { std::vector costas_matrix; - string output; + std::string output; for (int n = 0; n < dim; ++n) { const int64 v = collector->Value(0, vars[n]); @@ -414,7 +414,7 @@ void CostasHard(const int dim) { if (solver.NextSolution()) { std::vector costas_matrix; - string output; + std::string output; for (int n = 0; n < dim; ++n) { const int64 v = vars[n]->Value(); diff --git a/examples/cpp/cvrptw.cc b/examples/cpp/cvrptw.cc index 0cf8d3f6ce..806d747390 100644 --- a/examples/cpp/cvrptw.cc +++ b/examples/cpp/cvrptw.cc @@ -162,10 +162,10 @@ class ServiceTimePlusTransition { // TODO(user): Move the display code to the routing library. void DisplayPlan(const RoutingModel& routing, const Assignment& plan) { // Display plan cost. - string plan_output = StringPrintf("Cost %lld\n", plan.ObjectiveValue()); + std::string plan_output = StringPrintf("Cost %lld\n", plan.ObjectiveValue()); // Display dropped orders. - string dropped; + std::string dropped; for (int order = 1; order < routing.nodes(); ++order) { if (plan.Value(routing.NextVar(order)) == order) { if (dropped.empty()) { diff --git a/examples/cpp/dimacs_assignment.cc b/examples/cpp/dimacs_assignment.cc index f86415bf5c..ba90e41aed 100644 --- a/examples/cpp/dimacs_assignment.cc +++ b/examples/cpp/dimacs_assignment.cc @@ -12,6 +12,7 @@ // limitations under the License. #include +#include #include #include "base/hash.h" #include @@ -23,10 +24,10 @@ #include "base/stringprintf.h" #include "base/timer.h" #include "algorithms/hungarian.h" -#include "graph/ebert_graph.h" -#include "graph/linear_assignment.h" #include "cpp/parse_dimacs_assignment.h" #include "cpp/print_dimacs_assignment.h" +#include "graph/ebert_graph.h" +#include "graph/linear_assignment.h" DEFINE_bool(assignment_compare_hungarian, false, "Compare result and speed against Hungarian method."); @@ -59,8 +60,8 @@ template CostValue BuildAndSolveHungarianInstance( arc_it.Ok(); arc_it.Next()) { ArcIndex arc = arc_it.Index(); - CostValue cost_magnitude = ::std::abs(assignment.ArcCost(arc)); - largest_cost_magnitude = ::std::max(largest_cost_magnitude, cost_magnitude); + CostValue cost_magnitude = abs(assignment.ArcCost(arc)); + largest_cost_magnitude = std::max(largest_cost_magnitude, cost_magnitude); } double missing_arc_cost = static_cast((assignment.NumLeftNodes() * largest_cost_magnitude) + @@ -125,7 +126,7 @@ template void DisplayAssignment( template int SolveDimacsAssignment(int argc, char* argv[]) { - string error_message; + std::string error_message; // Handle on the graph we will need to delete because the // LinearSumAssignment object does not take ownership of it. GraphType* graph = NULL; @@ -185,7 +186,7 @@ using ::operations_research::StarGraph; using ::operations_research::StringPrintf; int main(int argc, char* argv[]) { - string usage; + std::string usage; if (argc < 1) { usage = StringPrintf(kUsageTemplate, "solve_dimacs_assignment"); } else { diff --git a/examples/cpp/jobshop.cc b/examples/cpp/jobshop.cc index 55d0510db8..5a3c02e9c1 100644 --- a/examples/cpp/jobshop.cc +++ b/examples/cpp/jobshop.cc @@ -77,7 +77,7 @@ void Jobshop(const JobShopData& data) { for (int task_index = 0; task_index < tasks.size(); ++task_index) { const JobShopData::Task& task = tasks[task_index]; CHECK_EQ(job_id, task.job_id); - const string name = StringPrintf("J%dM%dI%dD%d", + const std::string name = StringPrintf("J%dM%dI%dD%d", task.job_id, task.machine_id, task_index, @@ -112,7 +112,7 @@ void Jobshop(const JobShopData& data) { // whose job is to sequence interval variables. std::vector all_sequences; for (int machine_id = 0; machine_id < machine_count; ++machine_id) { - const string name = StringPrintf("Machine_%d", machine_id); + const std::string name = StringPrintf("Machine_%d", machine_id); DisjunctiveConstraint* const ct = solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id], name); solver.AddConstraint(ct); diff --git a/examples/cpp/jobshop.h b/examples/cpp/jobshop.h index 97dff3f0bd..f1b4785a85 100644 --- a/examples/cpp/jobshop.h +++ b/examples/cpp/jobshop.h @@ -90,7 +90,7 @@ class JobShopData { // --data_file for a description of the format. Note that the format // is only partially checked: bad inputs might cause undefined // behavior. - void Load(const string& filename) { + void Load(const std::string& filename) { FileLineReader reader(filename.c_str()); reader.set_line_callback(NewPermanentCallback( this, @@ -108,7 +108,7 @@ class JobShopData { int job_count() const { return job_count_; } // The name of the jobshop instance. - const string& name() const { return name_; } + const std::string& name() const { return name_; } // The horizon of the workshop (the sum of all durations), which is // a trivial upper bound of the optimal make_span. @@ -123,7 +123,7 @@ class JobShopData { void ProcessNewLine(char* const line) { // TODO(user): more robust logic to support single-task jobs. static const char kWordDelimiters[] = " "; - std::vector words; + std::vector words; SplitStringUsing(line, kWordDelimiters, &words); switch (problem_type_) { case UNDEFINED: { @@ -216,7 +216,7 @@ class JobShopData { horizon_ += duration; } - string name_; + std::string name_; int machine_count_; int job_count_; int horizon_; diff --git a/examples/cpp/jobshop_earlytardy.cc b/examples/cpp/jobshop_earlytardy.cc index beb26770c4..1fc02db29d 100644 --- a/examples/cpp/jobshop_earlytardy.cc +++ b/examples/cpp/jobshop_earlytardy.cc @@ -85,7 +85,7 @@ class TimePlacement : public DecisionBuilder { : data_(data), all_sequences_(all_sequences), jobs_to_tasks_(jobs_to_tasks), - mp_solver_("TimePlacement", MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING) {} + mp_solver_("TimePlacement", MPSolver::CBC_MIXED_INTEGER_PROGRAMMING) {} virtual ~TimePlacement() {} @@ -100,7 +100,7 @@ class TimePlacement : public DecisionBuilder { for (int s = 0; s < jobs_to_tasks_.size(); ++s) { for (int t = 0; t < jobs_to_tasks_[s].size(); ++t) { IntervalVar* const task = jobs_to_tasks_[s][t]; - const string name = StringPrintf("J%dT%d", s, t); + const std::string name = StringPrintf("J%dT%d", s, t); MPVariable* const var = mp_solver_.MakeIntVar(task->StartMin(), task->StartMax(), name); mapping[task] = var; @@ -192,7 +192,7 @@ class TimePlacement : public DecisionBuilder { return NULL; } - virtual string DebugString() const { + virtual std::string DebugString() const { return "TimePlacement"; } @@ -224,7 +224,7 @@ void EtJobShop(const EtJobShopData& data) { for (int task_index = 0; task_index < tasks.size(); ++task_index) { const Task& task = tasks[task_index]; CHECK_EQ(job_id, task.job_id); - const string name = StringPrintf("J%dM%dI%dD%d", + const std::string name = StringPrintf("J%dM%dI%dD%d", task.job_id, task.machine_id, task_index, @@ -283,7 +283,7 @@ void EtJobShop(const EtJobShopData& data) { // whose job is to sequence interval variables. std::vector all_sequences; for (int machine_id = 0; machine_id < machine_count; ++machine_id) { - const string name = StringPrintf("Machine_%d", machine_id); + const std::string name = StringPrintf("Machine_%d", machine_id); DisjunctiveConstraint* const ct = solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id], name); solver.AddConstraint(ct); @@ -340,21 +340,18 @@ void EtJobShop(const EtJobShopData& data) { std::vector operators; LOG(INFO) << " - use swap operator"; LocalSearchOperator* const swap_operator = - solver.RevAlloc(new SwapIntervals(all_sequences.data(), - all_sequences.size())); + solver.RevAlloc(new SwapIntervals(all_sequences)); operators.push_back(swap_operator); LOG(INFO) << " - use shuffle operator with a max length of " << FLAGS_shuffle_length; LocalSearchOperator* const shuffle_operator = - solver.RevAlloc(new ShuffleIntervals(all_sequences.data(), - all_sequences.size(), + solver.RevAlloc(new ShuffleIntervals(all_sequences, FLAGS_shuffle_length)); operators.push_back(shuffle_operator); LOG(INFO) << " - use free sub sequences of length " << FLAGS_sub_sequence_length << " lns operator"; LocalSearchOperator* const lns_operator = - solver.RevAlloc(new SequenceLns(all_sequences.data(), - all_sequences.size(), + solver.RevAlloc(new SequenceLns(all_sequences, FLAGS_lns_seed, FLAGS_sub_sequence_length)); operators.push_back(lns_operator); diff --git a/examples/cpp/jobshop_earlytardy.h b/examples/cpp/jobshop_earlytardy.h index 6700e3b420..6ed9425e62 100644 --- a/examples/cpp/jobshop_earlytardy.h +++ b/examples/cpp/jobshop_earlytardy.h @@ -78,7 +78,7 @@ class EtJobShopData { ~EtJobShopData() {} - void LoadJetFile(const string& filename) { + void LoadJetFile(const std::string& filename) { LOG(INFO) << "Reading jet file " << filename; name_ = StringPrintf("JetData(%s)", filename.c_str()); FileLineReader reader(filename.c_str()); @@ -143,7 +143,7 @@ class EtJobShopData { int job_count() const { return job_count_; } // The name of the jobshop instance. - const string& name() const { return name_; } + const std::string& name() const { return name_; } // The horizon of the workshop (the sum of all durations), which is // a trivial upper bound of the optimal make_span. @@ -158,7 +158,7 @@ class EtJobShopData { void ProcessNewJetLine(char* const line) { // TODO(user): more robust logic to support single-task jobs. static const char kWordDelimiters[] = " "; - std::vector words; + std::vector words; SplitStringUsing(line, kWordDelimiters, &words); if (words.size() == 2) { job_count_ = atoi32(words[0]); @@ -187,12 +187,11 @@ class EtJobShopData { } } - string name_; + std::string name_; int machine_count_; int job_count_; int horizon_; std::vector all_jobs_; }; } // namespace operations_research -#endif OR_TOOLS_EXAMPLES_JOBSHOP_EARLYTARDY_H_ - +#endif // OR_TOOLS_EXAMPLES_JOBSHOP_EARLYTARDY_H_ diff --git a/examples/cpp/jobshop_ls.cc b/examples/cpp/jobshop_ls.cc index cc9f203db5..0b387d3043 100644 --- a/examples/cpp/jobshop_ls.cc +++ b/examples/cpp/jobshop_ls.cc @@ -88,7 +88,7 @@ void JobshopLs(const JobShopData& data) { for (int task_index = 0; task_index < tasks.size(); ++task_index) { const JobShopData::Task& task = tasks[task_index]; CHECK_EQ(job_id, task.job_id); - const string name = StringPrintf("J%dM%dI%dD%d", + const std::string name = StringPrintf("J%dM%dI%dD%d", task.job_id, task.machine_id, task_index, @@ -123,7 +123,7 @@ void JobshopLs(const JobShopData& data) { // whose job is to sequence interval variables. std::vector all_sequences; for (int machine_id = 0; machine_id < machine_count; ++machine_id) { - const string name = StringPrintf("Machine_%d", machine_id); + const std::string name = StringPrintf("Machine_%d", machine_id); DisjunctiveConstraint* const ct = solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id], name); solver.AddConstraint(ct); diff --git a/examples/cpp/linear_solver_protocol_buffers.cc b/examples/cpp/linear_solver_protocol_buffers.cc index 5472609c51..982bc05539 100644 --- a/examples/cpp/linear_solver_protocol_buffers.cc +++ b/examples/cpp/linear_solver_protocol_buffers.cc @@ -21,10 +21,10 @@ namespace operations_research { void BuildLinearProgrammingMaxExample(MPSolver::OptimizationProblemType type) { const double kObjCoef[] = {10.0, 6.0, 4.0}; - const string kVarName[] = {"x1", "x2", "x3"}; + const std::string kVarName[] = {"x1", "x2", "x3"}; const int numVars = 3; const int kNumConstraints = 3; - const string kConstraintName[] = {"c1", "c2", "c3"}; + const std::string kConstraintName[] = {"c1", "c2", "c3"}; const double kConstraintCoef1[] = {1.0, 1.0, 1.0}; const double kConstraintCoef2[] = {10.0, 4.0, 5.0}; const double kConstraintCoef3[] = {2.0, 2.0, 6.0}; diff --git a/examples/cpp/magic_square.cc b/examples/cpp/magic_square.cc index 9b5d66d186..76f2114dac 100644 --- a/examples/cpp/magic_square.cc +++ b/examples/cpp/magic_square.cc @@ -134,7 +134,7 @@ void MagicSquare(int grid_size) { solver.NewSearch(db, monitors); if (solver.NextSolution()) { for (int n = 0; n < grid_size; ++n) { - string output; + std::string output; for (int m = 0; m < grid_size; ++m) { // extract row indices int64 v = vars[n * grid_size + m]->Value(); StringAppendF(&output, "%3lld ", v); diff --git a/examples/cpp/model_util.cc b/examples/cpp/model_util.cc index ccbb6fa596..821b20f637 100644 --- a/examples/cpp/model_util.cc +++ b/examples/cpp/model_util.cc @@ -61,28 +61,28 @@ static const char kYellow[] = "#FFF68F"; static const char kRed[] = "#A52A2A"; // Creates node labels. -string ExprLabel(int index) { +std::string ExprLabel(int index) { return StringPrintf("expr_%i", index); } -string IntervalLabel(int index) { +std::string IntervalLabel(int index) { return StringPrintf("interval_%i", index); } -string SequenceLabel(int index) { +std::string SequenceLabel(int index) { return StringPrintf("sequence_%i", index); } -string ConstraintLabel(int index) { +std::string ConstraintLabel(int index) { return StringPrintf("ct_%i", index); } // Scans argument to add links in the graph. template void ExportLinks(const CPModelProto& model, - const string& source, + const std::string& source, const T& proto, GraphExporter* const exporter) { - const string& arg_name = model.tags(proto.argument_index()); + const std::string& arg_name = model.tags(proto.argument_index()); if (proto.has_integer_expression_index()) { exporter->WriteLink(source, ExprLabel(proto.integer_expression_index()), @@ -151,7 +151,7 @@ void DeclareExpression(int index, const CPModelProto& proto, GraphExporter* const exporter) { const CPIntegerExpressionProto& expr = proto.expressions(index); - const string label = ExprLabel(index); + const std::string label = ExprLabel(index); int64 value = 0; if (expr.has_name()) { exporter->WriteNode(label, expr.name(), "oval", kGreen1); @@ -161,7 +161,7 @@ void DeclareExpression(int index, "oval", kYellow); } else { - const string& type = proto.tags(expr.type_index()); + const std::string& type = proto.tags(expr.type_index()); exporter->WriteNode(label, type, "oval", kWhite); } } @@ -170,11 +170,11 @@ void DeclareInterval(int index, const CPModelProto& proto, GraphExporter* const exporter) { const CPIntervalVariableProto& interval = proto.intervals(index); - const string label = IntervalLabel(index); + const std::string label = IntervalLabel(index); if (interval.has_name()) { exporter->WriteNode(label, interval.name(), "circle", kGreen2); } else { - const string& type = proto.tags(interval.type_index()); + const std::string& type = proto.tags(interval.type_index()); exporter->WriteNode(label, type, "circle", kWhite); } } @@ -183,11 +183,11 @@ void DeclareSequence(int index, const CPModelProto& proto, GraphExporter* const exporter) { const CPSequenceVariableProto& sequence = proto.sequences(index); - const string label = SequenceLabel(index); + const std::string label = SequenceLabel(index); if (sequence.has_name()) { exporter->WriteNode(label, sequence.name(), "circle", kGreen3); } else { - const string& type = proto.tags(sequence.type_index()); + const std::string& type = proto.tags(sequence.type_index()); exporter->WriteNode(label, type, "circle", kWhite); } } @@ -196,8 +196,8 @@ void DeclareConstraint(int index, const CPModelProto& proto, GraphExporter* const exporter) { const CPConstraintProto& ct = proto.constraints(index); - const string& type = proto.tags(ct.type_index()); - const string label = ConstraintLabel(index); + const std::string& type = proto.tags(ct.type_index()); + const std::string label = ConstraintLabel(index); exporter->WriteNode(label, type, "rectangle", kBlue); } @@ -226,13 +226,13 @@ void ExportToGraphFile(const CPModelProto& proto, const char kObjLabel[] = "obj"; if (proto.has_objective()) { - const string name = proto.objective().maximize() ? "Maximize" : "Minimize"; + const std::string name = proto.objective().maximize() ? "Maximize" : "Minimize"; exporter->WriteNode(kObjLabel, name, "diamond", kRed); } for (int i = 0; i < proto.expressions_size(); ++i) { const CPIntegerExpressionProto& expr = proto.expressions(i); - const string label = ExprLabel(i); + const std::string label = ExprLabel(i); for (int j = 0; j < expr.arguments_size(); ++j) { ExportLinks(proto, label, expr.arguments(j), exporter.get()); } @@ -240,7 +240,7 @@ void ExportToGraphFile(const CPModelProto& proto, for (int i = 0; i < proto.intervals_size(); ++i) { const CPIntervalVariableProto& interval = proto.intervals(i); - const string label = IntervalLabel(i); + const std::string label = IntervalLabel(i); for (int j = 0; j < interval.arguments_size(); ++j) { ExportLinks(proto, label, interval.arguments(j), exporter.get()); } @@ -248,7 +248,7 @@ void ExportToGraphFile(const CPModelProto& proto, for (int i = 0; i < proto.sequences_size(); ++i) { const CPSequenceVariableProto& sequence = proto.sequences(i); - const string label = SequenceLabel(i); + const std::string label = SequenceLabel(i); for (int j = 0; j < sequence.arguments_size(); ++j) { ExportLinks(proto, label, sequence.arguments(j), exporter.get()); } @@ -256,7 +256,7 @@ void ExportToGraphFile(const CPModelProto& proto, for (int i = 0; i < proto.constraints_size(); ++i) { const CPConstraintProto& ct = proto.constraints(i); - const string label = ConstraintLabel(i); + const std::string label = ConstraintLabel(i); for (int j = 0; j < ct.arguments_size(); ++j) { ExportLinks(proto, label, ct.arguments(j), exporter.get()); } diff --git a/examples/cpp/multidim_knapsack.cc b/examples/cpp/multidim_knapsack.cc index 89ab5f466d..1989cb1643 100644 --- a/examples/cpp/multidim_knapsack.cc +++ b/examples/cpp/multidim_knapsack.cc @@ -51,7 +51,7 @@ class MultiDimKnapsackData { problem_type_(-1) {} - void Load(const string& filename) { + void Load(const std::string& filename) { FileLineReader reader(filename.c_str()); reader.set_line_callback(NewPermanentCallback( this, @@ -77,7 +77,7 @@ class MultiDimKnapsackData { int dims() const { return num_dims_; } // Name of the problem. - const string& name() const { return name_; } + const std::string& name() const { return name_; } int capacity(int i) const { return dims_[i]; } int profit(int j) const { return profit_[j]; } @@ -87,7 +87,7 @@ class MultiDimKnapsackData { // Used internally. void ProcessNewLine(char* const line) { const char* const kWordDelimiters(" "); - std::vector words; + std::vector words; SplitStringUsing(line, kWordDelimiters, &words); line_read_++; if (problem_type_ == -1) { @@ -233,7 +233,7 @@ class MultiDimKnapsackData { } private: - string name_; + std::string name_; std::vector dims_; std::vector profit_; std::vector > weight_; diff --git a/examples/cpp/network_routing.cc b/examples/cpp/network_routing.cc index d93d4de308..fa520598df 100644 --- a/examples/cpp/network_routing.cc +++ b/examples/cpp/network_routing.cc @@ -108,7 +108,7 @@ class NetworkRoutingData { fixed_charge_cost_(-1) {} // Name of the problem. - const string& name() const { return name_; } + const std::string& name() const { return name_; } // Properties of the model. int num_nodes() const { return num_nodes_; } @@ -121,7 +121,7 @@ class NetworkRoutingData { int Capacity(int node1, int node2) const { return FindWithDefault(all_arcs_, std::make_pair(std::min(node1, node2), - std::max(node1, node2)), + std::max(node1, node2)), 0); } @@ -136,17 +136,17 @@ class NetworkRoutingData { void set_num_nodes(int num_nodes) { num_nodes_ = num_nodes; } void AddArc(int node1, int node2, int capacity) { all_arcs_[std::make_pair(std::min(node1, node2), - std::max(node1, node2))] = capacity; + std::max(node1, node2))] = capacity; } void AddDemand(int source, int destination, int traffic) { all_demands_[std::make_pair(source, destination)] = traffic; } - void set_name(const string& name) { name_ = name; } + void set_name(const std::string& name) { name_ = name; } void set_max_capacity(int max_capacity) { max_capacity_ = max_capacity; } void set_fixed_charge_cost(int cost) { fixed_charge_cost_ = cost; } private: - string name_; + std::string name_; int num_nodes_; int max_capacity_; int fixed_charge_cost_; @@ -338,7 +338,7 @@ class NetworkRoutingDataBuilder { NetworkRoutingData* const data) { const int size = num_backbones + num_clients; - const string name = + const std::string name = StringPrintf("mp_c%i_b%i_d%i.t%i-%i.cd%i-%i.bd%i-%i.mc%i.fc%i.s%i", num_clients, num_backbones, @@ -618,7 +618,7 @@ class NetworkRoutingSolver { tuple_set.Insert(tuple); } - const string name = StringPrintf("PathDecision_%i", demand_index); + const std::string name = StringPrintf("PathDecision_%i", demand_index); IntVar* const var = solver->MakeIntVar(0, tuple_set.NumTuples() - 1, name); std::vector tmp_vars; tmp_vars.push_back(var); @@ -780,7 +780,7 @@ class NetworkRoutingSolver { return NULL; } - virtual string DebugString() const { + virtual std::string DebugString() const { return "ApplyMaxDiscrepancy"; } }; diff --git a/examples/cpp/opb_reader.h b/examples/cpp/opb_reader.h index edf608fc90..1a11d6478d 100644 --- a/examples/cpp/opb_reader.h +++ b/examples/cpp/opb_reader.h @@ -24,7 +24,6 @@ #include "sat/boolean_problem.pb.h" #include "util/filelineiter.h" -using std::string; namespace operations_research { namespace sat { @@ -37,14 +36,14 @@ class OpbReader { OpbReader() {} // Loads the given opb filename into the given problem. - bool Load(const string& filename, LinearBooleanProblem* problem) { + bool Load(const std::string& filename, LinearBooleanProblem* problem) { problem->Clear(); problem->set_name(ExtractProblemName(filename)); problem->set_type(LinearBooleanProblem::SATISFIABILITY); num_variables_ = 0; int num_lines = 0; - for (const string& line : FileLines(filename)) { + for (const std::string& line : FileLines(filename)) { ++num_lines; ProcessNewLine(problem, line); } @@ -58,16 +57,16 @@ class OpbReader { private: // Since the problem name is not stored in the cnf format, we infer it from // the file name. - static string ExtractProblemName(const string& filename) { + static std::string ExtractProblemName(const std::string& filename) { const int found = filename.find_last_of("/"); - const string problem_name = found != string::npos ? + const std::string problem_name = found != std::string::npos ? filename.substr(found + 1) : filename; return problem_name; } - void ProcessNewLine(LinearBooleanProblem* problem, const string& line) { + void ProcessNewLine(LinearBooleanProblem* problem, const std::string& line) { static const char kWordDelimiters[] = " "; - std::vector words; + std::vector words; SplitStringUsing(line, kWordDelimiters, &words); if (words.size() == 0 || words[0].empty() || words[0][0] == '*') { return; @@ -77,7 +76,7 @@ class OpbReader { problem->set_type(LinearBooleanProblem::MINIMIZATION); LinearObjective* objective = problem->mutable_objective(); for (int i = 1; i < words.size(); ++i) { - const string& word = words[i]; + const std::string& word = words[i]; if (word.empty() || word[0] == ';') continue; if (word[0] == 'x') { const int literal = atoi32(word.substr(1)); @@ -95,7 +94,7 @@ class OpbReader { } LinearBooleanConstraint* constraint = problem->add_constraints(); for (int i = 0; i < words.size(); ++i) { - const string& word = words[i]; + const std::string& word = words[i]; CHECK(!word.empty()); if (word == ">=") { CHECK_LT(i + 1, words.size()); diff --git a/examples/cpp/parse_dimacs_assignment.h b/examples/cpp/parse_dimacs_assignment.h index f4b8cbf46b..b245f1590a 100644 --- a/examples/cpp/parse_dimacs_assignment.h +++ b/examples/cpp/parse_dimacs_assignment.h @@ -40,7 +40,7 @@ template class LinearSumAssignment; template class DimacsAssignmentParser { public: - explicit DimacsAssignmentParser(const string filename) + explicit DimacsAssignmentParser(const std::string filename) : filename_(filename), graph_builder_(NULL), assignment_(NULL) { } @@ -58,7 +58,7 @@ template class DimacsAssignmentParser { // representation back to the caller, the caller lacks a good way to // free the underlying graph (which isn't owned by the // LinearAssignment instance). - LinearSumAssignment* Parse(string* error_message, + LinearSumAssignment* Parse(std::string* error_message, GraphType** graph); private: @@ -70,10 +70,10 @@ template class DimacsAssignmentParser { void ParseOneLine(char* line); - void ParseFileByLines(const string& filename, + void ParseFileByLines(const std::string& filename, Callback1* line_parser); - string filename_; + std::string filename_; struct ErrorTrackingState { ErrorTrackingState() @@ -90,7 +90,7 @@ template class DimacsAssignmentParser { const char* reason; NodeIndex num_left_nodes; ArcIndex num_arcs; - std::unique_ptr bad_line; + std::unique_ptr bad_line; }; ErrorTrackingState state_; @@ -120,7 +120,7 @@ void DimacsAssignmentParser::ParseProblemLine( strlen(kAssignmentProblemType)) != 0)) { state_.bad = true; state_.reason = kIncorrectProblemLine; - state_.bad_line.reset(new string(line)); + state_.bad_line.reset(new std::string(line)); return; } @@ -135,16 +135,16 @@ void DimacsAssignmentParser::ParseNodeLine(const char* line) { if (sscanf(line, "%*c%d", &node_id) != 1) { state_.bad = true; state_.reason = "Syntax error in node desciption."; - state_.bad_line.reset(new string(line)); + state_.bad_line.reset(new std::string(line)); return; } if (state_.nodes_described) { state_.bad = true; state_.reason = "All node description must precede first arc description."; - state_.bad_line.reset(new string(line)); + state_.bad_line.reset(new std::string(line)); return; } - state_.num_left_nodes = ::std::max(state_.num_left_nodes, node_id); + state_.num_left_nodes = std::max(state_.num_left_nodes, node_id); } template @@ -154,7 +154,7 @@ void DimacsAssignmentParser::ParseArcLine( state_.bad = true; state_.reason = "Problem specification line must precede any arc specification."; - state_.bad_line.reset(new string(line)); + state_.bad_line.reset(new std::string(line)); return; } if (!state_.nodes_described) { @@ -169,7 +169,7 @@ void DimacsAssignmentParser::ParseArcLine( if (sscanf(line, "%*c%d%d%lld", &tail, &head, &cost) != 3) { state_.bad = true; state_.reason = "Syntax error in arc descriptor."; - state_.bad_line.reset(new string(line)); + state_.bad_line.reset(new std::string(line)); } ArcIndex arc = graph_builder_->AddArc(tail - 1, head - 1); assignment_->SetArcCost(arc, FLAGS_assignment_maximize_cost ? -cost : cost); @@ -200,7 +200,7 @@ void DimacsAssignmentParser::ParseOneLine(char* line) { // Prepare for the worst; we might need to inform the user of // an error on this line even though we can't detect the error // yet. - state_.bad_line.reset(new string(line)); + state_.bad_line.reset(new std::string(line)); } @@ -229,7 +229,7 @@ void DimacsAssignmentParser::ParseOneLine(char* line) { default: { state_.bad = true; state_.reason = "Unknown line type in the input."; - state_.bad_line.reset(new string(line)); + state_.bad_line.reset(new std::string(line)); break; } } @@ -237,7 +237,7 @@ void DimacsAssignmentParser::ParseOneLine(char* line) { template void DimacsAssignmentParser::ParseFileByLines( - const string& filename, + const std::string& filename, Callback1* line_parser) { FILE* fp = fopen(filename.c_str(), "r"); const int kMaximumLineSize = 1024; @@ -270,7 +270,7 @@ void DimacsAssignmentParser::ParseFileByLines( // LinearAssignment instance). template LinearSumAssignment* DimacsAssignmentParser::Parse( - string* error_message, + std::string* error_message, GraphType** graph_handle) { CHECK_NOTNULL(error_message); CHECK_NOTNULL(graph_handle); diff --git a/examples/cpp/pdptw.cc b/examples/cpp/pdptw.cc index a6d9d625a5..05fb3be51a 100644 --- a/examples/cpp/pdptw.cc +++ b/examples/cpp/pdptw.cc @@ -103,12 +103,12 @@ int64 Demand(const std::vector* const demands, return demands->at(from.value()); } -// Outputs a solution to the current model in a string. -string VerboseOutput(const RoutingModel& routing, +// Outputs a solution to the current model in a std::string. +std::string VerboseOutput(const RoutingModel& routing, const Assignment& assignment, const Coordinates& coords, const std::vector& service_times) { - string output; + std::string output; const RoutingDimension& time_dimension = routing.GetDimensionOrDie("time"); const RoutingDimension& load_dimension = routing.GetDimensionOrDie("demand"); for (int i = 0; i < routing.vehicles(); ++i) { @@ -156,10 +156,10 @@ string VerboseOutput(const RoutingModel& routing, namespace { // An inefficient but convenient method to parse a whitespace-separated list -// of integers. Returns true iff the input string was entirely valid and parsed. -bool SafeParseInt64Array(const string& str, std::vector* parsed_int) { +// of integers. Returns true iff the input std::string was entirely valid and parsed. +bool SafeParseInt64Array(const std::string& str, std::vector* parsed_int) { static const char kWhiteSpaces[] = " \t\n\v\f\r"; - std::vector items = strings::Split( + std::vector items = strings::Split( str, strings::delimiter::AnyOf(kWhiteSpaces), strings::SkipEmpty()); parsed_int->assign(items.size(), 0); for (int i = 0; i < items.size(); ++i) { @@ -175,13 +175,13 @@ bool SafeParseInt64Array(const string& str, std::vector* parsed_int) { // Builds and solves a model from a file in the format defined by Li & Lim // (http://www.sintef.no/static/am/opti/projects/top/vrp/format_pdp.htm). -bool LoadAndSolve(const string& pdp_file) { +bool LoadAndSolve(const std::string& pdp_file) { // Load all the lines of the file in RAM (it shouldn't be too large anyway). - std::vector lines; + std::vector lines; { const int64 kMaxInputFileSize = 1 << 30; // 1GB File* data_file = File::OpenOrDie(pdp_file, "r"); - string contents; + std::string contents; data_file->ReadToString(&contents, kMaxInputFileSize); data_file->Close(); if (contents.size() == kMaxInputFileSize) { diff --git a/examples/cpp/print_dimacs_assignment.h b/examples/cpp/print_dimacs_assignment.h index 95f066b76e..59534edd99 100644 --- a/examples/cpp/print_dimacs_assignment.h +++ b/examples/cpp/print_dimacs_assignment.h @@ -37,7 +37,7 @@ template void PrintDimacsAssignmentProblem( const LinearSumAssignment& assignment, const TailArrayManager& tail_array_manager, - const string& output_filename); + const std::string& output_filename); // Implementation is below here. namespace internal { @@ -60,10 +60,10 @@ template void PrintDimacsAssignmentProblem( const LinearSumAssignment& assignment, const TailArrayManager& tail_array_manager, - const string& output_filename) { + const std::string& output_filename) { FILE* output = fopen(output_filename.c_str(), "w"); const GraphType& graph(assignment.Graph()); - string output_line = StringPrintf("p asn %d %d\n", + std::string output_line = StringPrintf("p asn %d %d\n", graph.num_nodes(), graph.num_arcs()); internal::WriteOrDie(output_line.c_str(), 1, diff --git a/examples/cpp/sat_cnf_reader.h b/examples/cpp/sat_cnf_reader.h index 837937c455..58dd80b197 100644 --- a/examples/cpp/sat_cnf_reader.h +++ b/examples/cpp/sat_cnf_reader.h @@ -23,7 +23,6 @@ #include "sat/boolean_problem.pb.h" #include "util/filelineiter.h" -using std::string; namespace operations_research { namespace sat { @@ -38,7 +37,7 @@ class SatCnfReader { SatCnfReader() {} // Loads the given cnf filename into the given problem. - bool Load(const string& filename, LinearBooleanProblem* problem) { + bool Load(const std::string& filename, LinearBooleanProblem* problem) { problem->Clear(); problem->set_name(ExtractProblemName(filename)); is_wcnf_ = false; @@ -46,7 +45,7 @@ class SatCnfReader { slack_variable_weights_.clear(); int num_lines = 0; - for (const string& line : FileLines(filename)) { + for (const std::string& line : FileLines(filename)) { ++num_lines; ProcessNewLine(problem, line); } @@ -78,22 +77,19 @@ class SatCnfReader { private: // Since the problem name is not stored in the cnf format, we infer it from // the file name. - static string ExtractProblemName(const string& filename) { + static std::string ExtractProblemName(const std::string& filename) { const int found = filename.find_last_of("/"); - const string problem_name = found != string::npos ? + const std::string problem_name = found != std::string::npos ? filename.substr(found + 1) : filename; return problem_name; } - void ProcessNewLine(LinearBooleanProblem* problem, const string& line) { + void ProcessNewLine(LinearBooleanProblem* problem, const std::string& line) { static const char kWordDelimiters[] = " "; - std::vector words; + std::vector words; SplitStringUsing(line, kWordDelimiters, &words); - if (words.size() == 0 || words[0] == "c") return; - - // TODO(user): It seems our files contains 2 lines of junk at the end. - // Hence this test. Clear them? - if (words[0] == "%" || end_marker_seen_) { + if (words.size() == 0 || words[0] == "c" || end_marker_seen_) return; + if (words[0] == "%") { end_marker_seen_ = true; return; } @@ -141,9 +137,10 @@ class SatCnfReader { // Used for the wcnf format. bool is_wcnf_; + // Some files have text after %. This indicates if we have seen the '%'. + bool end_marker_seen_; std::vector slack_variable_weights_; int64 hard_weight_; - bool end_marker_seen_; DISALLOW_COPY_AND_ASSIGN(SatCnfReader); }; diff --git a/examples/cpp/sports_scheduling.cc b/examples/cpp/sports_scheduling.cc index 80e9b14fd9..0e397ae136 100644 --- a/examples/cpp/sports_scheduling.cc +++ b/examples/cpp/sports_scheduling.cc @@ -400,7 +400,7 @@ void SportsScheduling(int num_teams) { LOG(INFO) << "Solution found in " << solver.wall_time() << " ms, and " << solver.failures() << " failures."; for (int team_index = 0; team_index < num_teams; ++team_index) { - string line; + std::string line; for (int day = 0; day < full_season; ++day) { const int opponent = collector->Value(0, opponents[team_index][day]); const int home_away = collector->Value(0, home_aways[team_index][day]); diff --git a/examples/cpp/strawberry_fields_with_column_generation.cc b/examples/cpp/strawberry_fields_with_column_generation.cc index 74f30fbb9d..d6a0b554dc 100644 --- a/examples/cpp/strawberry_fields_with_column_generation.cc +++ b/examples/cpp/strawberry_fields_with_column_generation.cc @@ -51,8 +51,8 @@ // // No attempt is made to force integrality. -#include -#include // strlen +#include +#include // strlen #include #include "base/unique_ptr.h" #include @@ -66,7 +66,6 @@ #include "base/stringprintf.h" #include "linear_solver/linear_solver.h" -using std::string; DEFINE_bool(colgen_verbose, false, "print verbosely"); DEFINE_bool(colgen_complete, false, "generate all columns initially"); @@ -289,7 +288,7 @@ class Box { + kFixedCost; } - string DebugString() const { + std::string DebugString() const { return StringPrintf("[%d,%dx%d,%d]c%d", x_min(), y_min(), x_max(), y_max(), Cost()); } @@ -311,7 +310,7 @@ struct BoxLessThan { class CoveringProblem { public: - // Grid is a row-major string of length width*height with '@' for an + // Grid is a row-major std::string of length width*height with '@' for an // occupied cell (strawberry) and '.' for an empty cell. Solver is // not owned. CoveringProblem(MPSolver* const solver, const Instance& instance) @@ -455,15 +454,15 @@ class CoveringProblem { return var; } - string PrintGrid() const { - string output = StringPrintf("width = %d, height = %d, max_boxes = %d\n", + std::string PrintGrid() const { + std::string output = StringPrintf("width = %d, height = %d, max_boxes = %d\n", width_, height_, max_boxes_); for (int y = 0; y < height_; ++y) { StringAppendF(&output, "%s\n", - string(grid_ + width_ * y, width_).c_str()); + std::string(grid_ + width_ * y, width_).c_str()); } return output; } @@ -472,10 +471,10 @@ class CoveringProblem { // and graphical depiction of covering using upper case letters for // integral coverage and lower case for coverage using combination // of fractional boxes. - string PrintCovering() const { + std::string PrintCovering() const { static const double kTolerance = 1e-5; - string output = StringPrintf("cost = %lf\n", solver_->objective_value()); - scoped_ptr display(new char[(width_ + 1) * height_ + 1]); + std::string output = StringPrintf("cost = %lf\n", solver_->objective_value()); + std::unique_ptr display(new char[(width_ + 1) * height_ + 1]); for (int y = 0; y < height_; ++y) { memcpy(display.get() + y * (width_ + 1), grid_ + width_ * y, @@ -617,7 +616,7 @@ void SolveInstance(const Instance& instance, } // namespace operations_research int main(int argc, char** argv) { - string usage = "column_generation\n"; + std::string usage = "column_generation\n"; usage += " --colgen_verbose print verbosely\n"; usage += " --colgen_max_iterations max columns to generate\n"; usage += " --colgen_complete generate all columns at start\n"; diff --git a/examples/cpp/tsp.cc b/examples/cpp/tsp.cc index 9337bfb724..ca10652fa7 100644 --- a/examples/cpp/tsp.cc +++ b/examples/cpp/tsp.cc @@ -148,7 +148,7 @@ int main(int argc, char **argv) { // Inspect solution. // Only one route here; otherwise iterate from 0 to routing.vehicles() - 1 const int route_number = 0; - string route; + std::string route; for (int64 node = routing.Start(route_number); !routing.IsEnd(node); node = solution->Value(routing.NextVar(node))) { diff --git a/makefiles/Makefile.cpp.mk b/makefiles/Makefile.cpp.mk index 3cefee0e50..3d2bd875cd 100644 --- a/makefiles/Makefile.cpp.mk +++ b/makefiles/Makefile.cpp.mk @@ -306,6 +306,7 @@ CONSTRAINT_SOLVER_LIB_OBJS = \ $(OBJ_DIR)/expressions.$O\ $(OBJ_DIR)/gcc.$O\ $(OBJ_DIR)/hybrid.$O\ + $(OBJ_DIR)/graph_constraints.$O\ $(OBJ_DIR)/interval.$O\ $(OBJ_DIR)/io.$O\ $(OBJ_DIR)/local_search.$O\ @@ -396,6 +397,9 @@ $(OBJ_DIR)/expressions.$O:$(SRC_DIR)/constraint_solver/expressions.cc $(OBJ_DIR)/gcc.$O:$(SRC_DIR)/constraint_solver/gcc.cc $(CCC) $(CFLAGS) -c $(SRC_DIR)/constraint_solver/gcc.cc $(OBJ_OUT)$(OBJ_DIR)$Sgcc.$O +$(OBJ_DIR)/graph_constraints.$O:$(SRC_DIR)/constraint_solver/graph_constraints.cc + $(CCC) $(CFLAGS) -c $(SRC_DIR)/constraint_solver/graph_constraints.cc $(OBJ_OUT)$(OBJ_DIR)$Sgraph_constraints.$O + $(OBJ_DIR)/hybrid.$O:$(SRC_DIR)/constraint_solver/hybrid.cc $(CCC) $(CFLAGS) -c $(SRC_DIR)/constraint_solver/hybrid.cc $(OBJ_OUT)$(OBJ_DIR)$Shybrid.$O diff --git a/src/algorithms/hungarian.cc b/src/algorithms/hungarian.cc index 24e832aea3..c1e6348036 100644 --- a/src/algorithms/hungarian.cc +++ b/src/algorithms/hungarian.cc @@ -195,7 +195,7 @@ class HungarianOptimizer { // Return to Step 4 without altering any stars, primes, or covered lines. void AugmentPath(); - // The size of the problem, i.e. max(#agents, #tasks). + // The size of the problem, i.e. std::max(#agents, #tasks). int matrix_size_; // The expanded cost matrix. diff --git a/src/algorithms/knapsack_solver.cc b/src/algorithms/knapsack_solver.cc index b09697aa5d..8201a8dd92 100644 --- a/src/algorithms/knapsack_solver.cc +++ b/src/algorithms/knapsack_solver.cc @@ -346,13 +346,13 @@ int64 KnapsackCapacityPropagator::GetAdditionalProfit(int64 remaining_capacity, } const int64 additional_profit = std::max(additional_profit_when_no_break_item, - additional_profit_when_break_item); + additional_profit_when_break_item); CHECK_GE(additional_profit, 0); return additional_profit; } // ----- KnapsackGenericSolver ----- -KnapsackGenericSolver::KnapsackGenericSolver(const string& solver_name) +KnapsackGenericSolver::KnapsackGenericSolver(const std::string& solver_name) : BaseKnapsackSolver(solver_name), propagators_(), master_propagator_id_(kMasterPropagatorId), @@ -558,7 +558,7 @@ void KnapsackGenericSolver::UpdateBestSolution() { // number of items is less than 15. class KnapsackBruteForceSolver : public BaseKnapsackSolver { public: - explicit KnapsackBruteForceSolver(const string& solver_name); + explicit KnapsackBruteForceSolver(const std::string& solver_name); // Initializes the solver and enters the problem to be solved. void Init(const std::vector& profits, @@ -583,7 +583,7 @@ class KnapsackBruteForceSolver : public BaseKnapsackSolver { DISALLOW_COPY_AND_ASSIGN(KnapsackBruteForceSolver); }; -KnapsackBruteForceSolver::KnapsackBruteForceSolver(const string& solver_name) +KnapsackBruteForceSolver::KnapsackBruteForceSolver(const std::string& solver_name) : BaseKnapsackSolver(solver_name), num_items_(0), capacity_(0LL), @@ -687,7 +687,7 @@ struct KnapsackItemWithEfficiency { // than KnapsackGenericSolver. class Knapsack64ItemsSolver : public BaseKnapsackSolver { public: - explicit Knapsack64ItemsSolver(const string& solver_name); + explicit Knapsack64ItemsSolver(const std::string& solver_name); // Initializes the solver and enters the problem to be solved. void Init(const std::vector& profits, @@ -735,7 +735,7 @@ bool CompareKnapsackItemWithEfficiencyInDecreasingEfficiencyOrder( } // ----- Knapsack64ItemsSolver ----- -Knapsack64ItemsSolver::Knapsack64ItemsSolver(const string& solver_name) +Knapsack64ItemsSolver::Knapsack64ItemsSolver(const std::string& solver_name) : BaseKnapsackSolver(solver_name), sorted_items_(), sum_profits_(), @@ -946,7 +946,7 @@ void Knapsack64ItemsSolver::BuildBestSolution() { // Ulrich Pferschy and David Pisinger, Springer book (ISBN 978-3540402862). class KnapsackDynamicProgrammingSolver : public BaseKnapsackSolver { public: - explicit KnapsackDynamicProgrammingSolver(const string& solver_name); + explicit KnapsackDynamicProgrammingSolver(const std::string& solver_name); // Initializes the solver and enters the problem to be solved. void Init(const std::vector& profits, @@ -974,7 +974,7 @@ class KnapsackDynamicProgrammingSolver : public BaseKnapsackSolver { // ----- KnapsackDynamicProgrammingSolver ----- KnapsackDynamicProgrammingSolver::KnapsackDynamicProgrammingSolver( - const string& solver_name) : BaseKnapsackSolver(solver_name), + const std::string& solver_name) : BaseKnapsackSolver(solver_name), profits_(), weights_(), capacity_(0), @@ -1045,7 +1045,7 @@ class KnapsackMIPSolver : public BaseKnapsackSolver { public: KnapsackMIPSolver( MPSolver::OptimizationProblemType problem_type, - const string& solver_name); + const std::string& solver_name); // Initializes the solver and enters the problem to be solved. void Init(const std::vector& profits, @@ -1069,7 +1069,7 @@ class KnapsackMIPSolver : public BaseKnapsackSolver { }; KnapsackMIPSolver::KnapsackMIPSolver( - MPSolver::OptimizationProblemType problem_type, const string& solver_name) + MPSolver::OptimizationProblemType problem_type, const std::string& solver_name) : BaseKnapsackSolver(solver_name), problem_type_(problem_type), profits_(), @@ -1125,7 +1125,7 @@ int64 KnapsackMIPSolver::Solve() { } // ----- KnapsackSolver ----- -KnapsackSolver::KnapsackSolver(const string& solver_name) +KnapsackSolver::KnapsackSolver(const std::string& solver_name) : solver_(new KnapsackGenericSolver(solver_name)), known_value_(), best_solution_(), @@ -1136,7 +1136,7 @@ KnapsackSolver::KnapsackSolver(const string& solver_name) } KnapsackSolver::KnapsackSolver(SolverType solver_type, - const string& solver_name) + const std::string& solver_name) : solver_(), known_value_(), best_solution_(), @@ -1303,7 +1303,7 @@ bool KnapsackSolver::BestSolutionContains(int item_id) const { : solver_->best_solution(mapped_item_id); } -string KnapsackSolver::GetName() const { +std::string KnapsackSolver::GetName() const { return solver_->GetName(); } diff --git a/src/algorithms/knapsack_solver.h b/src/algorithms/knapsack_solver.h index 9bb9d0be25..5c27ecf65a 100644 --- a/src/algorithms/knapsack_solver.h +++ b/src/algorithms/knapsack_solver.h @@ -68,7 +68,6 @@ #include "base/macros.h" #include "base/scoped_ptr.h" -using std::string; namespace operations_research { @@ -125,8 +124,8 @@ class KnapsackSolver { KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER }; - explicit KnapsackSolver(const string& solver_name); - KnapsackSolver(SolverType solver_type, const string& solver_name); + explicit KnapsackSolver(const std::string& solver_name); + KnapsackSolver(SolverType solver_type, const std::string& solver_name); virtual ~KnapsackSolver(); // Initializes the solver and enters the problem to be solved. @@ -139,7 +138,7 @@ class KnapsackSolver { // Returns true if the item 'item_id' is packed in the optimal knapsack. bool BestSolutionContains(int item_id) const; - string GetName() const; + std::string GetName() const; bool use_reduction() const { return use_reduction_; } void set_use_reduction(bool use_reduction) { use_reduction_ = use_reduction; } @@ -469,7 +468,7 @@ class KnapsackCapacityPropagator : public KnapsackPropagator { // This the base class for knapsack solvers. class BaseKnapsackSolver { public: - explicit BaseKnapsackSolver(const string& solver_name) + explicit BaseKnapsackSolver(const std::string& solver_name) : solver_name_(solver_name) {} virtual ~BaseKnapsackSolver() {} @@ -492,10 +491,10 @@ class BaseKnapsackSolver { // Returns true if the item 'item_id' is packed in the optimal knapsack. virtual bool best_solution(int item_id) const = 0; - virtual string GetName() const { return solver_name_; } + virtual std::string GetName() const { return solver_name_; } private: - const string solver_name_; + const std::string solver_name_; }; // ----- KnapsackGenericSolver ----- @@ -509,7 +508,7 @@ class BaseKnapsackSolver { // to select next item (see for instance Dobson's aggregated efficiency). class KnapsackGenericSolver : public BaseKnapsackSolver { public: - explicit KnapsackGenericSolver(const string& solver_name); + explicit KnapsackGenericSolver(const std::string& solver_name); virtual ~KnapsackGenericSolver(); // Initializes the solver and enters the problem to be solved. diff --git a/src/base/file.cc b/src/base/file.cc index a6def9f3a9..390e9b3c64 100644 --- a/src/base/file.cc +++ b/src/base/file.cc @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include #include #include #if defined(_MSC_VER) @@ -22,6 +21,7 @@ #include #endif +#include #include #include "base/file.h" @@ -164,23 +164,23 @@ Status GetContents(const std::string& filename, std::string* output, return Status(size == file->ReadToString(output, size)); } -bool ReadFileToString(const string& file_name, string* output) { +bool ReadFileToString(const std::string& file_name, std::string* output) { return GetContents(file_name, output, file::Defaults()).ok(); } -bool WriteStringToFile(const string& data, const string& file_name) { +bool WriteStringToFile(const std::string& data, const std::string& file_name) { return SetContents(file_name, data, file::Defaults()).ok(); } namespace { class NoOpErrorCollector : public google::protobuf::io::ErrorCollector { public: - virtual void AddError(int line, int column, const string& message) { } + virtual void AddError(int line, int column, const std::string& message) { } }; } // namespace -bool ReadFileToProto(const string& file_name, google::protobuf::Message* proto) { - string str; +bool ReadFileToProto(const std::string& file_name, google::protobuf::Message* proto) { + std::string str; if (!ReadFileToString(file_name, &str)) { LOG(INFO) << "Could not read " << file_name; return false; @@ -207,30 +207,30 @@ bool ReadFileToProto(const string& file_name, google::protobuf::Message* proto) return false; } -void ReadFileToProtoOrDie(const string& file_name, google::protobuf::Message* proto) { +void ReadFileToProtoOrDie(const std::string& file_name, google::protobuf::Message* proto) { CHECK(ReadFileToProto(file_name, proto)) << "file_name: " << file_name; } bool WriteProtoToASCIIFile(const google::protobuf::Message& proto, - const string& file_name) { - string proto_string; + const std::string& file_name) { + std::string proto_string; return google::protobuf::TextFormat::PrintToString(proto, &proto_string) && WriteStringToFile(proto_string, file_name); } void WriteProtoToASCIIFileOrDie(const google::protobuf::Message& proto, - const string& file_name) { + const std::string& file_name) { CHECK(WriteProtoToASCIIFile(proto, file_name)) << "file_name: " << file_name; } -bool WriteProtoToFile(const google::protobuf::Message& proto, const string& file_name) { - string proto_string; +bool WriteProtoToFile(const google::protobuf::Message& proto, const std::string& file_name) { + std::string proto_string; return proto.AppendToString(&proto_string) && WriteStringToFile(proto_string, file_name); } void WriteProtoToFileOrDie(const google::protobuf::Message& proto, - const string& file_name) { + const std::string& file_name) { CHECK(WriteProtoToFile(proto, file_name)) << "file_name: " << file_name; } diff --git a/src/base/file.h b/src/base/file.h index af18ce3cf6..8a2b39b47d 100644 --- a/src/base/file.h +++ b/src/base/file.h @@ -29,8 +29,6 @@ // IO specifications. namespace operations_research { -using std::string; - class File { public: // Opens file "name" with flags specified by "flag". @@ -38,7 +36,7 @@ class File { static File* Open(const char* const name, const char* const flag); #ifndef SWIG // no overloading - inline static File* Open(const string& name, const char* const mode) { + inline static File* Open(const std::string& name, const char* const mode) { return Open(name.c_str(), mode); } #endif @@ -48,7 +46,7 @@ class File { static File* OpenOrDie(const char* const name, const char* const flag); #ifndef SWIG // no overloading - inline static File* OpenOrDie(const string& name, + inline static File* OpenOrDie(const std::string& name, const char* const flag) { return OpenOrDie(name.c_str(), flag); } @@ -61,13 +59,13 @@ class File { // If read failed, program will exit. void ReadOrDie(void* const buff, size_t size); - // Reads a line from file to a string. + // Reads a line from file to a std::string. // Each line must be no more than max_length bytes char* ReadLine(char* const output, uint64 max_length); - // Reads the whole file to a string, with a maximum length of 'max_length'. + // Reads the whole file to a std::string, with a maximum length of 'max_length'. // Returns the number of bytes read. - int64 ReadToString(string* const line, uint64 max_length); + int64 ReadToString(std::string* const line, uint64 max_length); // Writes "size" bytes of buff to file, buff should be pre-allocated. size_t Write(const void* const buff, size_t size); @@ -76,11 +74,11 @@ class File { // If write failed, program will exit. void WriteOrDie(const void* const buff, size_t size); - // Writes a string to file. - size_t WriteString(const string& line); + // Writes a std::string to file. + size_t WriteString(const std::string& line); - // Writes a string to file and append a "\n". - bool WriteLine(const string& line); + // Writes a std::string to file and append a "\n". + bool WriteLine(const std::string& line); // Closes the file. bool Close(); @@ -95,7 +93,7 @@ class File { static void Init(); // Returns the file name. - string filename() const; + std::string filename() const; // Deletes a file. static bool Delete(const char* const name); @@ -106,10 +104,10 @@ class File { bool Open() const; private: - File(FILE* const descriptor, const string& name); + File(FILE* const descriptor, const std::string& name); FILE* f_; - const string name_; + const std::string name_; }; namespace file { @@ -127,25 +125,25 @@ inline int Defaults() { return 0xBABA; } // A reduced version of the file::SetContents() function, which as of 2013-04 // can only be used with flags = file::Defaults(). -Status SetContents(const string& filename, const string& contents, +Status SetContents(const std::string& filename, const std::string& contents, int flags); // A reduced version of the file::GetContents() function, which as of 2013-09 // can only be used with flags = file::Defaults(). -Status GetContents(const string& filename, string* output, +Status GetContents(const std::string& filename, std::string* output, int flags); -bool ReadFileToString(const string& file_name, string* output); -bool WriteStringToFile(const string& data, const string& file_name); -bool ReadFileToProto(const string& file_name, google::protobuf::Message* proto); -void ReadFileToProtoOrDie(const string& file_name, google::protobuf::Message* proto); +bool ReadFileToString(const std::string& file_name, std::string* output); +bool WriteStringToFile(const std::string& data, const std::string& file_name); +bool ReadFileToProto(const std::string& file_name, google::protobuf::Message* proto); +void ReadFileToProtoOrDie(const std::string& file_name, google::protobuf::Message* proto); bool WriteProtoToASCIIFile(const google::protobuf::Message& proto, - const string& file_name); + const std::string& file_name); void WriteProtoToASCIIFileOrDie(const google::protobuf::Message& proto, - const string& file_name); -bool WriteProtoToFile(const google::protobuf::Message& proto, const string& file_name); + const std::string& file_name); +bool WriteProtoToFile(const google::protobuf::Message& proto, const std::string& file_name); void WriteProtoToFileOrDie(const google::protobuf::Message& proto, - const string& file_name); + const std::string& file_name); } // namespace file diff --git a/src/base/filelinereader.cc b/src/base/filelinereader.cc index 7c5bf58d4c..897974a48f 100644 --- a/src/base/filelinereader.cc +++ b/src/base/filelinereader.cc @@ -14,7 +14,7 @@ #include "base/filelinereader.h" -#include +#include #include #include "base/file.h" diff --git a/src/base/hash.h b/src/base/hash.h index 99c17892e4..9b415273a0 100644 --- a/src/base/hash.h +++ b/src/base/hash.h @@ -148,7 +148,7 @@ template struct hash { size_t operator()(T *x) const { return reinterpret_cast(x); } }; -// hash and hash are already defined with STLport. +// hash and hash are already defined with STLport. # ifndef STLPORT template<> struct hash { size_t operator()(int64 x) const { return static_cast(x); } diff --git a/src/base/integral_types.h b/src/base/integral_types.h index 751bcbc42d..b2c9733f59 100644 --- a/src/base/integral_types.h +++ b/src/base/integral_types.h @@ -76,7 +76,7 @@ typedef long sword_t; // NOLINT #define GG_LONGLONG(x) x##I64 #define GG_ULONGLONG(x) x##UI64 -// Length modifier in printf format string for int64's (e.g. within %d) +// Length modifier in printf format std::string for int64's (e.g. within %d) #define GG_LL_FORMAT "I64" // As in printf("%I64d", ...) #define GG_LL_FORMAT_W L"I64" diff --git a/src/base/jniutil.h b/src/base/jniutil.h index 64f55151fb..9d15486fb6 100644 --- a/src/base/jniutil.h +++ b/src/base/jniutil.h @@ -27,8 +27,8 @@ class JNIUtil { return env->NewStringUTF(cstr); } - // Creates a null-terminated UTF-8 encoded C string from a jstring. - // The returned string should be "delete[]"-ed when no longer needed. + // Creates a null-terminated UTF-8 encoded C std::string from a jstring. + // The returned std::string should be "delete[]"-ed when no longer needed. static char* MakeCString(JNIEnv* env, jstring str) { if (str == NULL) return NULL; jsize length = env->GetStringUTFLength(str); diff --git a/src/base/join.cc b/src/base/join.cc index 3fe98c1d21..a39a18fbe9 100644 --- a/src/base/join.cc +++ b/src/base/join.cc @@ -73,7 +73,7 @@ std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c) { } std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, - const AlphaNum &d) { + const AlphaNum &d) { std::string result; result.resize(a.size() + b.size() + c.size() + d.size()); char *const begin = &*result.begin(); @@ -83,7 +83,7 @@ std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, } std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, - const AlphaNum &d, const AlphaNum &e) { + const AlphaNum &d, const AlphaNum &e) { std::string result; result.resize(a.size() + b.size() + c.size() + d.size() + e.size()); char *const begin = &*result.begin(); @@ -94,7 +94,7 @@ std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, } std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, - const AlphaNum &d, const AlphaNum &e, const AlphaNum &f) { + const AlphaNum &d, const AlphaNum &e, const AlphaNum &f) { std::string result; result.resize(a.size() + b.size() + c.size() + d.size() + e.size() + f.size()); @@ -106,8 +106,8 @@ std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, } std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, - const AlphaNum &d, const AlphaNum &e, const AlphaNum &f, - const AlphaNum &g) { + const AlphaNum &d, const AlphaNum &e, const AlphaNum &f, + const AlphaNum &g) { std::string result; result.resize(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() + g.size()); @@ -120,8 +120,8 @@ std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, } std::string StrCat(const AlphaNum &a, const AlphaNum &b, const AlphaNum &c, - const AlphaNum &d, const AlphaNum &e, const AlphaNum &f, - const AlphaNum &g, const AlphaNum &h) { + const AlphaNum &d, const AlphaNum &e, const AlphaNum &f, + const AlphaNum &g, const AlphaNum &h) { std::string result; result.resize(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() + g.size() + h.size()); diff --git a/src/base/join.h b/src/base/join.h index 76e765738c..745e897f39 100644 --- a/src/base/join.h +++ b/src/base/join.h @@ -27,7 +27,7 @@ namespace operations_research { const int kFastToBufferSize = 32; // Writes output to the beginning of the given buffer. Returns a pointer to the -// end of the string (i.e. to the NUL char). Buffer must be at least 12 bytes. +// end of the std::string (i.e. to the NUL char). Buffer must be at least 12 bytes. // Not actually fast, but maybe someday! template char* NumToBuffer(T i, char* buffer) { std::stringstream ss; diff --git a/src/base/python-swig.cc b/src/base/python-swig.cc index 27d272edd3..8ec386d772 100644 --- a/src/base/python-swig.cc +++ b/src/base/python-swig.cc @@ -45,7 +45,7 @@ template PyObject* PyObjFrom(const T& c) { } #ifdef HAS_GLOBAL_STRING -template <> bool PyObjAs(PyObject* pystr, ::string* cstr) { +template <> bool PyObjAs(PyObject* pystr, ::std::string* cstr) { char* buf; Py_ssize_t len; #if PY_VERSION_HEX >= 0x03030000 @@ -75,7 +75,7 @@ template bool PyObjAs(PyObject* pystr, std::string* cstr) { return true; } #ifdef HAS_GLOBAL_STRING -template <> PyObject* PyObjFrom(const ::string& c) { +template <> PyObject* PyObjFrom(const ::std::string& c) { return PyString_FromStringAndSize(c.data(), c.size()); } #endif diff --git a/src/base/random.cc b/src/base/random.cc index 05e21ecd7c..fd5085974e 100644 --- a/src/base/random.cc +++ b/src/base/random.cc @@ -81,7 +81,7 @@ int32 ACMRandom::HostnamePidTimeSeed() { } const int namelen = strlen(name); for (int i = 0; i < sizeof(uint32) * 3; ++i) { // NOLINT - name[namelen + i] = '\0'; // so we mix 0's once we get to end-of-string + name[namelen + i] = '\0'; // so we mix 0's once we get to end-of-std::string } #if defined(__GNUC__) uint32 a = getpid(); diff --git a/src/base/random.h b/src/base/random.h index 6532660169..9a6bb2c0f4 100644 --- a/src/base/random.h +++ b/src/base/random.h @@ -58,7 +58,7 @@ class ACMRandom { // RandomNumberGenerator concept. Example: // ACMRandom rand(my_seed); - // random_shuffle(myvec.begin(), myvec.end(), rand); + // std::random_shuffle(myvec.begin(), myvec.end(), rand); #if defined(_MSC_VER) typedef __int64 difference_type; // NOLINT #else @@ -78,7 +78,7 @@ class ACMRandom { class MTRandom : public ACMRandom { public: explicit MTRandom(int32 seed) : ACMRandom(seed) { } - // MTRandom also supports a string seed. + // MTRandom also supports a std::string seed. explicit MTRandom(const std::string& str_seed) : ACMRandom(GenerateInt32SeedFromString(str_seed)) { } diff --git a/src/base/split.cc b/src/base/split.cc index f34a47a610..8fb0092f16 100644 --- a/src/base/split.cc +++ b/src/base/split.cc @@ -12,6 +12,7 @@ // limitations under the License. #include "base/split.h" + #if defined(_MSC_VER) #include #endif // _MSC_VER @@ -20,17 +21,17 @@ namespace operations_research { // ---------------------------------------------------------------------- // SplitStringUsing() -// Split a string using a character delimiter. Append the components +// Split a std::string using a character delimiter. Append the components // to 'result'. // // Note: For multi-character delimiters, this routine will split on *ANY* of -// the characters in the string, not the entire string as a single delimiter. +// the characters in the std::string, not the entire std::string as a single delimiter. // ---------------------------------------------------------------------- template static inline void SplitStringToIteratorUsing(const std::string& full, const char* delim, - ITR& result) { + ITR& result) { // NOLINT // Optimize the common case where delim is a single character. if (delim[0] != '\0' && delim[1] == '\0') { char c = delim[0]; @@ -69,8 +70,7 @@ void SplitStringUsing(const std::string& full, } namespace strings { -std::vector Split(const std::string& full, const char* delim, - int flags) { +std::vector Split(const std::string& full, const char* delim, int flags) { CHECK_EQ(SkipEmpty(), flags); std::vector out; SplitStringUsing(full, delim, &out); diff --git a/src/base/split.h b/src/base/split.h index dddfe19e28..8abc1886a3 100644 --- a/src/base/split.h +++ b/src/base/split.h @@ -26,7 +26,7 @@ namespace operations_research { // ---------------------------------------------------------------------- // SplitStringUsing() -// Split a string using a character delimiter. Append the components +// Split a std::string using a character delimiter. Append the components // to 'result'. If there are consecutive delimiters, this function skips // over all of them. // ---------------------------------------------------------------------- @@ -36,12 +36,11 @@ void SplitStringUsing(const std::string& full, const char* delim, // We define here a very truncated version of the powerful strings::Split() // function. As of 2013-04, it can only be used like this: // const char* separators = ...; -// std::vector x = strings::Split( +// std::vector x = strings::Split( // full, strings::delimiter::AnyOf(separators), strings::SkipEmpty()); namespace strings { -// Slightly different API that directly returns the std::vector. -std::vector Split(const std::string& full, const char* delim, - int flags); +// Slightly different API that directly returns the std::vector. +std::vector Split(const std::string& full, const char* delim, int flags); namespace delimiter { inline const char* AnyOf(const char* x) { return x; } } // namespace delimiter diff --git a/src/base/stl_util.h b/src/base/stl_util.h index 2db0067eed..a2fe44b921 100644 --- a/src/base/stl_util.h +++ b/src/base/stl_util.h @@ -58,15 +58,15 @@ inline void STLStringResizeUninitialized(std::string* s, size_t new_size) { s->resize(new_size); } -// Return a mutable char* pointing to a string's internal buffer, +// Return a mutable char* pointing to a std::string's internal buffer, // which may not be null-terminated. Writing through this pointer will -// modify the string. +// modify the std::string. // // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the -// next call to a string method that invalidates iterators. +// next call to a std::string method that invalidates iterators. // // As of 2006-04, there is no standard-blessed way of getting a -// mutable reference to a string's internal buffer. However, issue 530 +// mutable reference to a std::string's internal buffer. However, issue 530 // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530) // proposes this as the method. According to Matt Austern, this should // already work on all current implementations. diff --git a/src/base/stringpiece.h b/src/base/stringpiece.h index 294a9f4d52..5e3a8350ee 100644 --- a/src/base/stringpiece.h +++ b/src/base/stringpiece.h @@ -11,25 +11,26 @@ // See the License for the specific language governing permissions and // limitations under the License. -// A string-like object that points to a sized piece of memory. +// A std::string-like object that points to a sized piece of memory. // // Functions or methods may use const StringPiece& parameters to accept either -// a "const char*" or a "string" value that will be implicitly converted to +// a "const char*" or a "std::string" value that will be implicitly converted to // a StringPiece. The implicit conversion means that it is often appropriate // to include this .h file in other files rather than forward-declaring // StringPiece as would be appropriate for most other Google classes. // // Systematic usage of StringPiece is encouraged as it will reduce unnecessary -// conversions from "const char*" to "string" and back again. +// conversions from "const char*" to "std::string" and back again. #ifndef OR_TOOLS_BASE_STRINGPIECE_H_ #define OR_TOOLS_BASE_STRINGPIECE_H_ #include + #include +#include #include #include -#include namespace operations_research { @@ -40,7 +41,7 @@ class StringPiece { public: // We provide non-explicit singleton constructors so users can pass - // in a "const char*" or a "string" wherever a "StringPiece" is + // in a "const char*" or a "std::string" wherever a "StringPiece" is // expected. StringPiece() : ptr_(NULL), length_(0) { } StringPiece(const char* str) // NOLINT @@ -52,7 +53,7 @@ class StringPiece { // data() may return a pointer to a buffer with embedded NULs, and the // returned buffer may or may not be null terminated. Therefore it is // typically a mistake to pass data() to a routine that expects a NUL - // terminated string. + // terminated std::string. const char* data() const { return ptr_; } int size() const { return length_; } int length() const { return length_; } @@ -94,8 +95,8 @@ class StringPiece { std::string as_string() const { return std::string(data(), size()); } - // We also define ToString() here, since many other string-like - // interfaces name the routine that converts to a C++ string + // We also define ToString() here, since many other std::string-like + // interfaces name the routine that converts to a C++ std::string // "ToString", and it's confusing to have the method that does that // for a StringPiece be called "as_string()". We also leave the // "as_string()" method defined here for existing code. diff --git a/src/base/strtoint.h b/src/base/strtoint.h index 68760ec24d..19dad45dab 100644 --- a/src/base/strtoint.h +++ b/src/base/strtoint.h @@ -57,7 +57,7 @@ inline int64 atoi64(const char *nptr) { return strto64(nptr, NULL, 10); } -// Convenience versions of the above that take a string argument. +// Convenience versions of the above that take a std::string argument. inline int32 atoi32(const std::string &s) { return atoi32(s.c_str()); } diff --git a/src/base/strutil.h b/src/base/strutil.h index e3ed6a52b6..4993f1773f 100644 --- a/src/base/strutil.h +++ b/src/base/strutil.h @@ -18,8 +18,6 @@ #include #include "base/stringpiece.h" -using std::string; - namespace operations_research { // ---------------------------------------------------------------------- // HasSuffixString() @@ -31,65 +29,65 @@ inline bool HasSuffixString(const StringPiece& str, return str.ends_with(suffix); } -inline string StrCat(const string& str1, const string& str2) { +inline std::string StrCat(const std::string& str1, const std::string& str2) { return str1 + str2; } -inline string StrCat(const string& str1, const string& str2, - const string& str3) { +inline std::string StrCat(const std::string& str1, const std::string& str2, + const std::string& str3) { return str1 + str2 + str3; } -inline string StrCat(const string& str1, const string& str2, - const string& str3, const string& str4) { +inline std::string StrCat(const std::string& str1, const std::string& str2, + const std::string& str3, const std::string& str4) { return str1 + str2 + str3 + str4; } -inline string StrCat(const string& str1, const string& str2, - const string& str3, const string& str4, - const string& str5) { +inline std::string StrCat(const std::string& str1, const std::string& str2, + const std::string& str3, const std::string& str4, + const std::string& str5) { return str1 + str2 + str3 + str4 + str5; } -inline string StrCat(const string& str1, const string& str2, - const string& str3, const string& str4, - const string& str5, const string& str6) { +inline std::string StrCat(const std::string& str1, const std::string& str2, + const std::string& str3, const std::string& str4, + const std::string& str5, const std::string& str6) { return str1 + str2 + str3 + str4 + str5 + str6; } -inline string StrCat(const string& str1, const string& str2, - const string& str3, const string& str4, - const string& str5, const string& str6, - const string& str7) { +inline std::string StrCat(const std::string& str1, const std::string& str2, + const std::string& str3, const std::string& str4, + const std::string& str5, const std::string& str6, + const std::string& str7) { return str1 + str2 + str3 + str4 + str5 + str6 + str7; } -inline string StrCat(const string& str1, const string& str2, - const string& str3, const string& str4, - const string& str5, const string& str6, - const string& str7, const string& str8) { +inline std::string StrCat(const std::string& str1, const std::string& str2, + const std::string& str3, const std::string& str4, + const std::string& str5, const std::string& str6, + const std::string& str7, const std::string& str8) { return str1 + str2 + str3 + str4 + str5 + str6 + str7 + str8; } -inline string StrCat(const string& str1, const string& str2, - const string& str3, const string& str4, - const string& str5, const string& str6, - const string& str7, const string& str8, - const string& str9) { +inline std::string StrCat(const std::string& str1, const std::string& str2, + const std::string& str3, const std::string& str4, + const std::string& str5, const std::string& str6, + const std::string& str7, const std::string& str8, + const std::string& str9) { return str1 + str2 + str3 + str4 + str5 + str6 + str7 + str8 + str9; } -inline void StrAppend(string* str1, const string& str2) { +inline void StrAppend(std::string* str1, const std::string& str2) { *str1 += str2; } -inline void StrAppend(string* str1, const string& str2, const string& str3) { +inline void StrAppend(std::string* str1, const std::string& str2, const std::string& str3) { *str1 += str2 + str3; } -inline void StrAppend(string* str1, const string& str2, const string& str3, - const string& str4) { +inline void StrAppend(std::string* str1, const std::string& str2, const std::string& str3, + const std::string& str4) { *str1 += str2 + str3 + str4; } } // namespace operations_research diff --git a/src/base/threadpool.cc b/src/base/threadpool.cc index e59ba99fd1..37ac60fb49 100644 --- a/src/base/threadpool.cc +++ b/src/base/threadpool.cc @@ -14,8 +14,8 @@ #include "tinythread.h" // NOLINT #include "base/macros.h" #include "base/mutex.h" -#include "base/threadpool.h" #include "base/synchronization.h" +#include "base/threadpool.h" namespace operations_research { void RunWorker(void* data) { diff --git a/src/constraint_solver/ac4r_table.cc b/src/constraint_solver/ac4r_table.cc index 8fd9ae7171..fbb7729fcc 100644 --- a/src/constraint_solver/ac4r_table.cc +++ b/src/constraint_solver/ac4r_table.cc @@ -382,7 +382,7 @@ class Ac4TableConstraint : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("AllowedAssignments(arity = %d, tuple_count = %d)", table_->NumVars(), table_->NumTuples()); } diff --git a/src/constraint_solver/alldiff_cst.cc b/src/constraint_solver/alldiff_cst.cc index ad3532c9a0..7c6d18a97b 100644 --- a/src/constraint_solver/alldiff_cst.cc +++ b/src/constraint_solver/alldiff_cst.cc @@ -13,7 +13,6 @@ // // AllDifferent constraints -#include #include #include "base/unique_ptr.h" #include @@ -34,7 +33,7 @@ class BaseAllDifferent : public Constraint { BaseAllDifferent(Solver* const s, const std::vector& vars) : Constraint(s), vars_(vars) {} ~BaseAllDifferent() {} - string DebugStringInternal(const string& name) const { + std::string DebugStringInternal(const std::string& name) const { return StringPrintf("%s(%s)", name.c_str(), JoinDebugStringPtr(vars_, ", ").c_str()); } @@ -58,7 +57,7 @@ class ValueAllDifferent : public BaseAllDifferent { void OneMove(int index); bool AllMoves(); - virtual string DebugString() const { + virtual std::string DebugString() const { return DebugStringInternal("ValueAllDifferent"); } virtual void Accept(ModelVisitor* const visitor) const { @@ -180,9 +179,9 @@ class RangeBipartiteMatching { // the bounds_ array (and set the active_size_ counter). void SortArray() { std::sort(min_sorted_.get(), min_sorted_.get() + size_, - CompareIntervalMin()); + CompareIntervalMin()); std::sort(max_sorted_.get(), max_sorted_.get() + size_, - CompareIntervalMax()); + CompareIntervalMax()); int64 min = min_sorted_[0]->min; int64 max = max_sorted_[0]->max + 1; @@ -410,7 +409,7 @@ class BoundsAllDifferent : public BaseAllDifferent { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return DebugStringInternal("BoundsAllDifferent"); } @@ -493,7 +492,7 @@ class SortConstraint : public Constraint { visitor->EndVisitConstraint(ModelVisitor::kSortingConstraint, this); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Sort(%s, %s)", JoinDebugStringPtr(ovars_, ", ").c_str(), JoinDebugStringPtr(svars_, ", ").c_str()); @@ -570,7 +569,7 @@ class AllDifferentExcept : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("AllDifferentExcept([%s], %" GG_LL_FORMAT "d", JoinDebugStringPtr(vars_, ", ").c_str(), escape_value_); @@ -662,7 +661,7 @@ class NullIntersectArrayExcept : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf( "NullIntersectArray([%s], [%s], escape = %" GG_LL_FORMAT "d", JoinDebugStringPtr(first_vars_, ", ").c_str(), diff --git a/src/constraint_solver/assignment.cc b/src/constraint_solver/assignment.cc index a601b0ab16..10696ce899 100644 --- a/src/constraint_solver/assignment.cc +++ b/src/constraint_solver/assignment.cc @@ -97,7 +97,7 @@ void IntVarElement::WriteToProto( int_var_assignment_proto->set_active(Activated()); } -string IntVarElement::DebugString() const { +std::string IntVarElement::DebugString() const { if (Activated()) { if (min_ == max_) { return StringPrintf("(%" GG_LL_FORMAT "d)", min_); @@ -218,9 +218,9 @@ void IntervalVarElement::WriteToProto( interval_var_assignment_proto->set_active(Activated()); } -string IntervalVarElement::DebugString() const { +std::string IntervalVarElement::DebugString() const { if (Activated()) { - string out; + std::string out; SStringPrintf(&out, "(start = %" GG_LL_FORMAT "d", start_min_); if (start_max_ != start_min_) { StringAppendF(&out, "..%" GG_LL_FORMAT "d", start_max_); @@ -336,7 +336,7 @@ void SequenceVarElement::WriteToProto( } } -string SequenceVarElement::DebugString() const { +std::string SequenceVarElement::DebugString() const { if (Activated()) { return StringPrintf("[forward %s, backward %s, unperformed [%s]]", IntVectorToString(forward_sequence_, " -> ").c_str(), @@ -464,13 +464,13 @@ namespace { template void IdToElementMap(AssignmentContainer* container, - hash_map* id_to_element_map) { + hash_map* id_to_element_map) { CHECK(id_to_element_map != nullptr); id_to_element_map->clear(); for (int i = 0; i < container->Size(); ++i) { E* const element = container->MutableElement(i); const V* const var = element->Var(); - const string& name = var->name(); + const std::string& name = var->name(); if (name.empty()) { LOG(INFO) << "Cannot save/load variables with empty name" << "; variable will be ignored"; @@ -484,9 +484,9 @@ void IdToElementMap(AssignmentContainer* container, } template -void LoadElement(const hash_map& id_to_element_map, +void LoadElement(const hash_map& id_to_element_map, const P& proto) { - const string& var_id = proto.var_id(); + const std::string& var_id = proto.var_id(); CHECK(!var_id.empty()); E* element = nullptr; if (FindCopy(id_to_element_map, var_id, &element)) { @@ -499,7 +499,7 @@ void LoadElement(const hash_map& id_to_element_map, } // namespace -bool Assignment::Load(const string& filename) { +bool Assignment::Load(const std::string& filename) { File* file = File::Open(filename, "r"); if (file == nullptr) { LOG(INFO) << "Cannot open " << filename; @@ -536,7 +536,7 @@ void RealLoad(const AssignmentProto& assignment_proto, } } if (!fast_load) { - hash_map id_to_element_map; + hash_map id_to_element_map; IdToElementMap(container, &id_to_element_map); for (int i = 0; i < (assignment_proto.*GetSize)(); ++i) { LoadElement(id_to_element_map, @@ -560,7 +560,7 @@ void Assignment::Load(const AssignmentProto& assignment_proto) { &AssignmentProto::sequence_var_assignment); if (assignment_proto.has_objective()) { const IntVarAssignmentProto& objective = assignment_proto.objective(); - const string objective_id = objective.var_id(); + const std::string objective_id = objective.var_id(); CHECK(!objective_id.empty()); if (HasObjective() && objective_id.compare(Objective()->name()) == 0) { const int64 obj_min = objective.min(); @@ -575,7 +575,7 @@ void Assignment::Load(const AssignmentProto& assignment_proto) { } } -bool Assignment::Save(const string& filename) const { +bool Assignment::Save(const std::string& filename) const { File* file = File::Open(filename, "w"); if (file == nullptr) { LOG(INFO) << "Cannot open " << filename; @@ -598,7 +598,7 @@ void RealSave(AssignmentProto* const assignment_proto, for (int i = 0; i < container.Size(); ++i) { const Element& element = container.Element(i); const Var* const var = element.Var(); - const string& name = var->name(); + const std::string& name = var->name(); if (!name.empty()) { Proto* const var_assignment_proto = (assignment_proto->*Add)(); element.WriteToProto(var_assignment_proto); @@ -619,7 +619,7 @@ void Assignment::Save(AssignmentProto* const assignment_proto) const { &AssignmentProto::add_sequence_var_assignment); if (HasObjective()) { const IntVar* objective = Objective(); - const string& name = objective->name(); + const std::string& name = objective->name(); if (!name.empty()) { IntVarAssignmentProto* objective = assignment_proto->mutable_objective(); objective->set_var_id(name); @@ -635,7 +635,7 @@ void Assignment::Save(AssignmentProto* const assignment_proto) const { } template -void RealDebugString(const Container& container, string* const out) { +void RealDebugString(const Container& container, std::string* const out) { for (int i = 0; i < container.Size(); ++i) { const Element& element = container.Element(i); if (element.Var() != nullptr) { @@ -645,8 +645,8 @@ void RealDebugString(const Container& container, string* const out) { } } -string Assignment::DebugString() const { - string out = "Assignment("; +std::string Assignment::DebugString() const { + std::string out = "Assignment("; RealDebugString(int_var_container_, &out); RealDebugString( interval_var_container_, &out); @@ -1046,7 +1046,7 @@ class RestoreAssignment : public DecisionBuilder { return nullptr; } - virtual string DebugString() const { return "RestoreAssignment"; } + virtual std::string DebugString() const { return "RestoreAssignment"; } private: Assignment* const assignment_; @@ -1063,7 +1063,7 @@ class StoreAssignment : public DecisionBuilder { return nullptr; } - virtual string DebugString() const { return "StoreAssignment"; } + virtual std::string DebugString() const { return "StoreAssignment"; } private: Assignment* const assignment_; diff --git a/src/constraint_solver/collect_variables.cc b/src/constraint_solver/collect_variables.cc index 7b6ffa4153..2093378dea 100644 --- a/src/constraint_solver/collect_variables.cc +++ b/src/constraint_solver/collect_variables.cc @@ -11,8 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include -#include +#include #include "base/hash.h" #include #include @@ -40,7 +39,7 @@ class CollectVariablesVisitor : public ModelParser { virtual ~CollectVariablesVisitor() {} - virtual void EndVisitModel(const string& solver_name) { + virtual void EndVisitModel(const std::string& solver_name) { PopArgumentHolder(); primaries_->assign(primary_set_.begin(), primary_set_.end()); std::sort(primaries_->begin(), primaries_->end()); @@ -52,7 +51,7 @@ class CollectVariablesVisitor : public ModelParser { std::sort(sequences_->begin(), sequences_->end()); } - virtual void EndVisitConstraint(const string& type_name, + virtual void EndVisitConstraint(const std::string& type_name, const Constraint* const constraint) { if (type_name.compare(ModelVisitor::kLinkExprVar) == 0 || (type_name.compare(ModelVisitor::kSumEqual) == 0 && @@ -164,14 +163,14 @@ class CollectVariablesVisitor : public ModelParser { } virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { IgnoreIntegerVariable(const_cast(variable)); delegate->Accept(this); } virtual void VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate) { if (delegate != nullptr) { delegate->Accept(this); @@ -189,7 +188,7 @@ class CollectVariablesVisitor : public ModelParser { } } - virtual string DebugString() const { return "CollectVariablesVisitor"; } + virtual std::string DebugString() const { return "CollectVariablesVisitor"; } private: void IgnoreIntegerVariable(IntVar* const var) { diff --git a/src/constraint_solver/constraint_solver.cc b/src/constraint_solver/constraint_solver.cc index bd40e24f9d..09a119c650 100644 --- a/src/constraint_solver/constraint_solver.cc +++ b/src/constraint_solver/constraint_solver.cc @@ -16,8 +16,8 @@ #include "constraint_solver/constraint_solver.h" -#include -#include +#include +#include #include #include "base/unique_ptr.h" @@ -108,7 +108,7 @@ Solver::DemonPriority Demon::priority() const { return Solver::NORMAL_PRIORITY; } -string Demon::DebugString() const { return "Demon"; } +std::string Demon::DebugString() const { return "Demon"; } void Demon::inhibit(Solver* const s) { if (stamp_ < kuint64max) { @@ -124,7 +124,7 @@ void Demon::desinhibit(Solver* const s) { // ------------------ Action class ------------------ -string Action::DebugString() const { return "Action"; } +std::string Action::DebugString() const { return "Action"; } // ------------------ Queue class ------------------ @@ -493,8 +493,8 @@ class TrailPacker { explicit TrailPacker(int block_size) : block_size_(block_size) {} virtual ~TrailPacker() {} int input_size() const { return block_size_ * sizeof(addrval); } - virtual void Pack(const addrval* block, string* packed_block) = 0; - virtual void Unpack(const string& packed_block, addrval* block) = 0; + virtual void Pack(const addrval* block, std::string* packed_block) = 0; + virtual void Unpack(const std::string& packed_block, addrval* block) = 0; private: const int block_size_; @@ -508,14 +508,14 @@ class NoCompressionTrailPacker : public TrailPacker { explicit NoCompressionTrailPacker(int block_size) : TrailPacker(block_size) {} virtual ~NoCompressionTrailPacker() {} - virtual void Pack(const addrval* block, string* packed_block) { + virtual void Pack(const addrval* block, std::string* packed_block) { DCHECK(block != nullptr); DCHECK(packed_block != nullptr); StringPiece block_str; block_str.set(block, this->input_size()); block_str.CopyToString(packed_block); } - virtual void Unpack(const string& packed_block, addrval* block) { + virtual void Unpack(const std::string& packed_block, addrval* block) { DCHECK(block != nullptr); memcpy(block, packed_block.c_str(), packed_block.size()); } @@ -534,7 +534,7 @@ class ZlibTrailPacker : public TrailPacker { virtual ~ZlibTrailPacker() {} - virtual void Pack(const addrval* block, string* packed_block) { + virtual void Pack(const addrval* block, std::string* packed_block) { DCHECK(block != nullptr); DCHECK(packed_block != nullptr); uLongf size = tmp_size_; @@ -547,7 +547,7 @@ class ZlibTrailPacker : public TrailPacker { block_str.CopyToString(packed_block); } - virtual void Unpack(const string& packed_block, addrval* block) { + virtual void Unpack(const std::string& packed_block, addrval* block) { DCHECK(block != nullptr); uLongf size = this->input_size(); const int result = @@ -642,7 +642,7 @@ class CompressedTrail { private: struct Block { - string compressed; + std::string compressed; Block* next; }; @@ -1077,7 +1077,7 @@ void Search::JumpBack() { jmpbuf_filled_ = false; CP_DO_FAIL(this); } else { - string explanation = "Failure outside of search"; + std::string explanation = "Failure outside of search"; solver_->AddConstraint(solver_->MakeFalseConstraint(explanation)); } } @@ -1094,7 +1094,7 @@ class UndoBranchSelector : public Action { s->ActiveSearch()->SetBranchSelector(nullptr); } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("UndoBranchSelector(%i)", depth_); } @@ -1114,7 +1114,7 @@ class ApplyBranchSelector : public DecisionBuilder { return nullptr; } - virtual string DebugString() const { return "Apply(BranchSelector)"; } + virtual std::string DebugString() const { return "Apply(BranchSelector)"; } private: ResultCallback1* const selector_; @@ -1392,9 +1392,9 @@ extern PropagationMonitor* BuildTrace(Solver* const s); extern ModelCache* BuildModelCache(Solver* const solver); extern DependencyGraph* BuildDependencyGraph(Solver* const solver); -string Solver::model_name() const { return name_; } +std::string Solver::model_name() const { return name_; } -Solver::Solver(const string& name, const SolverParameters& parameters) +Solver::Solver(const std::string& name, const SolverParameters& parameters) : name_(name), parameters_(parameters), queue_(new Queue(this)), @@ -1426,7 +1426,7 @@ Solver::Solver(const string& name, const SolverParameters& parameters) Init(); } -Solver::Solver(const string& name) +Solver::Solver(const std::string& name) : name_(name), parameters_(), queue_(new Queue(this)), @@ -1501,8 +1501,8 @@ const SolverParameters::TraceLevel SolverParameters::kDefaultTraceLevel = SolverParameters::NO_TRACE; const bool SolverParameters::kDefaultNameAllVariables = false; -string Solver::DebugString() const { - string out = "Solver(name = \"" + name_ + "\", state = "; +std::string Solver::DebugString() const { + std::string out = "Solver(name = \"" + name_ + "\", state = "; switch (state_) { case OUTSIDE_SEARCH: out += "OUTSIDE_SEARCH"; @@ -2128,8 +2128,8 @@ class ReverseDecision : public Decision { decision_->Accept(visitor); } - virtual string DebugString() const { - string str = "Reverse("; + virtual std::string DebugString() const { + std::string str = "Reverse("; str += decision_->DebugString(); str += ")"; return str; @@ -2394,7 +2394,7 @@ class AddConstraintDecisionBuilder : public DecisionBuilder { return nullptr; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("AddConstraintDecisionBuilder(%s)", constraint_->DebugString().c_str()); } @@ -2475,8 +2475,8 @@ IntExpr* Solver::CastExpression(const IntVar* const var) const { // --- Propagation object names --- -string Solver::GetName(const PropagationBaseObject* object) { - const string* name = FindOrNull(propagation_object_names_, object); +std::string Solver::GetName(const PropagationBaseObject* object) { + const std::string* name = FindOrNull(propagation_object_names_, object); if (name != nullptr) { return *name; } @@ -2489,15 +2489,15 @@ string Solver::GetName(const PropagationBaseObject* object) { return StringPrintf("Var<%s>", cast_info->expression->DebugString().c_str()); } else { - const string new_name = + const std::string new_name = StringPrintf("CastVar<%d>", anonymous_variable_index_++); propagation_object_names_[object] = new_name; return new_name; } } - const string base_name = object->BaseName(); + const std::string base_name = object->BaseName(); if (FLAGS_cp_name_variables && !base_name.empty()) { - const string new_name = + const std::string new_name = StringPrintf("%s_%d", base_name.c_str(), anonymous_variable_index_++); propagation_object_names_[object] = new_name; return new_name; @@ -2505,7 +2505,7 @@ string Solver::GetName(const PropagationBaseObject* object) { return empty_name_; } -void Solver::SetName(const PropagationBaseObject* object, const string& name) { +void Solver::SetName(const PropagationBaseObject* object, const std::string& name) { if (parameters_.store_names && GetName(object).compare(name) != 0) { // in particular if name.empty() propagation_object_names_[object] = name; @@ -2533,18 +2533,18 @@ std::ostream& operator<<(std::ostream& out, // ---------- PropagationBaseObject --------- -string PropagationBaseObject::name() const { - // TODO(user) : merge with GetName() code to remove a string copy. +std::string PropagationBaseObject::name() const { + // TODO(user) : merge with GetName() code to remove a std::string copy. return solver_->GetName(this); } -void PropagationBaseObject::set_name(const string& name) { +void PropagationBaseObject::set_name(const std::string& name) { solver_->SetName(this, name); } bool PropagationBaseObject::HasName() const { return solver_->HasName(this); } -string PropagationBaseObject::BaseName() const { return ""; } +std::string PropagationBaseObject::BaseName() const { return ""; } void PropagationBaseObject::ExecuteAll(const SimpleRevFIFO& demons) { solver_->ExecuteAll(demons); @@ -2556,7 +2556,7 @@ void PropagationBaseObject::EnqueueAll(const SimpleRevFIFO& demons) { // ---------- Decision Builder ---------- -string DecisionBuilder::DebugString() const { return "DecisionBuilder"; } +std::string DecisionBuilder::DebugString() const { return "DecisionBuilder"; } void DecisionBuilder::AppendMonitors(Solver* const solver, std::vector* const extras) {} @@ -2684,7 +2684,6 @@ const char ModelVisitor::kBranchesLimitArgument[] = "branches_limit"; const char ModelVisitor::kCapacityArgument[] = "capacity"; const char ModelVisitor::kCardsArgument[] = "cardinalities"; const char ModelVisitor::kCoefficientsArgument[] = "coefficients"; -const char ModelVisitor::kCompleteArgument[] = "complete"; const char ModelVisitor::kCountArgument[] = "count"; const char ModelVisitor::kCumulativeArgument[] = "cumulative"; const char ModelVisitor::kCumulsArgument[] = "cumuls"; @@ -2713,6 +2712,7 @@ const char ModelVisitor::kMinArgument[] = "min_value"; const char ModelVisitor::kModuloArgument[] = "modulo"; const char ModelVisitor::kNextsArgument[] = "nexts"; const char ModelVisitor::kOptionalArgument[] = "optional"; +const char ModelVisitor::kPartialArgument[] = "partial"; const char ModelVisitor::kPositionXArgument[] = "position_x"; const char ModelVisitor::kPositionYArgument[] = "position_y"; const char ModelVisitor::kRangeArgument[] = "range"; @@ -2751,20 +2751,20 @@ const char ModelVisitor::kTraceOperation[] = "trace"; ModelVisitor::~ModelVisitor() {} -void ModelVisitor::BeginVisitModel(const string& type_name) {} -void ModelVisitor::EndVisitModel(const string& type_name) {} +void ModelVisitor::BeginVisitModel(const std::string& type_name) {} +void ModelVisitor::EndVisitModel(const std::string& type_name) {} -void ModelVisitor::BeginVisitConstraint(const string& type_name, +void ModelVisitor::BeginVisitConstraint(const std::string& type_name, const Constraint* const constraint) {} -void ModelVisitor::EndVisitConstraint(const string& type_name, +void ModelVisitor::EndVisitConstraint(const std::string& type_name, const Constraint* const constraint) {} -void ModelVisitor::BeginVisitExtension(const string& type) {} -void ModelVisitor::EndVisitExtension(const string& type) {} +void ModelVisitor::BeginVisitExtension(const std::string& type) {} +void ModelVisitor::EndVisitExtension(const std::string& type) {} -void ModelVisitor::BeginVisitIntegerExpression(const string& type_name, +void ModelVisitor::BeginVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) {} -void ModelVisitor::EndVisitIntegerExpression(const string& type_name, +void ModelVisitor::EndVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) {} void ModelVisitor::VisitIntegerVariable(const IntVar* const variable, @@ -2775,7 +2775,7 @@ void ModelVisitor::VisitIntegerVariable(const IntVar* const variable, } void ModelVisitor::VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { if (delegate != nullptr) { delegate->Accept(this); @@ -2783,7 +2783,7 @@ void ModelVisitor::VisitIntegerVariable(const IntVar* const variable, } void ModelVisitor::VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate) { if (delegate != nullptr) { delegate->Accept(this); @@ -2796,45 +2796,45 @@ void ModelVisitor::VisitSequenceVariable(const SequenceVar* const variable) { } } -void ModelVisitor::VisitIntegerArgument(const string& arg_name, int64 value) {} +void ModelVisitor::VisitIntegerArgument(const std::string& arg_name, int64 value) {} -void ModelVisitor::VisitIntegerArrayArgument(const string& arg_name, +void ModelVisitor::VisitIntegerArrayArgument(const std::string& arg_name, const std::vector& values) {} -void ModelVisitor::VisitIntegerMatrixArgument(const string& arg_name, +void ModelVisitor::VisitIntegerMatrixArgument(const std::string& arg_name, const IntTupleSet& tuples) {} -void ModelVisitor::VisitIntegerExpressionArgument(const string& arg_name, +void ModelVisitor::VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument) { argument->Accept(this); } void ModelVisitor::VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { arguments[i]->Accept(this); } } -void ModelVisitor::VisitIntervalArgument(const string& arg_name, +void ModelVisitor::VisitIntervalArgument(const std::string& arg_name, IntervalVar* const argument) { argument->Accept(this); } void ModelVisitor::VisitIntervalArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { arguments[i]->Accept(this); } } -void ModelVisitor::VisitSequenceArgument(const string& arg_name, +void ModelVisitor::VisitSequenceArgument(const std::string& arg_name, SequenceVar* const argument) { argument->Accept(this); } void ModelVisitor::VisitSequenceArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { arguments[i]->Accept(this); } @@ -2876,7 +2876,7 @@ void ModelVisitor::VisitInt64ToInt64Extension( } void ModelVisitor::VisitInt64ToInt64AsArray( - Solver::IndexEvaluator1* const callback, const string& arg_name, + Solver::IndexEvaluator1* const callback, const std::string& arg_name, int64 index_max) { if (callback == nullptr) { return; @@ -3000,7 +3000,7 @@ class Trace : public PropagationMonitor { } } - virtual void PushContext(const string& context) { + virtual void PushContext(const std::string& context) { for (int i = 0; i < monitors_.size(); ++i) { monitors_[i]->PushContext(context); } @@ -3188,7 +3188,7 @@ class Trace : public PropagationMonitor { // events. virtual void Install() { SearchMonitor::Install(); } - virtual string DebugString() const { return "Trace"; } + virtual std::string DebugString() const { return "Trace"; } private: std::vector monitors_; @@ -3207,7 +3207,7 @@ PropagationMonitor* Solver::GetPropagationMonitor() const { // ----------------- Constraint class ------------------- -string Constraint::DebugString() const { return "Constraint"; } +std::string Constraint::DebugString() const { return "Constraint"; } void Constraint::PostAndPropagate() { FreezeQueue(); diff --git a/src/constraint_solver/constraint_solver.h b/src/constraint_solver/constraint_solver.h index 586d2a22b0..f8fbd6051d 100644 --- a/src/constraint_solver/constraint_solver.h +++ b/src/constraint_solver/constraint_solver.h @@ -99,7 +99,6 @@ template class ResultCallback; -using std::string; namespace operations_research { @@ -854,8 +853,8 @@ class Solver { PROBLEM_INFEASIBLE // After search, the model is infeasible. }; - explicit Solver(const string& modelname); - Solver(const string& modelname, const SolverParameters& parameters); + explicit Solver(const std::string& modelname); + Solver(const std::string& modelname, const SolverParameters& parameters); ~Solver(); // Read-only Parameters. @@ -1090,22 +1089,22 @@ class Solver { std::vector* const interval_variables); // Registers a constraint builder. Ownership is passed to the solver. - void RegisterBuilder(const string& tag, ConstraintBuilder* const builder); + void RegisterBuilder(const std::string& tag, ConstraintBuilder* const builder); // Registers an integer expression builder. Ownership is passed to the solver. - void RegisterBuilder(const string& tag, + void RegisterBuilder(const std::string& tag, IntegerExpressionBuilder* const builder); // Registers an interval variable builder. Ownership is passed to the solver. - void RegisterBuilder(const string& tag, + void RegisterBuilder(const std::string& tag, IntervalVariableBuilder* const builder); // Registers a sequence variable builder. Ownership is passed to the solver. - void RegisterBuilder(const string& tag, + void RegisterBuilder(const std::string& tag, SequenceVariableBuilder* const builder); - ConstraintBuilder* GetConstraintBuilder(const string& tag) const; + ConstraintBuilder* GetConstraintBuilder(const std::string& tag) const; IntegerExpressionBuilder* GetIntegerExpressionBuilder( - const string& tag) const; - IntervalVariableBuilder* GetIntervalVariableBuilder(const string& tag) const; - SequenceVariableBuilder* GetSequenceVariableBuilder(const string& tag) const; + const std::string& tag) const; + IntervalVariableBuilder* GetIntervalVariableBuilder(const std::string& tag) const; + SequenceVariableBuilder* GetSequenceVariableBuilder(const std::string& tag) const; #endif // SWIG // When SaveValue() is not the best way to go, one can create a reversible @@ -1114,8 +1113,8 @@ class Solver { // before calling this method. void AddBacktrackAction(Action* a, bool fast); - // misc debug string. - string DebugString() const; + // misc debug std::string. + std::string DebugString() const; // Current memory usage in bytes static int64 MemoryUsage(); @@ -1163,13 +1162,13 @@ class Solver { // ----- Int Variables and Constants ----- // MakeIntVar will create the best range based int var for the bounds given. - IntVar* MakeIntVar(int64 vmin, int64 vmax, const string& name); + IntVar* MakeIntVar(int64 vmin, int64 vmax, const std::string& name); // MakeIntVar will create a variable with the given sparse domain. - IntVar* MakeIntVar(const std::vector& values, const string& name); + IntVar* MakeIntVar(const std::vector& values, const std::string& name); // MakeIntVar will create a variable with the given sparse domain. - IntVar* MakeIntVar(const std::vector& values, const string& name); + IntVar* MakeIntVar(const std::vector& values, const std::string& name); // MakeIntVar will create the best range based int var for the bounds given. IntVar* MakeIntVar(int64 vmin, int64 vmax); @@ -1181,13 +1180,13 @@ class Solver { IntVar* MakeIntVar(const std::vector& values); // MakeBoolVar will create a variable with a {0, 1} domain. - IntVar* MakeBoolVar(const string& name); + IntVar* MakeBoolVar(const std::string& name); // MakeBoolVar will create a variable with a {0, 1} domain. IntVar* MakeBoolVar(); // IntConst will create a constant expression. - IntVar* MakeIntConst(int64 val, const string& name); + IntVar* MakeIntConst(int64 val, const std::string& name); // IntConst will create a constant expression. IntVar* MakeIntConst(int64 val); @@ -1196,25 +1195,25 @@ class Solver { // having bounds vmin and vmax and having name "name" where is // the index of the variable. void MakeIntVarArray(int var_count, int64 vmin, int64 vmax, - const string& name, std::vector* vars); + const std::string& name, std::vector* vars); // This method will append the vector vars with 'var_count' variables // having bounds vmin and vmax and having no names. void MakeIntVarArray(int var_count, int64 vmin, int64 vmax, std::vector* vars); // Same but allocates an array and returns it. IntVar** MakeIntVarArray(int var_count, int64 vmin, int64 vmax, - const string& name); + const std::string& name); // This method will append the vector vars with 'var_count' boolean // variables having name "name" where is the index of the // variable. - void MakeBoolVarArray(int var_count, const string& name, + void MakeBoolVarArray(int var_count, const std::string& name, std::vector* vars); // This method will append the vector vars with 'var_count' boolean // variables having no names. void MakeBoolVarArray(int var_count, std::vector* vars); // Same but allocates an array and returns it. - IntVar** MakeBoolVarArray(int var_count, const string& name); + IntVar** MakeBoolVarArray(int var_count, const std::string& name); // ----- Integer Expressions ----- @@ -1283,22 +1282,22 @@ class Solver { // It assumes that vars are all different. IntExpr* MakeIndexExpression(const std::vector& vars, int64 value); - // min(vars) + // std::min(vars) IntExpr* MakeMin(const std::vector& vars); // min (left, right) IntExpr* MakeMin(IntExpr* const left, IntExpr* const right); - // min(expr, val) + // std::min(expr, val) IntExpr* MakeMin(IntExpr* const expr, int64 val); - // min(expr, val) + // std::min(expr, val) IntExpr* MakeMin(IntExpr* const expr, int val); - // max(vars) + // std::max(vars) IntExpr* MakeMax(const std::vector& vars); - // max(left, right) + // std::max(left, right) IntExpr* MakeMax(IntExpr* const left, IntExpr* const right); - // max(expr, val) + // std::max(expr, val) IntExpr* MakeMax(IntExpr* const expr, int64 val); - // max(expr, val) + // std::max(expr, val) IntExpr* MakeMax(IntExpr* const expr, int val); // convex piecewise function. @@ -1326,7 +1325,7 @@ class Solver { Constraint* MakeTrueConstraint(); // This constraint always fails. Constraint* MakeFalseConstraint(); - Constraint* MakeFalseConstraint(const string& explanation); + Constraint* MakeFalseConstraint(const std::string& explanation); // b == (v == c) Constraint* MakeIsEqualCstCt(IntExpr* const v, int64 c, IntVar* const b); @@ -1764,56 +1763,56 @@ class Solver { // is always performed. IntervalVar* MakeFixedDurationIntervalVar(int64 start_min, int64 start_max, int64 duration, bool optional, - const string& name); + const std::string& name); // This method fills the vector with 'count' interval var built with // the corresponding parameters. void MakeFixedDurationIntervalVarArray(int count, int64 start_min, int64 start_max, int64 duration, - bool optional, const string& name, + bool optional, const std::string& name, std::vector* const array); // Creates an interval var with a fixed duration. The duration must // be greater than 0. IntervalVar* MakeFixedDurationIntervalVar(IntVar* const start_variable, - int64 duration, const string& name); + int64 duration, const std::string& name); // This method fills the vector with 'count' interval var built with // the corresponding start variables. void MakeFixedDurationIntervalVarArray(const std::vector& start_variables, - int64 duration, const string& name, + int64 duration, const std::string& name, std::vector* const array); // This method fills the vector with interval variables built with // the corresponding start variables. void MakeFixedDurationIntervalVarArray(const std::vector& start_variables, const std::vector& durations, - const string& name, + const std::string& name, std::vector* const array); // This method fills the vector with interval variables built with // the corresponding start variables. void MakeFixedDurationIntervalVarArray(const std::vector& start_variables, const std::vector& durations, - const string& name, + const std::string& name, std::vector* const array); // Creates a fixed and performed interval. IntervalVar* MakeFixedInterval(int64 start, int64 duration, - const string& name); + const std::string& name); // Creates an interval var by specifying the bounds on start, // duration, and end. IntervalVar* MakeIntervalVar(int64 start_min, int64 start_max, int64 duration_min, int64 duration_max, int64 end_min, int64 end_max, bool optional, - const string& name); + const std::string& name); // This method fills the vector with 'count' interval var built with // the corresponding parameters. void MakeIntervalVarArray(int count, int64 start_min, int64 start_max, int64 duration_min, int64 duration_max, int64 end_min, int64 end_max, bool optional, - const string& name, + const std::string& name, std::vector* const array); // Creates an interval var that is the mirror image of the given one, that is, @@ -1912,7 +1911,7 @@ class Solver { // This constraint forces all interval vars into an non overlapping // sequence. DisjunctiveConstraint* MakeDisjunctiveConstraint( - const std::vector& intervals, const string& name); + const std::vector& intervals, const std::string& name); // This constraint forces that, for any integer t, the sum of the demands // corresponding to an interval containing t does not exceed the given @@ -1925,7 +1924,7 @@ class Solver { // nor are impacted by this constraint. Constraint* MakeCumulative(const std::vector& intervals, const std::vector& demands, int64 capacity, - const string& name); + const std::string& name); // This constraint forces that, for any integer t, the sum of the demands // corresponding to an interval containing t does not exceed the given @@ -1938,7 +1937,7 @@ class Solver { // nor are impacted by this constraint. Constraint* MakeCumulative(const std::vector& intervals, const std::vector& demands, int64 capacity, - const string& name); + const std::string& name); // This constraint forces that, for any integer t, the sum of the demands // corresponding to an interval containing t does not exceed the given @@ -1951,7 +1950,7 @@ class Solver { // nor are impacted by this constraint. Constraint* MakeCumulative(const std::vector& intervals, const std::vector& demands, - IntVar* const capacity, const string& name); + IntVar* const capacity, const std::string& name); // This constraint forces that, for any integer t, the sum of the demands // corresponding to an interval containing t does not exceed the given @@ -1964,7 +1963,7 @@ class Solver { // nor are impacted by this constraint. Constraint* MakeCumulative(const std::vector& intervals, const std::vector& demands, IntVar* const capacity, - const string& name); + const std::string& name); // This constraint states that the target_var is the convex hull of // the intervals. If none of the interval variables is performed, @@ -2171,35 +2170,35 @@ class Solver { // decision phase in cpviz format. The XML data is written to files // file_tree and file_visualization as the search finishes. SearchMonitor* MakeTreeMonitor(const std::vector& vars, - const string& file_tree, - const string& file_visualization); + const std::string& file_tree, + const std::string& file_visualization); // Creates a tree monitor that outputs a detailed overview of the // decision phase in cpviz format. The XML data is written to files // file_config, file_tree and file_visualization as the search // finishes. SearchMonitor* MakeTreeMonitor(const std::vector& vars, - const string& file_config, - const string& file_tree, - const string& file_visualization); + const std::string& file_config, + const std::string& file_tree, + const std::string& file_visualization); #if !defined(SWIG) // Creates a tree monitor that outputs a detailed overview of the // decision phase in cpviz format. The XML data is copied to tree_xml // and visualization_xml as the search finishes. The tree monitor does - // not take ownership of either string. + // not take ownership of either std::string. SearchMonitor* MakeTreeMonitor(const std::vector& vars, - string* const tree_xml, - string* const visualization_xml); + std::string* const tree_xml, + std::string* const visualization_xml); // Creates a tree monitor that outputs a detailed overview of the // decision phase in cpviz format. The XML data is copied to config_xml, // tree_xml and visualization_xml as the search finishes. The tree monitor // does not take ownership of these strings. SearchMonitor* MakeTreeMonitor(const std::vector& vars, - string* const config_xml, - string* const tree_xml, - string* const visualization_xml); + std::string* const config_xml, + std::string* const tree_xml, + std::string* const visualization_xml); #endif // #if !defined(SWIG) @@ -2217,12 +2216,12 @@ class Solver { // At each solution, this monitor will also display result of @p // display_callback. SearchMonitor* MakeSearchLog(int branch_count, - ResultCallback* display_callback); + ResultCallback* display_callback); // At each solution, this monitor will display the objective value and the // result of @p display_callback. SearchMonitor* MakeSearchLog(int branch_count, IntVar* objective, - ResultCallback* display_callback); + ResultCallback* display_callback); // OptimizeVar Search Logs // At each solution, this monitor will also display the objective->Print(). @@ -2232,14 +2231,14 @@ class Solver { // Creates a search monitor that will also print the result of the // display callback. SearchMonitor* MakeSearchLog(int branch_count, OptimizeVar* const objective, - ResultCallback* display_callback); + ResultCallback* display_callback); // ----- Search Trace ------ // Creates a search monitor that will trace precisely the behavior of the // search. Use this only for low level debugging. - SearchMonitor* MakeSearchTrace(const string& prefix); + SearchMonitor* MakeSearchTrace(const std::string& prefix); // ----- ModelVisitor ----- @@ -2764,7 +2763,7 @@ class Solver { // Exports the profiling information in a human readable overview. // The parameter profile_level used to create the solver must be // different from NO_PROFILING. - void ExportProfilingOverview(const string& filename); + void ExportProfilingOverview(const std::string& filename); // Returns true whether the current search has been // created using a Solve() call instead of a NewSearch 0ne. It @@ -2817,7 +2816,7 @@ class Solver { // Returns whether all variables should be named. bool NameAllVariables() const; // Returns the name of the model. - string model_name() const; + std::string model_name() const; // Returns the dependency graph of the solver. DependencyGraph* Graph() const; // Returns the propagation monitor. @@ -2944,19 +2943,19 @@ class Solver { } // Naming - string GetName(const PropagationBaseObject* object); - void SetName(const PropagationBaseObject* object, const string& name); + std::string GetName(const PropagationBaseObject* object); + void SetName(const PropagationBaseObject* object, const std::string& name); // Internal. bool IsADifference(IntExpr* expr, IntExpr** const left, IntExpr** const right); - const string name_; + const std::string name_; const SolverParameters parameters_; - hash_map propagation_object_names_; + hash_map propagation_object_names_; hash_map cast_information_; hash_set cast_constraints_; - const string empty_name_; + const std::string empty_name_; std::unique_ptr queue_; std::unique_ptr trail_; std::vector constraints_list_; @@ -2998,10 +2997,10 @@ class Solver { int additional_constraint_index_; // Support for model loading. - hash_map expression_builders_; - hash_map constraint_builders_; - hash_map interval_builders_; - hash_map sequence_builders_; + hash_map expression_builders_; + hash_map constraint_builders_; + hash_map interval_builders_; + hash_map sequence_builders_; std::unique_ptr model_cache_; std::unique_ptr dependency_graph_; @@ -3035,7 +3034,7 @@ class BaseObject { public: BaseObject() {} virtual ~BaseObject() {} - virtual string DebugString() const { return "BaseObject"; } + virtual std::string DebugString() const { return "BaseObject"; } private: DISALLOW_COPY_AND_ASSIGN(BaseObject); @@ -3051,7 +3050,7 @@ class PropagationBaseObject : public BaseObject { explicit PropagationBaseObject(Solver* const s) : solver_(s) {} virtual ~PropagationBaseObject() {} - virtual string DebugString() const { + virtual std::string DebugString() const { if (name().empty()) { return "PropagationBaseObject"; } else { @@ -3086,12 +3085,12 @@ class PropagationBaseObject : public BaseObject { void clear_queue_action_on_fail() { solver_->clear_queue_action_on_fail(); } // Naming - virtual string name() const; - void set_name(const string& name); + virtual std::string name() const; + void set_name(const std::string& name); // Returns whether the object has been named or not. bool HasName() const; // Returns a base name for automatic naming. - virtual string BaseName() const; + virtual std::string BaseName() const; private: Solver* const solver_; @@ -3111,7 +3110,7 @@ class Decision : public BaseObject { // Refute will be called after a backtrack. virtual void Refute(Solver* const s) = 0; - virtual string DebugString() const { return "Decision"; } + virtual std::string DebugString() const { return "Decision"; } // Accepts the given visitor. virtual void Accept(DecisionVisitor* const visitor) const; @@ -3148,7 +3147,7 @@ class DecisionBuilder : public BaseObject { // returns nullptr, this means that the decision builder has finished // its work. virtual Decision* Next(Solver* const s) = 0; - virtual string DebugString() const; + virtual std::string DebugString() const; #if !defined(SWIG) // This method will be called at the start of the search. It asks // the decision builder if it wants to append search monitors to the @@ -3187,7 +3186,7 @@ class Demon : public BaseObject { // use to maintain variables. virtual Solver::DemonPriority priority() const; - virtual string DebugString() const; + virtual std::string DebugString() const; // This method inhibits the demon in the search tree below the // current position. @@ -3213,7 +3212,7 @@ class Action : public BaseObject { // The main callback of the class. virtual void Run(Solver* const s) = 0; - virtual string DebugString() const; + virtual std::string DebugString() const; private: DISALLOW_COPY_AND_ASSIGN(Action); @@ -3321,7 +3320,6 @@ class ModelVisitor : public BaseObject { static const char kCapacityArgument[]; static const char kCardsArgument[]; static const char kCoefficientsArgument[]; - static const char kCompleteArgument[]; static const char kCountArgument[]; static const char kCumulativeArgument[]; static const char kCumulsArgument[]; @@ -3350,6 +3348,7 @@ class ModelVisitor : public BaseObject { static const char kModuloArgument[]; static const char kNextsArgument[]; static const char kOptionalArgument[]; + static const char kPartialArgument[]; static const char kPositionXArgument[]; static const char kPositionYArgument[]; static const char kRangeArgument[]; @@ -3390,53 +3389,53 @@ class ModelVisitor : public BaseObject { // ----- Virtual methods for visitors ----- // Begin/End visit element. - virtual void BeginVisitModel(const string& solver_name); - virtual void EndVisitModel(const string& solver_name); - virtual void BeginVisitConstraint(const string& type_name, + virtual void BeginVisitModel(const std::string& solver_name); + virtual void EndVisitModel(const std::string& solver_name); + virtual void BeginVisitConstraint(const std::string& type_name, const Constraint* const constraint); - virtual void EndVisitConstraint(const string& type_name, + virtual void EndVisitConstraint(const std::string& type_name, const Constraint* const constraint); - virtual void BeginVisitExtension(const string& type); - virtual void EndVisitExtension(const string& type); - virtual void BeginVisitIntegerExpression(const string& type_name, + virtual void BeginVisitExtension(const std::string& type); + virtual void EndVisitExtension(const std::string& type); + virtual void BeginVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr); - virtual void EndVisitIntegerExpression(const string& type_name, + virtual void EndVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr); virtual void VisitIntegerVariable(const IntVar* const variable, IntExpr* const delegate); virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate); virtual void VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate); virtual void VisitSequenceVariable(const SequenceVar* const sequence); // Visit integer arguments. - virtual void VisitIntegerArgument(const string& arg_name, int64 value); - virtual void VisitIntegerArrayArgument(const string& arg_name, + virtual void VisitIntegerArgument(const std::string& arg_name, int64 value); + virtual void VisitIntegerArrayArgument(const std::string& arg_name, const std::vector& values); - virtual void VisitIntegerMatrixArgument(const string& arg_name, + virtual void VisitIntegerMatrixArgument(const std::string& arg_name, const IntTupleSet& tuples); // Visit integer expression argument. - virtual void VisitIntegerExpressionArgument(const string& arg_name, + virtual void VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument); virtual void VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments); + const std::string& arg_name, const std::vector& arguments); // Visit interval argument. - virtual void VisitIntervalArgument(const string& arg_name, + virtual void VisitIntervalArgument(const std::string& arg_name, IntervalVar* const argument); - virtual void VisitIntervalArrayArgument(const string& arg_name, + virtual void VisitIntervalArrayArgument(const std::string& arg_name, const std::vector& argument); // Visit sequence argument. - virtual void VisitSequenceArgument(const string& arg_name, + virtual void VisitSequenceArgument(const std::string& arg_name, SequenceVar* const argument); - virtual void VisitSequenceArrayArgument(const string& arg_name, + virtual void VisitSequenceArrayArgument(const std::string& arg_name, const std::vector& argument); // Helpers. #if !defined(SWIG) @@ -3448,7 +3447,7 @@ class ModelVisitor : public BaseObject { int64 index_min, int64 index_max); // Expands function as array when index min is 0. void VisitInt64ToInt64AsArray(ResultCallback1* const callback, - const string& arg_name, int64 index_max); + const std::string& arg_name, int64 index_max); #endif // #if !defined(SWIG) }; @@ -3470,7 +3469,7 @@ class Constraint : public PropagationBaseObject { // This method performs the initial propagation of the // constraint. It is called just after the post. virtual void InitialPropagate() = 0; - virtual string DebugString() const; + virtual std::string DebugString() const; // Calls Post and then Propagate to initialize the constraints. This // is usually done in the root node. @@ -3746,7 +3745,7 @@ class IntExpr : public PropagationBaseObject { // resulting var. If the expression is already a variable, then it // will set the name of the expression, possibly overwriting it. // This is just a shortcut to Var() followed by set_name(). - IntVar* VarWithName(const string& name); + IntVar* VarWithName(const std::string& name); // Attach a demon that will watch the min or the max of the expression. virtual void WhenRange(Demon* d) = 0; @@ -3793,7 +3792,7 @@ class IntVarIterator : public BaseObject { virtual void Next() = 0; // Pretty Print. - virtual string DebugString() const { return "IntVar::Iterator"; } + virtual std::string DebugString() const { return "IntVar::Iterator"; } }; // The class IntVar is a subset of IntExpr. In addition to the @@ -3802,7 +3801,7 @@ class IntVarIterator : public BaseObject { class IntVar : public IntExpr { public: explicit IntVar(Solver* const s); - IntVar(Solver* const s, const string& name); + IntVar(Solver* const s, const std::string& name); virtual ~IntVar() {} virtual bool IsVar() const { return true; } @@ -3983,8 +3982,8 @@ class OptimizeVar : public SearchMonitor { virtual void RefuteDecision(Decision* const d); virtual bool AtSolution(); virtual bool AcceptSolution(); - virtual string Print() const; - virtual string DebugString() const; + virtual std::string Print() const; + virtual std::string DebugString() const; virtual void Accept(ModelVisitor* const visitor) const; void ApplyBound(); @@ -4032,7 +4031,7 @@ class SearchLimit : public SearchMonitor { virtual void BeginNextDecision(DecisionBuilder* const b); virtual void PeriodicCheck(); virtual void RefuteDecision(Decision* const d); - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("SearchLimit(crossed = %i)", crossed_); } @@ -4067,7 +4066,7 @@ class NoGood { // still active and needs to be reevaluated. bool Apply(Solver* const solver); // Pretty print. - string DebugString() const; + std::string DebugString() const; // TODO(user) : support interval variables and more types of constraints. private: @@ -4096,7 +4095,7 @@ class NoGoodManager : public SearchMonitor { // Returns the number of nogoods added to the recorder. virtual int NoGoodCount() const = 0; // Pretty Print. - virtual string DebugString() const = 0; + virtual std::string DebugString() const = 0; // ----- Internal methods that links search events to the recorder API ----- virtual void EnterSearch(); @@ -4131,7 +4130,7 @@ class IntervalVar : public PropagationBaseObject { static const int64 kMinValidValue; // The largest acceptable value to be returned by EndMax() static const int64 kMaxValidValue; - IntervalVar(Solver* const solver, const string& name) + IntervalVar(Solver* const solver, const std::string& name) : PropagationBaseObject(solver) { set_name(name); } @@ -4218,11 +4217,11 @@ class IntervalVar : public PropagationBaseObject { class SequenceVar : public PropagationBaseObject { public: SequenceVar(Solver* const s, const std::vector& intervals, - const std::vector& nexts, const string& name); + const std::vector& nexts, const std::string& name); virtual ~SequenceVar(); - virtual string DebugString() const; + virtual std::string DebugString() const; // Returns the minimum and maximum duration of combined interval // vars in the sequence. @@ -4358,7 +4357,7 @@ class IntVarElement : public AssignmentElement { min_ = v; max_ = v; } - string DebugString() const; + std::string DebugString() const; bool operator==(const IntVarElement& element) const; bool operator!=(const IntVarElement& element) const { @@ -4452,7 +4451,7 @@ class IntervalVarElement : public AssignmentElement { performed_min_ = v; performed_max_ = v; } - string DebugString() const; + std::string DebugString() const; bool operator==(const IntervalVarElement& element) const; bool operator!=(const IntervalVarElement& element) const { return !(*this == element); @@ -4510,7 +4509,7 @@ class SequenceVarElement : public AssignmentElement { void SetBackwardSequence(const std::vector& backward_sequence); void SetUnperformed(const std::vector& unperformed); - string DebugString() const; + std::string DebugString() const; bool operator==(const SequenceVarElement& element) const; bool operator!=(const SequenceVarElement& element) const { @@ -4697,13 +4696,13 @@ class Assignment : public PropagationBaseObject { // Loads an assignment from a file; does not add variables to the // assignment (only the variables contained in the assignment are modified). - bool Load(const string& filename); + bool Load(const std::string& filename); #if !defined(SWIG) bool Load(File* file); #endif // #if !defined(SWIG) void Load(const AssignmentProto& proto); // Saves the assignment to a file. - bool Save(const string& filename) const; + bool Save(const std::string& filename) const; #if !defined(SWIG) bool Save(File* file) const; #endif // #if !defined(SWIG) @@ -4801,7 +4800,7 @@ class Assignment : public PropagationBaseObject { void DeactivateObjective(); bool ActivatedObjective() const; - virtual string DebugString() const; + virtual std::string DebugString() const; bool Contains(const IntVar* const var) const; bool Contains(const IntervalVar* const var) const; @@ -4925,7 +4924,7 @@ class Pack : public Constraint { virtual void InitialPropagate(); void Propagate(); void OneDomain(int var_index); - virtual string DebugString() const; + virtual std::string DebugString() const; bool IsUndecided(int var_index, int bin_index) const; void SetImpossible(int var_index, int bin_index); void Assign(int var_index, int bin_index); @@ -4963,7 +4962,7 @@ class Pack : public Constraint { class DisjunctiveConstraint : public Constraint { public: DisjunctiveConstraint(Solver* const s, const std::vector& intervals, - const string& name); + const std::string& name); virtual ~DisjunctiveConstraint(); // Creates a sequence variable from the constraint. diff --git a/src/constraint_solver/constraint_solveri.h b/src/constraint_solver/constraint_solveri.h index cbd0372d26..d26a0b29d3 100644 --- a/src/constraint_solver/constraint_solveri.h +++ b/src/constraint_solver/constraint_solveri.h @@ -520,26 +520,26 @@ class RevBitMatrix : private RevBitSet { template class CallMethod0 : public Demon { public: - CallMethod0(T* const ct, void (T::*method)(), const string& name) + CallMethod0(T* const ct, void (T::*method)(), const std::string& name) : constraint_(ct), method_(method), name_(name) {} virtual ~CallMethod0() {} virtual void Run(Solver* const s) { (constraint_->*method_)(); } - virtual string DebugString() const { + virtual std::string DebugString() const { return "CallMethod_" + name_ + "(" + constraint_->DebugString() + ")"; } private: T* const constraint_; void (T::*const method_)(); - const string name_; + const std::string name_; }; template Demon* MakeConstraintDemon0(Solver* const s, T* const ct, void (T::*method)(), - const string& name) { + const std::string& name) { return s->RevAlloc(new CallMethod0(ct, method, name)); } @@ -547,14 +547,14 @@ Demon* MakeConstraintDemon0(Solver* const s, T* const ct, void (T::*method)(), template class CallMethod1 : public Demon { public: - CallMethod1(T* const ct, void (T::*method)(P), const string& name, P param1) + CallMethod1(T* const ct, void (T::*method)(P), const std::string& name, P param1) : constraint_(ct), method_(method), name_(name), param1_(param1) {} virtual ~CallMethod1() {} virtual void Run(Solver* const s) { (constraint_->*method_)(param1_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StrCat(StrCat("CallMethod_", name_), StrCat("(", constraint_->DebugString(), ", "), StrCat(param1_, ")")); @@ -563,13 +563,13 @@ class CallMethod1 : public Demon { private: T* const constraint_; void (T::*const method_)(P); - const string name_; + const std::string name_; P param1_; }; template Demon* MakeConstraintDemon1(Solver* const s, T* const ct, void (T::*method)(P), - const string& name, P param1) { + const std::string& name, P param1) { return s->RevAlloc(new CallMethod1(ct, method, name, param1)); } @@ -577,7 +577,7 @@ Demon* MakeConstraintDemon1(Solver* const s, T* const ct, void (T::*method)(P), template class CallMethod2 : public Demon { public: - CallMethod2(T* const ct, void (T::*method)(P, Q), const string& name, + CallMethod2(T* const ct, void (T::*method)(P, Q), const std::string& name, P param1, Q param2) : constraint_(ct), method_(method), @@ -591,7 +591,7 @@ class CallMethod2 : public Demon { (constraint_->*method_)(param1_, param2_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StrCat(StrCat("CallMethod_", name_), StrCat("(", constraint_->DebugString()), StrCat(", ", param1_), StrCat(", ", param2_, ")")); @@ -600,14 +600,14 @@ class CallMethod2 : public Demon { private: T* const constraint_; void (T::*const method_)(P, Q); - const string name_; + const std::string name_; P param1_; Q param2_; }; template Demon* MakeConstraintDemon2(Solver* const s, T* const ct, - void (T::*method)(P, Q), const string& name, + void (T::*method)(P, Q), const std::string& name, P param1, Q param2) { return s->RevAlloc( new CallMethod2(ct, method, name, param1, param2)); @@ -616,7 +616,7 @@ Demon* MakeConstraintDemon2(Solver* const s, T* const ct, template class CallMethod3 : public Demon { public: - CallMethod3(T* const ct, void (T::*method)(P, Q, R), const string& name, + CallMethod3(T* const ct, void (T::*method)(P, Q, R), const std::string& name, P param1, Q param2, R param3) : constraint_(ct), method_(method), @@ -631,7 +631,7 @@ class CallMethod3 : public Demon { (constraint_->*method_)(param1_, param2_, param3_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StrCat(StrCat("CallMethod_", name_), StrCat("(", constraint_->DebugString()), StrCat(", ", param1_), StrCat(", ", param2_), @@ -641,7 +641,7 @@ class CallMethod3 : public Demon { private: T* const constraint_; void (T::*const method_)(P, Q, R); - const string name_; + const std::string name_; P param1_; Q param2_; R param3_; @@ -649,7 +649,7 @@ class CallMethod3 : public Demon { template Demon* MakeConstraintDemon3(Solver* const s, T* const ct, - void (T::*method)(P, Q, R), const string& name, + void (T::*method)(P, Q, R), const std::string& name, P param1, Q param2, R param3) { return s->RevAlloc( new CallMethod3(ct, method, name, param1, param2, param3)); @@ -665,7 +665,7 @@ Demon* MakeConstraintDemon3(Solver* const s, T* const ct, template class DelayedCallMethod0 : public Demon { public: - DelayedCallMethod0(T* const ct, void (T::*method)(), const string& name) + DelayedCallMethod0(T* const ct, void (T::*method)(), const std::string& name) : constraint_(ct), method_(method), name_(name) {} virtual ~DelayedCallMethod0() {} @@ -676,7 +676,7 @@ class DelayedCallMethod0 : public Demon { return Solver::DELAYED_PRIORITY; } - virtual string DebugString() const { + virtual std::string DebugString() const { return "DelayedCallMethod_" + name_ + "(" + constraint_->DebugString() + ")"; } @@ -684,12 +684,12 @@ class DelayedCallMethod0 : public Demon { private: T* const constraint_; void (T::*const method_)(); - const string name_; + const std::string name_; }; template Demon* MakeDelayedConstraintDemon0(Solver* const s, T* const ct, - void (T::*method)(), const string& name) { + void (T::*method)(), const std::string& name) { return s->RevAlloc(new DelayedCallMethod0(ct, method, name)); } @@ -697,7 +697,7 @@ Demon* MakeDelayedConstraintDemon0(Solver* const s, T* const ct, template class DelayedCallMethod1 : public Demon { public: - DelayedCallMethod1(T* const ct, void (T::*method)(P), const string& name, + DelayedCallMethod1(T* const ct, void (T::*method)(P), const std::string& name, P param1) : constraint_(ct), method_(method), name_(name), param1_(param1) {} @@ -709,7 +709,7 @@ class DelayedCallMethod1 : public Demon { return Solver::DELAYED_PRIORITY; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StrCat(StrCat("DelayedCallMethod_", name_), StrCat("(", constraint_->DebugString(), ", "), StrCat(param1_, ")")); @@ -718,13 +718,13 @@ class DelayedCallMethod1 : public Demon { private: T* const constraint_; void (T::*const method_)(P); - const string name_; + const std::string name_; P param1_; }; template Demon* MakeDelayedConstraintDemon1(Solver* const s, T* const ct, - void (T::*method)(P), const string& name, + void (T::*method)(P), const std::string& name, P param1) { return s->RevAlloc(new DelayedCallMethod1(ct, method, name, param1)); } @@ -733,7 +733,7 @@ Demon* MakeDelayedConstraintDemon1(Solver* const s, T* const ct, template class DelayedCallMethod2 : public Demon { public: - DelayedCallMethod2(T* const ct, void (T::*method)(P, Q), const string& name, + DelayedCallMethod2(T* const ct, void (T::*method)(P, Q), const std::string& name, P param1, Q param2) : constraint_(ct), method_(method), @@ -751,7 +751,7 @@ class DelayedCallMethod2 : public Demon { return Solver::DELAYED_PRIORITY; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StrCat(StrCat("DelayedCallMethod_", name_), StrCat("(", constraint_->DebugString()), StrCat(", ", param1_), StrCat(", ", param2_, ")")); @@ -760,14 +760,14 @@ class DelayedCallMethod2 : public Demon { private: T* const constraint_; void (T::*const method_)(P, Q); - const string name_; + const std::string name_; P param1_; Q param2_; }; template Demon* MakeDelayedConstraintDemon2(Solver* const s, T* const ct, - void (T::*method)(P, Q), const string& name, + void (T::*method)(P, Q), const std::string& name, P param1, Q param2) { return s->RevAlloc( new DelayedCallMethod2(ct, method, name, param1, param2)); @@ -1213,7 +1213,7 @@ class PropagationMonitor : public SearchMonitor { virtual void EndDemonRun(Demon* const demon) = 0; virtual void StartProcessingIntegerVariable(IntVar* const var) = 0; virtual void EndProcessingIntegerVariable(IntVar* const var) = 0; - virtual void PushContext(const string& context) = 0; + virtual void PushContext(const std::string& context) = 0; virtual void PopContext() = 0; // IntExpr modifiers. virtual void SetMin(IntExpr* const expr, int64 new_min) = 0; @@ -1261,7 +1261,7 @@ class BooleanVar : public IntVar { public: static const int kUnboundBooleanVarValue; - BooleanVar(Solver* const s, const string& name = "") + BooleanVar(Solver* const s, const std::string& name = "") : IntVar(s, name), value_(kUnboundBooleanVarValue) {} virtual ~BooleanVar() {} @@ -1285,7 +1285,7 @@ class BooleanVar : public IntVar { virtual bool Contains(int64 v) const; virtual IntVarIterator* MakeHoleIterator(bool reversible) const; virtual IntVarIterator* MakeDomainIterator(bool reversible) const; - virtual string DebugString() const; + virtual std::string DebugString() const; virtual int VarType() const { return BOOLEAN_VAR; } virtual IntVar* IsEqual(int64 constant); @@ -1294,7 +1294,7 @@ class BooleanVar : public IntVar { virtual IntVar* IsLessOrEqual(int64 constant); virtual void RestoreValue() = 0; - virtual string BaseName() const { return "BooleanVar"; } + virtual std::string BaseName() const { return "BooleanVar"; } int RawValue() const { return value_; } @@ -1345,7 +1345,7 @@ class SymmetryBreaker : public DecisionVisitor { class SearchLog : public SearchMonitor { public: SearchLog(Solver* const s, OptimizeVar* const obj, IntVar* const var, - ResultCallback* display_callback, int period); + ResultCallback* display_callback, int period); virtual ~SearchLog(); virtual void EnterSearch(); virtual void ExitSearch(); @@ -1358,20 +1358,20 @@ class SearchLog : public SearchMonitor { void Maintain(); virtual void BeginInitialPropagation(); virtual void EndInitialPropagation(); - virtual string DebugString() const; + virtual std::string DebugString() const; protected: /* Bottleneck function used for all UI related output. */ - virtual void OutputLine(const string& line); + virtual void OutputLine(const std::string& line); private: - static string MemoryUsage(); + static std::string MemoryUsage(); const int period_; std::unique_ptr timer_; IntVar* const var_; OptimizeVar* const obj_; - std::unique_ptr > display_callback_; + std::unique_ptr > display_callback_; int nsol_; int64 tick_; int64 objective_min_; @@ -1676,53 +1676,53 @@ class DependencyGraph : public BaseObject { class ArgumentHolder { public: // Type of the argument. - const string& TypeName() const; - void SetTypeName(const string& type_name); + const std::string& TypeName() const; + void SetTypeName(const std::string& type_name); // Setters. - void SetIntegerArgument(const string& arg_name, int64 value); - void SetIntegerArrayArgument(const string& arg_name, + void SetIntegerArgument(const std::string& arg_name, int64 value); + void SetIntegerArrayArgument(const std::string& arg_name, const std::vector& values); - void SetIntegerMatrixArgument(const string& arg_name, + void SetIntegerMatrixArgument(const std::string& arg_name, const IntTupleSet& values); - void SetIntegerExpressionArgument(const string& arg_name, + void SetIntegerExpressionArgument(const std::string& arg_name, IntExpr* const expr); - void SetIntegerVariableArrayArgument(const string& arg_name, + void SetIntegerVariableArrayArgument(const std::string& arg_name, const std::vector& vars); - void SetIntervalArgument(const string& arg_name, IntervalVar* const var); - void SetIntervalArrayArgument(const string& arg_name, + void SetIntervalArgument(const std::string& arg_name, IntervalVar* const var); + void SetIntervalArrayArgument(const std::string& arg_name, const std::vector& vars); - void SetSequenceArgument(const string& arg_name, SequenceVar* const var); - void SetSequenceArrayArgument(const string& arg_name, + void SetSequenceArgument(const std::string& arg_name, SequenceVar* const var); + void SetSequenceArrayArgument(const std::string& arg_name, const std::vector& vars); // Checks if arguments exist. - bool HasIntegerExpressionArgument(const string& arg_name) const; - bool HasIntegerVariableArrayArgument(const string& arg_name) const; + bool HasIntegerExpressionArgument(const std::string& arg_name) const; + bool HasIntegerVariableArrayArgument(const std::string& arg_name) const; // Getters. - int64 FindIntegerArgumentWithDefault(const string& arg_name, int64 def) const; - int64 FindIntegerArgumentOrDie(const string& arg_name) const; - const std::vector& FindIntegerArrayArgumentOrDie(const string& arg_name) + int64 FindIntegerArgumentWithDefault(const std::string& arg_name, int64 def) const; + int64 FindIntegerArgumentOrDie(const std::string& arg_name) const; + const std::vector& FindIntegerArrayArgumentOrDie(const std::string& arg_name) const; - const IntTupleSet& FindIntegerMatrixArgumentOrDie(const string& arg_name) + const IntTupleSet& FindIntegerMatrixArgumentOrDie(const std::string& arg_name) const; - IntExpr* FindIntegerExpressionArgumentOrDie(const string& arg_name) const; + IntExpr* FindIntegerExpressionArgumentOrDie(const std::string& arg_name) const; const std::vector& FindIntegerVariableArrayArgumentOrDie( - const string& arg_name) const; + const std::string& arg_name) const; private: - string type_name_; - hash_map integer_argument_; - hash_map > integer_array_argument_; - hash_map matrix_argument_; - hash_map integer_expression_argument_; - hash_map interval_argument_; - hash_map sequence_argument_; - hash_map > integer_variable_array_argument_; - hash_map > interval_array_argument_; - hash_map > sequence_array_argument_; + std::string type_name_; + hash_map integer_argument_; + hash_map > integer_array_argument_; + hash_map matrix_argument_; + hash_map integer_expression_argument_; + hash_map interval_argument_; + hash_map sequence_argument_; + hash_map > integer_variable_array_argument_; + hash_map > interval_array_argument_; + hash_map > sequence_array_argument_; }; // Model Parser @@ -1734,46 +1734,46 @@ class ModelParser : public ModelVisitor { virtual ~ModelParser(); // Header/footers. - virtual void BeginVisitModel(const string& solver_name); - virtual void EndVisitModel(const string& solver_name); - virtual void BeginVisitConstraint(const string& type_name, + virtual void BeginVisitModel(const std::string& solver_name); + virtual void EndVisitModel(const std::string& solver_name); + virtual void BeginVisitConstraint(const std::string& type_name, const Constraint* const constraint); - virtual void EndVisitConstraint(const string& type_name, + virtual void EndVisitConstraint(const std::string& type_name, const Constraint* const constraint); - virtual void BeginVisitIntegerExpression(const string& type_name, + virtual void BeginVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr); - virtual void EndVisitIntegerExpression(const string& type_name, + virtual void EndVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr); virtual void VisitIntegerVariable(const IntVar* const variable, IntExpr* const delegate); virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate); virtual void VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate); virtual void VisitSequenceVariable(const SequenceVar* const variable); // Integer arguments - virtual void VisitIntegerArgument(const string& arg_name, int64 value); - virtual void VisitIntegerArrayArgument(const string& arg_name, + virtual void VisitIntegerArgument(const std::string& arg_name, int64 value); + virtual void VisitIntegerArrayArgument(const std::string& arg_name, const std::vector& values); - virtual void VisitIntegerMatrixArgument(const string& arg_name, + virtual void VisitIntegerMatrixArgument(const std::string& arg_name, const IntTupleSet& values); // Variables. - virtual void VisitIntegerExpressionArgument(const string& arg_name, + virtual void VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument); virtual void VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments); + const std::string& arg_name, const std::vector& arguments); // Visit interval argument. - virtual void VisitIntervalArgument(const string& arg_name, + virtual void VisitIntervalArgument(const std::string& arg_name, IntervalVar* const argument); virtual void VisitIntervalArrayArgument( - const string& arg_name, const std::vector& arguments); + const std::string& arg_name, const std::vector& arguments); // Visit sequence argument. - virtual void VisitSequenceArgument(const string& arg_name, + virtual void VisitSequenceArgument(const std::string& arg_name, SequenceVar* const argument); virtual void VisitSequenceArrayArgument( - const string& arg_name, const std::vector& arguments); + const std::string& arg_name, const std::vector& arguments); protected: void PushArgumentHolder(); @@ -2032,8 +2032,8 @@ class RevPartialSequence { position > last_ranked_.Value()); } - string DebugString() const { - string result = "["; + std::string DebugString() const { + std::string result = "["; for (int i = 0; i < first_ranked_.Value(); ++i) { result.append(StringPrintf("%d", elements_[i])); if (i != first_ranked_.Value() - 1) { diff --git a/src/constraint_solver/constraints.cc b/src/constraint_solver/constraints.cc index e11b01d53b..7c397eb03b 100644 --- a/src/constraint_solver/constraints.cc +++ b/src/constraint_solver/constraints.cc @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include #include #include "base/unique_ptr.h" #include @@ -89,7 +88,7 @@ class TrueConstraint : public Constraint { virtual void Post() {} virtual void InitialPropagate() {} - virtual string DebugString() const { return "TrueConstraint()"; } + virtual std::string DebugString() const { return "TrueConstraint()"; } void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kTrueConstraint, this); @@ -107,13 +106,13 @@ namespace { class FalseConstraint : public Constraint { public: explicit FalseConstraint(Solver* const s) : Constraint(s) {} - FalseConstraint(Solver* const s, const string& explanation) + FalseConstraint(Solver* const s, const std::string& explanation) : Constraint(s), explanation_(explanation) {} virtual ~FalseConstraint() {} virtual void Post() {} virtual void InitialPropagate() { solver()->Fail(); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StrCat("FalseConstraint(", explanation_, ")"); } @@ -123,7 +122,7 @@ class FalseConstraint : public Constraint { } private: - const string explanation_; + const std::string explanation_; }; } // namespace @@ -131,7 +130,7 @@ Constraint* Solver::MakeFalseConstraint() { DCHECK(false_constraint_ != nullptr); return false_constraint_; } -Constraint* Solver::MakeFalseConstraint(const string& explanation) { +Constraint* Solver::MakeFalseConstraint(const std::string& explanation) { return RevAlloc(new FalseConstraint(this, explanation)); } @@ -228,7 +227,7 @@ class MapDomain : public Constraint { actives_[val]->SetValue(1); } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("MapDomain(%s, [%s])", var_->DebugString().c_str(), JoinDebugStringPtr(actives_, ", ").c_str()); } @@ -253,1016 +252,4 @@ Constraint* Solver::MakeMapDomain(IntVar* const var, const std::vector& actives) { return RevAlloc(new MapDomain(this, var, actives)); } - -// ---------- No cycle ---------- - -// This constraint ensures there are no cycles in the variable/value graph. -// "Sink" values are values outside the range of the array of variables; they -// are used to end paths. -// The constraint does essentially two things: -// - forbid partial paths from looping back to themselves -// - ensure each variable/node can be connected to a "sink". -// If assume_paths is true, the constraint assumes the 'next' variables -// represent paths (and performs a faster propagation); otherwise the -// constraint assumes the 'next' variables represent a forest. -// TODO(user): improve code when assume_paths is false (currently does an -// expensive n^2 loop). - -namespace { -class NoCycle : public Constraint { - public: - NoCycle(Solver* const s, const std::vector& nexts, - const std::vector& active, - ResultCallback1* sink_handler, bool owner, - bool assume_paths); - virtual ~NoCycle() { - if (owner_) { - delete sink_handler_; - } - } - virtual void Post(); - virtual void InitialPropagate(); - void NextChange(int index); - void ActiveBound(int index); - void NextBound(int index); - void ComputeSupports(); - void ComputeSupport(int index); - virtual string DebugString() const; - - void Accept(ModelVisitor* const visitor) const { - visitor->BeginVisitConstraint(ModelVisitor::kNoCycle, this); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kNextsArgument, - nexts_); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kActiveArgument, - active_); - visitor->VisitIntegerArgument("assume_paths", assume_paths_); - visitor->VisitInt64ToBoolExtension(sink_handler_, -size(), size()); - visitor->EndVisitConstraint(ModelVisitor::kNoCycle, this); - } - - private: - int64 size() const { return nexts_.size(); } - - const std::vector nexts_; - const std::vector active_; - std::vector iterators_; - std::vector starts_; - std::vector ends_; - bool all_nexts_bound_; - std::vector outbound_supports_; - std::vector support_leaves_; - std::vector unsupported_; - ResultCallback1* sink_handler_; - std::vector sinks_; - bool owner_; - bool assume_paths_; -}; - -NoCycle::NoCycle(Solver* const s, const std::vector& nexts, - const std::vector& active, - ResultCallback1* sink_handler, bool owner, - bool assume_paths) - : Constraint(s), - nexts_(nexts), - active_(active), - iterators_(nexts.size(), nullptr), - starts_(nexts.size()), - ends_(nexts.size()), - all_nexts_bound_(false), - outbound_supports_(nexts.size(), -1), - sink_handler_(sink_handler), - owner_(owner), - assume_paths_(assume_paths) { - support_leaves_.reserve(size()); - unsupported_.reserve(size()); - for (int i = 0; i < size(); ++i) { - starts_[i] = i; - ends_[i] = i; - iterators_[i] = nexts_[i]->MakeDomainIterator(true); - } - sink_handler_->CheckIsRepeatable(); -} - -void NoCycle::InitialPropagate() { - // Reduce next domains to sinks + range of nexts - for (int i = 0; i < size(); ++i) { - outbound_supports_[i] = -1; - IntVar* next = nexts_[i]; - for (int j = next->Min(); j < 0; ++j) { - if (!sink_handler_->Run(j)) { - next->RemoveValue(j); - } - } - for (int j = next->Max(); j >= size(); --j) { - if (!sink_handler_->Run(j)) { - next->RemoveValue(j); - } - } - } - solver()->SaveAndSetValue(&all_nexts_bound_, true); - for (int i = 0; i < size(); ++i) { - if (nexts_[i]->Bound()) { - NextBound(i); - } else { - solver()->SaveAndSetValue(&all_nexts_bound_, false); - } - } - ComputeSupports(); -} - -void NoCycle::Post() { - if (size() == 0) return; - for (int i = 0; i < size(); ++i) { - IntVar* next = nexts_[i]; - Demon* support_demon = MakeConstraintDemon1( - solver(), this, &NoCycle::NextChange, "NextChange", i); - next->WhenDomain(support_demon); - Demon* active_demon = MakeConstraintDemon1( - solver(), this, &NoCycle::ActiveBound, "ActiveBound", i); - active_[i]->WhenBound(active_demon); - } - // Setting up sinks - int64 min_min = nexts_[0]->Min(); - int64 max_max = nexts_[0]->Max(); - for (int i = 1; i < size(); ++i) { - const IntVar* next = nexts_[i]; - min_min = std::min(min_min, next->Min()); - max_max = std::max(max_max, next->Max()); - } - sinks_.clear(); - for (int i = min_min; i <= max_max; ++i) { - if (sink_handler_->Run(i)) { - sinks_.push_back(i); - } - } -} - -void NoCycle::NextChange(int index) { - IntVar* const next_var = nexts_[index]; - if (next_var->Bound()) { - NextBound(index); - } - if (!all_nexts_bound_) { - bool all_nexts_bound = true; - for (int i = 0; i < size(); ++i) { - if (!nexts_[i]->Bound()) { - all_nexts_bound = false; - break; - } - } - solver()->SaveAndSetValue(&all_nexts_bound_, all_nexts_bound); - } - if (all_nexts_bound_) { - return; - } - if (!next_var->Contains(outbound_supports_[index])) { - ComputeSupport(index); - } -} - -void NoCycle::ActiveBound(int index) { - if (nexts_[index]->Bound()) { - NextBound(index); - } -} - -void NoCycle::NextBound(int index) { - if (active_[index]->Min() == 0) return; - const int64 next = nexts_[index]->Value(); - const int64 chain_start = starts_[index]; - const int64 chain_end = !sink_handler_->Run(next) ? ends_[next] : next; - Solver* const s = solver(); - s->SaveAndSetValue(&ends_[chain_start], chain_end); - if (!sink_handler_->Run(chain_end)) { - s->SaveAndSetValue(&starts_[chain_end], chain_start); - nexts_[chain_end]->RemoveValue(chain_start); - if (!assume_paths_) { - for (int i = 0; i < size(); ++i) { - int64 current = i; - bool found = (current == chain_end); - // Counter to detect implicit cycles. - int count = 0; - while (!found && count < size() && !sink_handler_->Run(current) && - nexts_[current]->Bound()) { - current = nexts_[current]->Value(); - found = (current == chain_end); - ++count; - } - if (found) { - nexts_[chain_end]->RemoveValue(i); - } - } - } - } -} - -// Compute the support tree. For each variable, find a path connecting to a -// sink. Starts partial paths from the sinks down to all unconnected variables. -// If some variables remain unconnected, make the corresponding active_ -// variable false. -// Resulting tree is used as supports for next variables. -// TODO(user): Try to see if we can find an algorithm which is less than -// quadratic to do this (note that if the tree is flat we are already linear -// for a given number of sinks). -void NoCycle::ComputeSupports() { - // unsupported_ contains nodes not connected to sinks. - unsupported_.clear(); - // supported_leaves_ contains the current frontier containing nodes surely - // connected to sinks. - support_leaves_.clear(); - // Initial phase: find direct connections to sinks and initialize - // support_leaves_ and unsupported_ accordingly. - const int sink_size = sinks_.size(); - for (int i = 0; i < size(); ++i) { - const IntVar* next = nexts_[i]; - // If node is not active, no need to try to connect it to a sink. - if (active_[i]->Max() != 0) { - const int64 current_support = outbound_supports_[i]; - // Optimization: if this node was already supported by a sink, check if - // it's still a valid support. - if (current_support >= 0 && sink_handler_->Run(current_support) && - next->Contains(current_support)) { - support_leaves_.push_back(i); - } else { - // Optimization: iterate on sinks or next domain depending on which is - // smaller. - outbound_supports_[i] = -1; - if (sink_size < next->Size()) { - for (int j = 0; j < sink_size; ++j) { - if (next->Contains(sinks_[j])) { - outbound_supports_[i] = sinks_[j]; - support_leaves_.push_back(i); - break; - } - } - } else { - for (iterators_[i]->Init(); iterators_[i]->Ok(); - iterators_[i]->Next()) { - const int64 value = iterators_[i]->Value(); - if (sink_handler_->Run(value)) { - outbound_supports_[i] = value; - support_leaves_.push_back(i); - break; - } - } - } - } - if (outbound_supports_[i] == -1) { - unsupported_.push_back(i); - } - } - } - // No need to iterate on all nodes connected to sinks but just on the ones - // added in the last iteration; leaves_begin and leaves_end mark the block - // in support_leaves_ corresponding to such nodes. - size_t leaves_begin = 0; - size_t leaves_end = support_leaves_.size(); - while (!unsupported_.empty()) { - // Try to connected unsupported nodes to nodes connected to sinks. - for (int64 unsupported_index = 0; unsupported_index < unsupported_.size(); - ++unsupported_index) { - const int64 unsupported = unsupported_[unsupported_index]; - const IntVar* const next = nexts_[unsupported]; - for (int i = leaves_begin; i < leaves_end; ++i) { - if (next->Contains(support_leaves_[i])) { - outbound_supports_[unsupported] = support_leaves_[i]; - support_leaves_.push_back(unsupported); - // Remove current node from unsupported vector. - unsupported_[unsupported_index] = unsupported_.back(); - unsupported_.pop_back(); - --unsupported_index; - break; - } - // TODO(user): evaluate same trick as with the sinks by keeping a - // bitmap with supported nodes. - } - } - // No new leaves were added, we can bail out. - if (leaves_end == support_leaves_.size()) { - break; - } - leaves_begin = leaves_end; - leaves_end = support_leaves_.size(); - } - // Mark as inactive any unsupported node. - for (int64 unsupported_index = 0; unsupported_index < unsupported_.size(); - ++unsupported_index) { - active_[unsupported_[unsupported_index]]->SetMax(0); - } -} - -void NoCycle::ComputeSupport(int index) { - // Try to reconnect the node to the support tree by finding a next node - // which is both supported and was not a descendant of the node in the tree. - if (active_[index]->Max() != 0) { - for (iterators_[index]->Init(); iterators_[index]->Ok(); - iterators_[index]->Next()) { - const int64 next = iterators_[index]->Value(); - if (sink_handler_->Run(next)) { - outbound_supports_[index] = next; - return; - } - if (next != index && next < outbound_supports_.size()) { - int64 next_support = outbound_supports_[next]; - if (next_support >= 0) { - // Check if next is not already a descendant of index. - bool ancestor_found = false; - while (next_support < outbound_supports_.size() && - !sink_handler_->Run(next_support)) { - if (next_support == index) { - ancestor_found = true; - break; - } - next_support = outbound_supports_[next_support]; - } - if (!ancestor_found) { - outbound_supports_[index] = next; - return; - } - } - } - } - } - // No support was found, rebuild the support tree. - ComputeSupports(); -} - -string NoCycle::DebugString() const { - return StringPrintf("NoCycle(%s)", JoinDebugStringPtr(nexts_, ", ").c_str()); -} - -// ----- Circuit constraint ----- - -class Circuit : public Constraint { - public: - Circuit(Solver* const s, const std::vector& nexts, bool complete) - : Constraint(s), - nexts_(nexts), - size_(nexts_.size()), - starts_(size_, -1), - ends_(size_, -1), - lengths_(size_, 1), - domains_(size_), - outbound_support_(size_, -1), - inbound_support_(size_, -1), - temp_support_(size_, -1), - inbound_demon_(nullptr), - outbound_demon_(nullptr), - root_(-1), - num_inactives_(0), - complete_(complete) { - for (int i = 0; i < size_; ++i) { - domains_[i] = nexts_[i]->MakeDomainIterator(true); - } - } - - virtual ~Circuit() {} - - virtual void Post() { - inbound_demon_ = MakeDelayedConstraintDemon0( - solver(), this, &Circuit::CheckReachabilityToRoot, - "CheckReachabilityToRoot"); - outbound_demon_ = MakeDelayedConstraintDemon0( - solver(), this, &Circuit::CheckReachabilityFromRoot, - "CheckReachabilityFromRoot"); - for (int i = 0; i < size_; ++i) { - if (!nexts_[i]->Bound()) { - Demon* const bound_demon = MakeConstraintDemon1( - solver(), this, &Circuit::NextBound, "NextBound", i); - nexts_[i]->WhenBound(bound_demon); - Demon* const domain_demon = MakeConstraintDemon1( - solver(), this, &Circuit::NextDomain, "NextDomain", i); - nexts_[i]->WhenDomain(domain_demon); - } - } - solver()->AddConstraint(solver()->MakeAllDifferent(nexts_)); - } - - virtual void InitialPropagate() { - if (complete_) { - root_.SetValue(solver(), 0); - } - for (int i = 0; i < size_; ++i) { - nexts_[i]->SetRange(0, size_ - 1); - if (complete_) { - nexts_[i]->RemoveValue(i); - } - } - for (int i = 0; i < size_; ++i) { - starts_.SetValue(solver(), i, i); - ends_.SetValue(solver(), i, i); - lengths_.SetValue(solver(), i, 1); - } - for (int i = 0; i < size_; ++i) { - if (nexts_[i]->Bound()) { - NextBound(i); - } - } - CheckReachabilityFromRoot(); - CheckReachabilityToRoot(); - } - - virtual string DebugString() const { - return StringPrintf("%sCircuit(%s)", complete_ ? "" : "Sub", - JoinDebugStringPtr(nexts_, " ").c_str()); - } - - void Accept(ModelVisitor* const visitor) const { - visitor->BeginVisitConstraint(ModelVisitor::kCircuit, this); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kNextsArgument, - nexts_); - visitor->VisitIntegerArgument(ModelVisitor::kCompleteArgument, complete_); - visitor->EndVisitConstraint(ModelVisitor::kCircuit, this); - } - - private: - bool Inactive(int index) const { - return nexts_[index]->Bound() && nexts_[index]->Min() == index; - } - - void NextBound(int index) { - Solver* const s = solver(); - const int destination = nexts_[index]->Value(); - const int root = root_.Value(); - if (destination != index) { - if (root == -1) { - root_.SetValue(s, index); - } - const int new_end = ends_.Value(destination); - const int new_start = starts_.Value(index); - starts_.SetValue(s, new_end, new_start); - ends_.SetValue(s, new_start, new_end); - lengths_.SetValue(s, new_start, lengths_.Value(new_start) + - lengths_.Value(destination)); - if (complete_) { - if (lengths_.Value(new_start) < size_ - 1 - num_inactives_.Value()) { - nexts_[new_end]->RemoveValue(new_start); - } - } else { - // You are creating the only path. Nexts can no longer loop upon itself. - nexts_[destination]->RemoveValue(destination); - } - } else { - num_inactives_.Incr(solver()); - } - } - - void NextDomain(int index) { - if (root_.Value() == -1) { - return; - } - if (!nexts_[index]->Contains(outbound_support_[index])) { - EnqueueDelayedDemon(outbound_demon_); - } - if (!nexts_[index]->Contains(inbound_support_[index])) { - EnqueueDelayedDemon(inbound_demon_); - } - } - - void TryInsertReached(int candidate, int64 after) { - if (!reached_[after]) { - reached_[after] = true; - insertion_queue_.push_back(after); - temp_support_[candidate] = after; - } - } - - void CheckReachabilityFromRoot() { - if (root_.Value() == -1) { // Root is not yet defined. Nothing to deduce. - return; - } - - // Assign temp_support_ to a dummy value. - temp_support_.assign(size_, -1); - // Clear the spanning tree. - int processed = 0; - reached_.assign(size_, false); - insertion_queue_.clear(); - // Add the root node. - const int root_value = root_.Value(); - reached_[root_value] = true; - insertion_queue_.push_back(root_value); - // Compute reachable nodes. - while (processed < insertion_queue_.size() && - insertion_queue_.size() + num_inactives_.Value() < size_) { - const int candidate = insertion_queue_[processed++]; - IntVar* const var = nexts_[candidate]; - switch (var->Size()) { - case 1: { - TryInsertReached(candidate, var->Min()); - break; - } - case 2: { - TryInsertReached(candidate, var->Min()); - TryInsertReached(candidate, var->Max()); - break; - } - default: { - IntVarIterator* const domain = domains_[candidate]; - for (domain->Init(); domain->Ok(); domain->Next()) { - TryInsertReached(candidate, domain->Value()); - } - } - } - } - // All non reachable nodes should point to themselves in the incomplete - // case - for (int i = 0; i < size_; ++i) { - if (!reached_[i]) { - nexts_[i]->SetValue(i); - } - } - // Update the outbound_support_ vector. - outbound_support_.swap(temp_support_); - } - - void CheckReachabilityToRoot() { - // TODO(user): Improve with prev_ data structure. - if (root_.Value() == -1) { - return; - } - - insertion_queue_.clear(); - insertion_queue_.push_back(root_.Value()); - temp_support_[root_.Value()] = nexts_[root_.Value()]->Min(); - int processed = 0; - to_visit_.clear(); - for (int i = 0; i < size_; ++i) { - if (!Inactive(i) && i != root_.Value()) { - to_visit_.push_back(i); - } - } - const int inactive = num_inactives_.Value(); - while (processed < insertion_queue_.size() && - insertion_queue_.size() + inactive < size_) { - const int inserted = insertion_queue_[processed++]; - std::vector rejected; - for (int index = 0; index < to_visit_.size(); ++index) { - const int candidate = to_visit_[index]; - if (nexts_[candidate]->Contains(inserted)) { - insertion_queue_.push_back(candidate); - temp_support_[candidate] = inserted; - } else { - rejected.push_back(candidate); - } - } - to_visit_.swap(rejected); - } - for (int i = 0; i < to_visit_.size(); ++i) { - const int node = to_visit_[i]; - nexts_[node]->SetValue(node); - } - temp_support_.swap(inbound_support_); - } - - const std::vector nexts_; - const int size_; - std::vector insertion_queue_; - std::vector to_visit_; - std::vector reached_; - RevArray starts_; - RevArray ends_; - RevArray lengths_; - std::vector domains_; - std::vector outbound_support_; - std::vector inbound_support_; - std::vector temp_support_; - Demon* inbound_demon_; - Demon* outbound_demon_; - Rev root_; - NumericalRev num_inactives_; - const bool complete_; -}; - -// ----- Misc ----- - -bool GreaterThan(int64 x, int64 y) { return y >= x; } -} // namespace - -Constraint* Solver::MakeNoCycle(const std::vector& nexts, - const std::vector& active, - ResultCallback1* sink_handler, - bool assume_paths) { - CHECK_EQ(nexts.size(), active.size()); - if (sink_handler == nullptr) { - sink_handler = - NewPermanentCallback(&GreaterThan, static_cast(nexts.size())); - } - return RevAlloc( - new NoCycle(this, nexts, active, sink_handler, true, assume_paths)); -} - -Constraint* Solver::MakeNoCycle(const std::vector& nexts, - const std::vector& active, - ResultCallback1* sink_handler) { - return MakeNoCycle(nexts, active, sink_handler, true); -} - -// TODO(user): Merge NoCycle and Circuit. -Constraint* Solver::MakeCircuit(const std::vector& nexts) { - return RevAlloc(new Circuit(this, nexts, true)); -} - -Constraint* Solver::MakeSubCircuit(const std::vector& nexts) { - return RevAlloc(new Circuit(this, nexts, false)); -} - -// ----- Path cumul constraints ----- - -namespace { -class BasePathCumul : public Constraint { - public: - BasePathCumul(Solver* const s, const std::vector& nexts, - const std::vector& active, const std::vector& cumuls); - virtual ~BasePathCumul() {} - virtual void Post(); - virtual void InitialPropagate(); - void ActiveBound(int index); - virtual void NextBound(int index) = 0; - virtual bool AcceptLink(int i, int j) const = 0; - void UpdateSupport(int index); - void CumulRange(int index); - virtual string DebugString() const; - - protected: - int64 size() const { return nexts_.size(); } - int cumul_size() const { return cumuls_.size(); } - - const std::vector nexts_; - const std::vector active_; - const std::vector cumuls_; - RevArray prevs_; - std::vector supports_; -}; - -BasePathCumul::BasePathCumul(Solver* const s, const std::vector& nexts, - const std::vector& active, - const std::vector& cumuls) - : Constraint(s), - nexts_(nexts), - active_(active), - cumuls_(cumuls), - prevs_(cumuls.size(), -1), - supports_(nexts.size()) { - CHECK_GE(cumul_size(), size()); - for (int i = 0; i < size(); ++i) { - supports_[i] = -1; - } -} - -void BasePathCumul::InitialPropagate() { - for (int i = 0; i < size(); ++i) { - if (nexts_[i]->Bound()) { - NextBound(i); - } else { - UpdateSupport(i); - } - } -} - -void BasePathCumul::Post() { - for (int i = 0; i < size(); ++i) { - IntVar* var = nexts_[i]; - Demon* d = MakeConstraintDemon1(solver(), this, &BasePathCumul::NextBound, - "NextBound", i); - var->WhenBound(d); - Demon* ds = MakeConstraintDemon1( - solver(), this, &BasePathCumul::UpdateSupport, "UpdateSupport", i); - var->WhenDomain(ds); - Demon* active_demon = MakeConstraintDemon1( - solver(), this, &BasePathCumul::ActiveBound, "ActiveBound", i); - active_[i]->WhenBound(active_demon); - } - for (int i = 0; i < cumul_size(); ++i) { - IntVar* cumul = cumuls_[i]; - Demon* d = MakeConstraintDemon1(solver(), this, &BasePathCumul::CumulRange, - "CumulRange", i); - cumul->WhenRange(d); - } -} - -void BasePathCumul::ActiveBound(int index) { - if (nexts_[index]->Bound()) { - NextBound(index); - } -} - -void BasePathCumul::CumulRange(int index) { - if (index < size()) { - if (nexts_[index]->Bound()) { - NextBound(index); - } else { - UpdateSupport(index); - } - } - if (prevs_[index] >= 0) { - NextBound(prevs_[index]); - } else { - for (int i = 0; i < size(); ++i) { - if (index == supports_[i]) { - UpdateSupport(i); - } - } - } -} - -void BasePathCumul::UpdateSupport(int index) { - int support = supports_[index]; - if (support < 0 || !AcceptLink(index, support)) { - IntVar* var = nexts_[index]; - for (int i = var->Min(); i <= var->Max(); ++i) { - if (i != support && AcceptLink(index, i)) { - supports_[index] = i; - return; - } - } - active_[index]->SetMax(0); - } -} - -string BasePathCumul::DebugString() const { - string out = "PathCumul("; - for (int i = 0; i < size(); ++i) { - out += nexts_[i]->DebugString() + " " + cumuls_[i]->DebugString(); - } - out += ")"; - return out; -} - -// cumuls[next[i]] = cumuls[i] + transits[i] - -class PathCumul : public BasePathCumul { - public: - PathCumul(Solver* const s, const std::vector& nexts, - const std::vector& active, const std::vector& cumuls, - const std::vector& transits) - : BasePathCumul(s, nexts, active, cumuls), transits_(transits) {} - virtual ~PathCumul() {} - virtual void Post(); - virtual void NextBound(int index); - virtual bool AcceptLink(int i, int j) const; - void TransitRange(int index); - - void Accept(ModelVisitor* const visitor) const { - visitor->BeginVisitConstraint(ModelVisitor::kPathCumul, this); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kNextsArgument, - nexts_); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kActiveArgument, - active_); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kCumulsArgument, - cumuls_); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kTransitsArgument, - transits_); - visitor->EndVisitConstraint(ModelVisitor::kPathCumul, this); - } - - private: - const std::vector transits_; -}; - -void PathCumul::Post() { - BasePathCumul::Post(); - for (int i = 0; i < size(); ++i) { - Demon* transit_demon = MakeConstraintDemon1( - solver(), this, &PathCumul::TransitRange, "TransitRange", i); - transits_[i]->WhenRange(transit_demon); - } -} - -void PathCumul::NextBound(int index) { - if (active_[index]->Min() == 0) return; - const int64 next = nexts_[index]->Value(); - IntVar* cumul = cumuls_[index]; - IntVar* cumul_next = cumuls_[next]; - IntVar* transit = transits_[index]; - cumul_next->SetMin(cumul->Min() + transit->Min()); - cumul_next->SetMax(CapAdd(cumul->Max(), transit->Max())); - cumul->SetMin(CapSub(cumul_next->Min(), transit->Max())); - cumul->SetMax(CapSub(cumul_next->Max(), transit->Min())); - transit->SetMin(CapSub(cumul_next->Min(), cumul->Max())); - transit->SetMax(CapSub(cumul_next->Max(), cumul->Min())); - if (prevs_[next] < 0) { - prevs_.SetValue(solver(), next, index); - } -} - -void PathCumul::TransitRange(int index) { - if (nexts_[index]->Bound()) { - NextBound(index); - } else { - UpdateSupport(index); - } - if (prevs_[index] >= 0) { - NextBound(prevs_[index]); - } else { - for (int i = 0; i < size(); ++i) { - if (index == supports_[i]) { - UpdateSupport(i); - } - } - } -} - -bool PathCumul::AcceptLink(int i, int j) const { - const IntVar* const cumul_i = cumuls_[i]; - const IntVar* const cumul_j = cumuls_[j]; - const IntVar* const transit_i = transits_[i]; - return transit_i->Min() <= CapSub(cumul_j->Max(), cumul_i->Min()) && - CapSub(cumul_j->Min(), cumul_i->Max()) <= transit_i->Max(); -} - -// cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]) - -class ResultCallback2PathCumul : public BasePathCumul { - public: - ResultCallback2PathCumul(Solver* const s, const std::vector& nexts, - const std::vector& active, - const std::vector& cumuls, - Solver::IndexEvaluator2* transit_evaluator); - virtual ~ResultCallback2PathCumul() {} - virtual void NextBound(int index); - virtual bool AcceptLink(int i, int j) const; - - void Accept(ModelVisitor* const visitor) const { - visitor->BeginVisitConstraint(ModelVisitor::kPathCumul, this); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kNextsArgument, - nexts_); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kActiveArgument, - active_); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kCumulsArgument, - cumuls_); - // TODO(user): Visit transit correctly. - // visitor->VisitIntegerVariableArrayArgument( - // ModelVisitor::kTransitsArgument, - // transit_evaluator); - visitor->EndVisitConstraint(ModelVisitor::kPathCumul, this); - } - - private: - std::unique_ptr transits_evaluator_; -}; - -ResultCallback2PathCumul::ResultCallback2PathCumul( - Solver* const s, const std::vector& nexts, - const std::vector& active, const std::vector& cumuls, - Solver::IndexEvaluator2* transit_evaluator) - : BasePathCumul(s, nexts, active, cumuls), - transits_evaluator_(transit_evaluator) { - transits_evaluator_->CheckIsRepeatable(); -} - -void ResultCallback2PathCumul::NextBound(int index) { - if (active_[index]->Min() == 0) return; - const int64 next = nexts_[index]->Value(); - IntVar* cumul = cumuls_[index]; - IntVar* cumul_next = cumuls_[next]; - const int64 transit = transits_evaluator_->Run(index, next); - cumul_next->SetMin(cumul->Min() + transit); - cumul_next->SetMax(CapAdd(cumul->Max(), transit)); - cumul->SetMin(CapSub(cumul_next->Min(), transit)); - cumul->SetMax(CapSub(cumul_next->Max(), transit)); - if (prevs_[next] < 0) { - prevs_.SetValue(solver(), next, index); - } -} - -bool ResultCallback2PathCumul::AcceptLink(int i, int j) const { - const IntVar* const cumul_i = cumuls_[i]; - const IntVar* const cumul_j = cumuls_[j]; - const int64 transit = transits_evaluator_->Run(i, j); - return transit <= CapSub(cumul_j->Max(), cumul_i->Min()) && - CapSub(cumul_j->Min(), cumul_i->Max()) <= transit; -} - -// ----- ResulatCallback2SlackPathCumul ----- - -class ResultCallback2SlackPathCumul : public BasePathCumul { - public: - ResultCallback2SlackPathCumul(Solver* const s, const std::vector& nexts, - const std::vector& active, - const std::vector& cumuls, - const std::vector& slacks, - Solver::IndexEvaluator2* transit_evaluator); - virtual ~ResultCallback2SlackPathCumul() {} - virtual void Post(); - virtual void NextBound(int index); - virtual bool AcceptLink(int i, int j) const; - void SlackRange(int index); - - void Accept(ModelVisitor* const visitor) const { - visitor->BeginVisitConstraint(ModelVisitor::kPathCumul, this); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kNextsArgument, - nexts_); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kActiveArgument, - active_); - visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kCumulsArgument, - cumuls_); - // TODO(user): Visit transit correctly. - // visitor->VisitIntegerVariableArrayArgument( - // ModelVisitor::kTransitsArgument, - // transit_evaluator); - visitor->EndVisitConstraint(ModelVisitor::kPathCumul, this); - } - - private: - const std::vector slacks_; - std::unique_ptr transits_evaluator_; -}; - -ResultCallback2SlackPathCumul::ResultCallback2SlackPathCumul( - Solver* const s, const std::vector& nexts, - const std::vector& active, const std::vector& cumuls, - const std::vector& slacks, Solver::IndexEvaluator2* transit_evaluator) - : BasePathCumul(s, nexts, active, cumuls), - slacks_(slacks), - transits_evaluator_(transit_evaluator) { - transits_evaluator_->CheckIsRepeatable(); -} - -void ResultCallback2SlackPathCumul::Post() { - BasePathCumul::Post(); - for (int i = 0; i < size(); ++i) { - Demon* slack_demon = MakeConstraintDemon1( - solver(), this, &ResultCallback2SlackPathCumul::SlackRange, - "SlackRange", i); - slacks_[i]->WhenRange(slack_demon); - } -} - -void ResultCallback2SlackPathCumul::SlackRange(int index) { - if (nexts_[index]->Bound()) { - NextBound(index); - } else { - UpdateSupport(index); - } - if (prevs_[index] >= 0) { - NextBound(prevs_[index]); - } else { - for (int i = 0; i < size(); ++i) { - if (index == supports_[i]) { - UpdateSupport(i); - } - } - } -} - -void ResultCallback2SlackPathCumul::NextBound(int index) { - if (active_[index]->Min() == 0) return; - const int64 next = nexts_[index]->Value(); - IntVar* const cumul = cumuls_[index]; - IntVar* const cumul_next = cumuls_[next]; - IntVar* const slack = slacks_[index]; - const int64 transit = transits_evaluator_->Run(index, next); - const int64 cumul_next_minus_transit_min = CapSub(cumul_next->Min(), transit); - const int64 cumul_next_minus_transit_max = CapSub(cumul_next->Max(), transit); - cumul_next->SetMin(CapAdd(CapAdd(cumul->Min(), transit), slack->Min())); - cumul_next->SetMax(CapAdd(CapAdd(cumul->Max(), transit), slack->Max())); - cumul->SetMin(CapSub(cumul_next_minus_transit_min, slack->Max())); - cumul->SetMax(CapSub(cumul_next_minus_transit_max, slack->Min())); - slack->SetMin(CapSub(cumul_next_minus_transit_min, cumul->Max())); - slack->SetMax(CapSub(cumul_next_minus_transit_max, cumul->Min())); - if (prevs_[next] < 0) { - prevs_.SetValue(solver(), next, index); - } -} - -bool ResultCallback2SlackPathCumul::AcceptLink(int i, int j) const { - const IntVar* const cumul_i = cumuls_[i]; - const IntVar* const cumul_j = cumuls_[j]; - const IntVar* const slack = slacks_[i]; - const int64 transit = transits_evaluator_->Run(i, j); - return CapAdd(transit, slack->Min()) <= - CapSub(cumul_j->Max(), cumul_i->Min()) && - CapSub(cumul_j->Min(), cumul_i->Max()) <= - CapAdd(slack->Max(), transit); -} -} // namespace - -Constraint* Solver::MakePathCumul(const std::vector& nexts, - const std::vector& active, - const std::vector& cumuls, - const std::vector& transits) { - CHECK_EQ(nexts.size(), active.size()); - CHECK_EQ(transits.size(), nexts.size()); - return RevAlloc(new PathCumul(this, nexts, active, cumuls, transits)); -} - -Constraint* Solver::MakePathCumul(const std::vector& nexts, - const std::vector& active, - const std::vector& cumuls, - Solver::IndexEvaluator2* transit_evaluator) { - CHECK_EQ(nexts.size(), active.size()); - return RevAlloc(new ResultCallback2PathCumul(this, nexts, active, cumuls, - transit_evaluator)); -} - -Constraint* Solver::MakePathCumul(const std::vector& nexts, - const std::vector& active, - const std::vector& cumuls, - const std::vector& slacks, - Solver::IndexEvaluator2* transit_evaluator) { - CHECK_EQ(nexts.size(), active.size()); - return RevAlloc(new ResultCallback2SlackPathCumul(this, nexts, active, cumuls, - slacks, transit_evaluator)); -} } // namespace operations_research diff --git a/src/constraint_solver/count_cst.cc b/src/constraint_solver/count_cst.cc index a5da23bdd2..a01d95e2e5 100644 --- a/src/constraint_solver/count_cst.cc +++ b/src/constraint_solver/count_cst.cc @@ -13,7 +13,6 @@ // // Count constraints -#include #include #include #include @@ -85,7 +84,7 @@ class Distribute : public Constraint { void CountVar(int cindex); void CardMin(int cindex); void CardMax(int cindex); - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Distribute(vars = [%s], values = [%s], cards = [%s])", JoinDebugStringPtr(vars_, ", ").c_str(), IntVectorToString(values_, ", ").c_str(), @@ -249,7 +248,7 @@ class FastDistribute : public Constraint { void CountVar(int card_index); void CardMin(int card_index); void CardMax(int card_index); - virtual string DebugString() const; + virtual std::string DebugString() const; void SetRevCannotContribute(int64 var_index, int64 card_index) { Solver* const s = solver(); undecided_.SetToZero(s, var_index, card_index); @@ -304,7 +303,7 @@ FastDistribute::FastDistribute(Solver* const s, const std::vector& vars } } -string FastDistribute::DebugString() const { +std::string FastDistribute::DebugString() const { return StringPrintf("FastDistribute(vars = [%s], cards = [%s])", JoinDebugStringPtr(vars_, ", ").c_str(), JoinDebugStringPtr(cards_, ", ").c_str()); @@ -437,7 +436,7 @@ class BoundedDistribute : public Constraint { void CountVar(int card_index); void CardMin(int card_index); void CardMax(int card_index); - virtual string DebugString() const; + virtual std::string DebugString() const; void SetRevCannotContribute(int64 var_index, int64 card_index) { Solver* const s = solver(); undecided_.SetToZero(s, var_index, card_index); @@ -504,7 +503,7 @@ BoundedDistribute::BoundedDistribute(Solver* const s, } } -string BoundedDistribute::DebugString() const { +std::string BoundedDistribute::DebugString() const { return StringPrintf( "BoundedDistribute([%s], values = [%s], card_min = [%s], card_max = [%s]", JoinDebugStringPtr(vars_, ", ").c_str(), @@ -640,7 +639,7 @@ class BoundedFastDistribute : public Constraint { void CountVar(int card_index); void CardMin(int card_index); void CardMax(int card_index); - virtual string DebugString() const; + virtual std::string DebugString() const; void SetRevCannotContribute(int64 var_index, int64 card_index) { Solver* const s = solver(); undecided_.SetToZero(s, var_index, card_index); @@ -703,7 +702,7 @@ BoundedFastDistribute::BoundedFastDistribute(Solver* const s, } } -string BoundedFastDistribute::DebugString() const { +std::string BoundedFastDistribute::DebugString() const { return StringPrintf( "BoundedFastDistribute([%s], card_min = [%s], card_max = [%s]", JoinDebugStringPtr(vars_, ", ").c_str(), @@ -857,7 +856,7 @@ class SetAllToZero : public Constraint { } } - virtual string DebugString() const { return "SetAllToZero()"; } + virtual std::string DebugString() const { return "SetAllToZero()"; } virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kDistribute, this); diff --git a/src/constraint_solver/default_search.cc b/src/constraint_solver/default_search.cc index d70ca39ddb..8e37ff1c50 100644 --- a/src/constraint_solver/default_search.cc +++ b/src/constraint_solver/default_search.cc @@ -11,8 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include -#include +#include #include "base/hash.h" #include #include "base/unique_ptr.h" @@ -30,8 +29,8 @@ #include "constraint_solver/constraint_solver.h" #include "constraint_solver/constraint_solveri.h" #include "util/cached_log.h" -#include "base/random.h" #include "util/string_array.h" +#include "base/random.h" DEFINE_int32(cp_impact_divider, 10, "Divider for continuous update."); @@ -122,7 +121,7 @@ class FindVar : public DecisionVisitor { return value_; } - virtual string DebugString() const { return "FindVar decision visitor"; } + virtual std::string DebugString() const { return "FindVar decision visitor"; } private: IntVar* var_; @@ -575,7 +574,7 @@ class ImpactRecorder : public SearchMonitor { } } - virtual string DebugString() const { return "ImpactRecorder"; } + virtual std::string DebugString() const { return "ImpactRecorder"; } private: // A container for the variables needed in FirstRun that is reversibly @@ -599,7 +598,7 @@ class ImpactRecorder : public SearchMonitor { InitVarImpacts* without_split() { return &without_splits_; } InitVarImpactsWithSplits* with_splits() { return &with_splits_; } - virtual string DebugString() const { return "FirstRunVariableContainers"; } + virtual std::string DebugString() const { return "FirstRunVariableContainers"; } private: std::unique_ptr > update_impact_callback_; @@ -651,7 +650,7 @@ class ChoiceInfo { ChoiceInfo(IntVar* const var, int64 value, bool left) : value_(value), var_(var), left_(left) {} - string DebugString() const { + std::string DebugString() const { return StringPrintf("%s %s %lld", var_->name().c_str(), (left_ ? "==" : "!="), value_); } @@ -761,7 +760,7 @@ class RestartMonitor : public SearchMonitor { } } - virtual string DebugString() const { return "RestartMonitor"; } + virtual std::string DebugString() const { return "RestartMonitor"; } private: // Called before applying the refutation of the decision. This @@ -1032,7 +1031,7 @@ class RunHeuristicsAsDives : public Decision { HeuristicWrapper(Solver* const solver, const std::vector& vars, Solver::IntVarStrategy var_strategy, Solver::IntValueStrategy value_strategy, - const string& heuristic_name, int heuristic_runs) + const std::string& heuristic_name, int heuristic_runs) : phase(solver->MakePhase(vars, var_strategy, value_strategy)), name(heuristic_name), runs(heuristic_runs) {} @@ -1040,7 +1039,7 @@ class RunHeuristicsAsDives : public Decision { // The decision builder we are going to use in this dive. DecisionBuilder* const phase; // A name for logging purposes. - const string name; + const std::string name; // How many times we will run this particular heuristic in case the // parameter run_all_heuristics is true. This is useful for random // heuristics where it makes sense to run them more than once. @@ -1110,8 +1109,8 @@ class DefaultIntegerSearch : public DecisionBuilder { visitor->EndVisitExtension(ModelVisitor::kVariableGroupExtension); } - virtual string DebugString() const { - string out = "DefaultIntegerSearch("; + virtual std::string DebugString() const { + std::string out = "DefaultIntegerSearch("; if (parameters_.decision_builder == nullptr) { out.append("Impact Based Search, "); diff --git a/src/constraint_solver/demon_profiler.cc b/src/constraint_solver/demon_profiler.cc index ecf40f6b38..66fcd1ad00 100644 --- a/src/constraint_solver/demon_profiler.cc +++ b/src/constraint_solver/demon_profiler.cc @@ -11,9 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include -#include #include +#include +#include #include "base/hash.h" #include #include @@ -164,7 +164,7 @@ class DemonProfiler : public PropagationMonitor { virtual void StartProcessingIntegerVariable(IntVar* const var) {} virtual void EndProcessingIntegerVariable(IntVar* const var) {} - virtual void PushContext(const string& context) {} + virtual void PushContext(const std::string& context) {} virtual void PopContext() {} virtual void BeginFail() { @@ -246,7 +246,7 @@ class DemonProfiler : public PropagationMonitor { } // Exports collected data as human-readable text. - void PrintOverview(Solver* const solver, const string& filename) { + void PrintOverview(Solver* const solver, const std::string& filename) { const char* const kConstraintFormat = " - Constraint: %s\n failures=%" GG_LL_FORMAT "d, initial propagation runtime=%" GG_LL_FORMAT @@ -257,7 +257,7 @@ class DemonProfiler : public PropagationMonitor { "d, failures=%" GG_LL_FORMAT "d, total runtime=%" GG_LL_FORMAT "d us, [average=%.2lf, median=%.2lf, stddev=%.2lf]\n"; File* const file = File::Open(filename, "w"); - const string model = + const std::string model = StringPrintf("Model %s:\n", solver->model_name().c_str()); if (file) { file->Write(model.c_str(), model.length()); @@ -296,7 +296,7 @@ class DemonProfiler : public PropagationMonitor { &demon_invocations, &total_demon_runtime, &demon_count); - const string constraint_message = + const std::string constraint_message = StringPrintf(kConstraintFormat, ct->DebugString().c_str(), fails, initial_propagation_runtime, demon_count, demon_invocations, total_demon_runtime); @@ -314,7 +314,7 @@ class DemonProfiler : public PropagationMonitor { ExportInformation(demon_runs, &invocations, &fails, &runtime, &mean_runtime, &median_runtime, &standard_deviation); - const string runs = StringPrintf( + const std::string runs = StringPrintf( kDemonFormat, demon_runs->demon_id().c_str(), invocations, fails, runtime, mean_runtime, median_runtime, standard_deviation); file->Write(runs.c_str(), runs.length()); @@ -414,7 +414,7 @@ class DemonProfiler : public PropagationMonitor { // start of the search. virtual void Install() { SearchMonitor::Install(); } - virtual string DebugString() const { return "DemonProfiler"; } + virtual std::string DebugString() const { return "DemonProfiler"; } private: Constraint* active_constraint_; @@ -425,7 +425,7 @@ class DemonProfiler : public PropagationMonitor { hash_map > demons_per_constraint_; }; -void Solver::ExportProfilingOverview(const string& filename) { +void Solver::ExportProfilingOverview(const std::string& filename) { if (demon_profiler_ != nullptr) { demon_profiler_->PrintOverview(this, filename); } diff --git a/src/constraint_solver/dependency_graph.cc b/src/constraint_solver/dependency_graph.cc index aaef8c19a1..b51be36004 100644 --- a/src/constraint_solver/dependency_graph.cc +++ b/src/constraint_solver/dependency_graph.cc @@ -54,7 +54,7 @@ class DependencyGraphNode { void SetMax(int64 new_max); virtual void SetMaxInternal(int64 new_max) = 0; virtual void SetState(PerformedState state) = 0; - virtual string DebugString() const = 0; + virtual std::string DebugString() const = 0; void AddMinDependency(DependencyGraphNode* const node, int64 offset); void AddMaxDependency(DependencyGraphNode* const node, int64 offset); @@ -112,7 +112,7 @@ class IntervalVarStartAdapter : public DependencyGraphNode { interval_var_->SetPerformed(state == PERFORMED); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Node-Start(%s)", interval_var_->DebugString().c_str()); } @@ -168,7 +168,7 @@ class NonReversibleDependencyGraph : public DependencyGraph { ProcessQueue(); } - virtual string DebugString() const { return "NonReversibleDependencyGraph"; } + virtual std::string DebugString() const { return "NonReversibleDependencyGraph"; } private: bool Dequeue(DependencyGraphNode** const node, bool* const changed_min) { diff --git a/src/constraint_solver/deviation.cc b/src/constraint_solver/deviation.cc index a6dccac699..ab838cc395 100644 --- a/src/constraint_solver/deviation.cc +++ b/src/constraint_solver/deviation.cc @@ -11,9 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include -#include #include +#include #include "base/unique_ptr.h" #include #include @@ -72,7 +71,7 @@ class Deviation : public Constraint { PropagateBounds(delta_min); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Deviation([%s], deviation_var = %s, sum = %lld)", JoinDebugStringPtr(vars_, ", ").c_str(), deviation_var_->DebugString().c_str(), total_sum_); diff --git a/src/constraint_solver/diffn.cc b/src/constraint_solver/diffn.cc index 4303e43d78..16376aa943 100644 --- a/src/constraint_solver/diffn.cc +++ b/src/constraint_solver/diffn.cc @@ -19,8 +19,8 @@ #include "base/scoped_ptr.h" #include "base/stringprintf.h" #include "base/concise_iterator.h" -#include "base/int_type_indexed_vector.h" #include "base/int_type.h" +#include "base/int_type_indexed_vector.h" #include "base/hash.h" #include "constraint_solver/constraint_solver.h" #include "constraint_solver/constraint_solveri.h" @@ -108,7 +108,7 @@ class Diffn : public Constraint { PropagateAll(); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Diffn(x = [%s], y = [%s], dx = [%s], dy = [%s]))", JoinDebugStringPtr(x_, ", ").c_str(), JoinDebugStringPtr(y_, ", ").c_str(), diff --git a/src/constraint_solver/element.cc b/src/constraint_solver/element.cc index 86ad7836a6..aea9ed02f3 100644 --- a/src/constraint_solver/element.cc +++ b/src/constraint_solver/element.cc @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include #include #include "base/unique_ptr.h" #include @@ -235,7 +234,7 @@ class IntElementConstraint : public CastConstraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntElementConstraint(%s, %s, %s)", IntVectorToString(values_, ", ").c_str(), index_->DebugString().c_str(), @@ -270,7 +269,7 @@ class IntExprElement : public BaseIntExprElement { virtual ~IntExprElement() {} - virtual string name() const { + virtual std::string name() const { const int size = values_.size(); if (size > 10) { return StringPrintf("IntElement(array of size %d, %s)", size, @@ -282,7 +281,7 @@ class IntExprElement : public BaseIntExprElement { } } - virtual string DebugString() const { + virtual std::string DebugString() const { const int size = values_.size(); if (size > 10) { return StringPrintf("IntElement(array of size %d, %s)", size, @@ -340,12 +339,12 @@ class IncreasingIntExprElement : public BaseIntExpr { virtual void SetRange(int64 mi, int64 ma); virtual bool Bound() const { return (index_->Bound()); } // TODO(user) : improve me, the previous test is not always true - virtual string name() const { + virtual std::string name() const { return StringPrintf("IntElement(%s, %s)", IntVectorToString(values_, ", ").c_str(), index_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntElement(%s, %s)", IntVectorToString(values_, ", ").c_str(), index_->DebugString().c_str()); @@ -541,11 +540,11 @@ class IntExprFunctionElement : public BaseIntExprElement { IntVar* const expr, bool del); virtual ~IntExprFunctionElement(); - virtual string name() const { + virtual std::string name() const { return StringPrintf("IntFunctionElement(%s)", expr_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntFunctionElement(%s)", expr_->DebugString().c_str()); } @@ -655,12 +654,12 @@ class IncreasingIntExprFunctionElement : public BaseIntExpr { index_->SetRange(nmin, nmax); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("IncreasingIntExprFunctionElement(values, %s)", index_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IncreasingIntExprFunctionElement(values, %s)", index_->DebugString().c_str()); } @@ -708,7 +707,7 @@ class OppositeCallback : public BaseObject { int64 Run(int64 index) { return -values_->Run(index); } - virtual string DebugString() const { return "OppositeCallback"; } + virtual std::string DebugString() const { return "OppositeCallback"; } public: std::unique_ptr> values_; @@ -740,7 +739,7 @@ class IntIntExprFunctionElement : public BaseIntExpr { ResultCallback2* values, IntVar* const expr1, IntVar* const expr2); virtual ~IntIntExprFunctionElement(); - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntIntFunctionElement(%s,%s)", expr1_->DebugString().c_str(), expr2_->DebugString().c_str()); @@ -984,7 +983,7 @@ class IntExprArrayElementCt : public CastConstraint { void Update(int index); void UpdateExpr(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kElementEqual, this); @@ -1096,7 +1095,7 @@ void IntExprArrayElementCt::UpdateExpr() { } } -string IntExprArrayElementCt::DebugString() const { +std::string IntExprArrayElementCt::DebugString() const { if (size() > 10) { return StringPrintf("IntExprArrayElement(var array of size %" GG_LL_FORMAT "d, %s) == %s", @@ -1158,7 +1157,7 @@ class IntExprArrayElementCstCt : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntExprArrayElement([%s], %s) == %" GG_LL_FORMAT "d", JoinDebugStringPtr(vars_, ", ").c_str(), index_->DebugString().c_str(), target_); @@ -1253,7 +1252,7 @@ class IntExprIndexOfCt : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntExprIndexOf([%s], %s) == %" GG_LL_FORMAT "d", JoinDebugStringPtr(vars_, ", ").c_str(), index_->DebugString().c_str(), target_); @@ -1318,7 +1317,7 @@ IntExpr* Solver::MakeElement(const std::vector& vars, IntVar* const ind emax = std::max(emax, vars[index_value]->Max()); } } - const string vname = + const std::string vname = size > 10 ? StringPrintf("ElementVar(var array of size %d, %s)", size, index->DebugString().c_str()) @@ -1395,7 +1394,7 @@ IntExpr* Solver::MakeIndexExpression(const std::vector& vars, int64 val if (cache != nullptr) { return cache->Var(); } else { - const string name = StringPrintf("Index(%s, %" GG_LL_FORMAT "d)", + const std::string name = StringPrintf("Index(%s, %" GG_LL_FORMAT "d)", JoinNamePtr(vars, ", ").c_str(), value); IntVar* const index = MakeIntVar(0, vars.size() - 1, name); diff --git a/src/constraint_solver/expr_array.cc b/src/constraint_solver/expr_array.cc index 3ab169a0bf..48796818ed 100644 --- a/src/constraint_solver/expr_array.cc +++ b/src/constraint_solver/expr_array.cc @@ -13,8 +13,8 @@ // // Array Expression constraints -#include #include +#include #include #include @@ -55,13 +55,13 @@ class TreeArrayConstraint : public CastConstraint { root_node_ = &tree_[0][0]; } - string DebugStringInternal(const string& name) const { + std::string DebugStringInternal(const std::string& name) const { return StringPrintf("%s(%s) == %s", name.c_str(), JoinDebugStringPtr(vars_, ", ").c_str(), target_var_->DebugString().c_str()); } - void AcceptInternal(const string& name, ModelVisitor* const visitor) const { + void AcceptInternal(const std::string& name, ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(name, this); visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kVarsArgument, vars_); @@ -277,7 +277,7 @@ class SumConstraint : public TreeArrayConstraint { target_var_->SetRange(RootMin(), RootMax()); } - string DebugString() const { return DebugStringInternal("Sum"); } + std::string DebugString() const { return DebugStringInternal("Sum"); } virtual void Accept(ModelVisitor* const visitor) const { AcceptInternal(ModelVisitor::kSumEqual, visitor); @@ -467,7 +467,7 @@ class SafeSumConstraint : public TreeArrayConstraint { target_var_->SetRange(RootMin(), RootMax()); } - string DebugString() const { return DebugStringInternal("Sum"); } + std::string DebugString() const { return DebugStringInternal("Sum"); } virtual void Accept(ModelVisitor* const visitor) const { AcceptInternal(ModelVisitor::kSumEqual, visitor); @@ -504,7 +504,7 @@ class SafeSumConstraint : public TreeArrayConstraint { // ---------- Min Array ---------- -// This constraint implements min(vars) == min_var. +// This constraint implements std::min(vars) == min_var. class MinConstraint : public TreeArrayConstraint { public: MinConstraint(Solver* const solver, const std::vector& vars, @@ -647,7 +647,7 @@ class MinConstraint : public TreeArrayConstraint { MinVarChanged(); } - string DebugString() const { return DebugStringInternal("Min"); } + std::string DebugString() const { return DebugStringInternal("Min"); } virtual void Accept(ModelVisitor* const visitor) const { AcceptInternal(ModelVisitor::kMinEqual, visitor); @@ -659,7 +659,7 @@ class MinConstraint : public TreeArrayConstraint { // ---------- Max Array ---------- -// This constraint implements max(vars) == max_var. +// This constraint implements std::max(vars) == max_var. class MaxConstraint : public TreeArrayConstraint { public: MaxConstraint(Solver* const solver, const std::vector& vars, @@ -801,7 +801,7 @@ class MaxConstraint : public TreeArrayConstraint { MaxVarChanged(); } - string DebugString() const { return DebugStringInternal("Max"); } + std::string DebugString() const { return DebugStringInternal("Max"); } virtual void Accept(ModelVisitor* const visitor) const { AcceptInternal(ModelVisitor::kMaxEqual, visitor); @@ -901,7 +901,7 @@ class ArrayBoolAndEq : public CastConstraint { } } - string DebugString() const { + std::string DebugString() const { return StringPrintf("And(%s) == %s", JoinDebugStringPtr(vars_, ", ").c_str(), target_var_->DebugString().c_str()); @@ -1031,7 +1031,7 @@ class ArrayBoolOrEq : public CastConstraint { } } - string DebugString() const { + std::string DebugString() const { return StringPrintf("Or(%s) == %s", JoinDebugStringPtr(vars_, ", ").c_str(), target_var_->DebugString().c_str()); @@ -1082,7 +1082,7 @@ class BaseSumBooleanConstraint : public Constraint { virtual ~BaseSumBooleanConstraint() {} protected: - string DebugStringInternal(const string& name) const { + std::string DebugStringInternal(const std::string& name) const { return StringPrintf("%s(%s)", name.c_str(), JoinDebugStringPtr(vars_, ", ").c_str()); } @@ -1137,7 +1137,7 @@ class SumBooleanLessOrEqualToOne : public BaseSumBooleanConstraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return DebugStringInternal("SumBooleanLessOrEqualToOne"); } @@ -1165,7 +1165,7 @@ class SumBooleanGreaterOrEqualToOne : public BaseSumBooleanConstraint { void Update(int index); void UpdateVar(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kSumGreaterOrEqual, this); @@ -1226,7 +1226,7 @@ void SumBooleanGreaterOrEqualToOne::Update(int index) { } } -string SumBooleanGreaterOrEqualToOne::DebugString() const { +std::string SumBooleanGreaterOrEqualToOne::DebugString() const { return DebugStringInternal("SumBooleanGreaterOrEqualToOne"); } @@ -1316,7 +1316,7 @@ class SumBooleanEqualToOne : public BaseSumBooleanConstraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return DebugStringInternal("SumBooleanEqualToOne"); } @@ -1447,7 +1447,7 @@ class SumBooleanEqualToVar : public BaseSumBooleanConstraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("%s == %s", DebugStringInternal("SumBoolean").c_str(), sum_var_->DebugString().c_str()); } @@ -1598,7 +1598,7 @@ class BooleanScalProdLessConstant : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("BooleanScalProd([%s], [%s]) <= %" GG_LL_FORMAT "d)", JoinDebugStringPtr(vars_, ", ").c_str(), IntVectorToString(coefs_, ", ").c_str(), upper_bound_); @@ -1715,7 +1715,7 @@ class PositiveBooleanScalProdEqVar : public CastConstraint { Propagate(); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("PositiveBooleanScal([%s], [%s]) == %s", JoinDebugStringPtr(vars_, ", ").c_str(), IntVectorToString(coefs_, ", ").c_str(), @@ -1828,7 +1828,7 @@ class PositiveBooleanScalProd : public BaseIntExpr { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("PositiveBooleanScalProd([%s], [%s])", JoinDebugStringPtr(vars_, ", ").c_str(), IntVectorToString(coefs_, ", ").c_str()); @@ -1956,7 +1956,7 @@ class PositiveBooleanScalProdEqCst : public Constraint { Propagate(); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("PositiveBooleanScalProd([%s], [%s]) == %" GG_LL_FORMAT "d", JoinDebugStringPtr(vars_, ", ").c_str(), @@ -1995,33 +1995,33 @@ class ExprLinearizer : public ModelParser { virtual ~ExprLinearizer() {} // Begin/End visit element. - virtual void BeginVisitModel(const string& solver_name) { + virtual void BeginVisitModel(const std::string& solver_name) { LOG(FATAL) << "Should not be here"; } - virtual void EndVisitModel(const string& solver_name) { + virtual void EndVisitModel(const std::string& solver_name) { LOG(FATAL) << "Should not be here"; } - virtual void BeginVisitConstraint(const string& type_name, + virtual void BeginVisitConstraint(const std::string& type_name, const Constraint* const constraint) { LOG(FATAL) << "Should not be here"; } - virtual void EndVisitConstraint(const string& type_name, + virtual void EndVisitConstraint(const std::string& type_name, const Constraint* const constraint) { LOG(FATAL) << "Should not be here"; } - virtual void BeginVisitExtension(const string& type) {} + virtual void BeginVisitExtension(const std::string& type) {} - virtual void EndVisitExtension(const string& type) {} - virtual void BeginVisitIntegerExpression(const string& type_name, + virtual void EndVisitExtension(const std::string& type) {} + virtual void BeginVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) { BeginVisit(true); } - virtual void EndVisitIntegerExpression(const string& type_name, + virtual void EndVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) { if (IS_TYPE(type_name, kSum)) { VisitSum(expr); @@ -2042,7 +2042,7 @@ class ExprLinearizer : public ModelParser { } virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { if (operation == ModelVisitor::kSumOperation) { AddConstant(value); @@ -2075,37 +2075,37 @@ class ExprLinearizer : public ModelParser { } // Visit integer arguments. - virtual void VisitIntegerArgument(const string& arg_name, int64 value) { + virtual void VisitIntegerArgument(const std::string& arg_name, int64 value) { Top()->SetIntegerArgument(arg_name, value); } - virtual void VisitIntegerArrayArgument(const string& arg_name, + virtual void VisitIntegerArrayArgument(const std::string& arg_name, const std::vector& values) { Top()->SetIntegerArrayArgument(arg_name, values); } - virtual void VisitIntegerMatrixArgument(const string& arg_name, + virtual void VisitIntegerMatrixArgument(const std::string& arg_name, const IntTupleSet& values) { Top()->SetIntegerMatrixArgument(arg_name, values); } // Visit integer expression argument. - virtual void VisitIntegerExpressionArgument(const string& arg_name, + virtual void VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument) { Top()->SetIntegerExpressionArgument(arg_name, argument); } virtual void VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { Top()->SetIntegerVariableArrayArgument(arg_name, arguments); } // Visit interval argument. - virtual void VisitIntervalArgument(const string& arg_name, + virtual void VisitIntervalArgument(const std::string& arg_name, IntervalVar* const argument) {} virtual void VisitIntervalArrayArgument( - const string& arg_name, const std::vector& argument) {} + const std::string& arg_name, const std::vector& argument) {} void Visit(const IntExpr* const expr, int64 multiplier) { if (expr->Min() == expr->Max()) { @@ -2119,7 +2119,7 @@ class ExprLinearizer : public ModelParser { int64 Constant() const { return constant_; } - virtual string DebugString() const { return "ExprLinearizer"; } + virtual std::string DebugString() const { return "ExprLinearizer"; } private: void BeginVisit(bool active) { PushArgumentHolder(); } @@ -2577,7 +2577,7 @@ IntExpr* MakeSumArrayAux(Solver* const solver, const std::vector& vars, if (cache != nullptr) { return solver->MakeSum(cache, constant); } else { - const string name = + const std::string name = StringPrintf("Sum([%s])", JoinNamePtr(vars, ", ").c_str()); IntVar* const sum_var = solver->MakeIntVar(new_min, new_max, name); if (AreAllBooleans(vars)) { @@ -2704,15 +2704,15 @@ IntExpr* MakeScalProdFct(Solver* solver, const std::vector& pre_vars, return solver->MakeIntConst(constant); } // Can we simplify using some gcd computation. - int64 gcd = std::abs(coefs[0]); + int64 gcd = abs(coefs[0]); for (int i = 1; i < coefs.size(); ++i) { - gcd = MathUtil::GCD64(gcd, std::abs(coefs[i])); + gcd = MathUtil::GCD64(gcd, abs(coefs[i])); if (gcd == 1) { break; } } if (constant != 0 && gcd != 1) { - gcd = MathUtil::GCD64(gcd, std::abs(constant)); + gcd = MathUtil::GCD64(gcd, abs(constant)); } if (gcd > 1) { for (int i = 0; i < coefs.size(); ++i) { @@ -2772,7 +2772,7 @@ IntExpr* Solver::MakeSum(const std::vector& vars) { IntVar* sum_var = nullptr; const bool all_booleans = AreAllBooleans(vars); if (all_booleans) { - const string name = + const std::string name = StringPrintf("BooleanSum([%s])", JoinNamePtr(vars, ", ").c_str()); sum_var = MakeIntVar(new_min, new_max, name); @@ -2780,7 +2780,7 @@ IntExpr* Solver::MakeSum(const std::vector& vars) { } else if (new_min != kint64min && new_max != kint64max) { sum_var = MakeSumFct(this, vars)->Var(); } else { - const string name = + const std::string name = StringPrintf("Sum([%s])", JoinNamePtr(vars, ", ").c_str()); sum_var = MakeIntVar(new_min, new_max, name); AddConstraint(RevAlloc(new SafeSumConstraint(this, vars, sum_var))); diff --git a/src/constraint_solver/expr_cst.cc b/src/constraint_solver/expr_cst.cc index b5b88d10c2..ccf64613e6 100644 --- a/src/constraint_solver/expr_cst.cc +++ b/src/constraint_solver/expr_cst.cc @@ -13,7 +13,7 @@ // // Expression constraints -#include +#include #include #include #include @@ -46,7 +46,7 @@ class EqualityExprCst : public Constraint { virtual IntVar* Var() { return solver()->MakeIsEqualCstVar(expr_->Var(), value_); } - virtual string DebugString() const; + virtual std::string DebugString() const; virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kEquality, this); @@ -73,7 +73,7 @@ void EqualityExprCst::Post() { void EqualityExprCst::InitialPropagate() { expr_->SetValue(value_); } -string EqualityExprCst::DebugString() const { +std::string EqualityExprCst::DebugString() const { return StringPrintf("(%s == %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), value_); } @@ -119,7 +119,7 @@ class GreaterEqExprCst : public Constraint { virtual ~GreaterEqExprCst() {} virtual void Post(); virtual void InitialPropagate(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual IntVar* Var() { return solver()->MakeIsGreaterOrEqualCstVar(expr_->Var(), value_); } @@ -149,7 +149,7 @@ void GreaterEqExprCst::Post() { void GreaterEqExprCst::InitialPropagate() { expr_->SetMin(value_); } -string GreaterEqExprCst::DebugString() const { +std::string GreaterEqExprCst::DebugString() const { return StringPrintf("(%s >= %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), value_); } @@ -185,7 +185,7 @@ class LessEqExprCst : public Constraint { virtual ~LessEqExprCst() {} virtual void Post(); virtual void InitialPropagate(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual IntVar* Var() { return solver()->MakeIsLessOrEqualCstVar(expr_->Var(), value_); } @@ -214,7 +214,7 @@ void LessEqExprCst::Post() { void LessEqExprCst::InitialPropagate() { expr_->SetMax(value_); } -string LessEqExprCst::DebugString() const { +std::string LessEqExprCst::DebugString() const { return StringPrintf("(%s <= %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), value_); } @@ -251,7 +251,7 @@ class DiffCst : public Constraint { virtual void Post() {} virtual void InitialPropagate(); void BoundPropagate(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual IntVar* Var() { return solver()->MakeIsDifferentCstVar(var_, value_); } @@ -297,7 +297,7 @@ void DiffCst::BoundPropagate() { } } -string DiffCst::DebugString() const { +std::string DiffCst::DebugString() const { return StringPrintf("(%s != %" GG_LL_FORMAT "d)", var_->DebugString().c_str(), value_); } @@ -361,7 +361,7 @@ class IsEqualCstCt : public CastConstraint { demon_->inhibit(solver()); } } - string DebugString() const { + std::string DebugString() const { return StringPrintf("IsEqualCstCt(%s, %" GG_LL_FORMAT "d, %s)", var_->DebugString().c_str(), cst_, target_var_->DebugString().c_str()); @@ -477,7 +477,7 @@ class IsDiffCstCt : public CastConstraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IsDiffCstCt(%s, %" GG_LL_FORMAT "d, %s)", var_->DebugString().c_str(), cst_, target_var_->DebugString().c_str()); @@ -576,7 +576,7 @@ class IsGreaterEqualCstCt : public CastConstraint { demon_->inhibit(solver()); } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IsGreaterEqualCstCt(%s, %" GG_LL_FORMAT "d, %s)", expr_->DebugString().c_str(), cst_, target_var_->DebugString().c_str()); @@ -676,7 +676,7 @@ class IsLessEqualCstCt : public CastConstraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IsLessEqualCstCt(%s, %" GG_LL_FORMAT "d, %s)", expr_->DebugString().c_str(), cst_, target_var_->DebugString().c_str()); @@ -753,7 +753,7 @@ class BetweenCt : public Constraint { virtual void InitialPropagate() { var_->SetRange(min_, max_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("BetweenCt(%s, %" GG_LL_FORMAT "d, %" GG_LL_FORMAT "d)", var_->DebugString().c_str(), min_, max_); } @@ -821,7 +821,7 @@ class IsBetweenCt : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IsBetweenCt(%s, %" GG_LL_FORMAT "d, %" GG_LL_FORMAT "d, %s)", var_->DebugString().c_str(), min_, max_, @@ -879,7 +879,7 @@ class MemberCt : public Constraint { virtual void InitialPropagate() { var_->SetValues(values_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Member(%s, %s)", var_->DebugString().c_str(), IntVectorToString(values_, ", ").c_str()); } @@ -963,7 +963,7 @@ class IsMemberCt : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IsMemberCt(%s, %s, %s)", var_->DebugString().c_str(), IntVectorToString(values_, ", ").c_str(), boolvar_->DebugString().c_str()); diff --git a/src/constraint_solver/expressions.cc b/src/constraint_solver/expressions.cc index 1341abf49a..d4b3b55842 100644 --- a/src/constraint_solver/expressions.cc +++ b/src/constraint_solver/expressions.cc @@ -11,9 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include -#include #include +#include #include "base/hash.h" #include "base/unique_ptr.h" #include @@ -44,7 +43,7 @@ namespace operations_research { // ---------- IntExpr ---------- -IntVar* IntExpr::VarWithName(const string& name) { +IntVar* IntExpr::VarWithName(const std::string& name) { IntVar* const var = Var(); var->set_name(name); return var; @@ -54,7 +53,7 @@ IntVar* IntExpr::VarWithName(const string& name) { IntVar::IntVar(Solver* const s) : IntExpr(s) {} -IntVar::IntVar(Solver* const s, const string& name) : IntExpr(s) { +IntVar::IntVar(Solver* const s, const std::string& name) : IntExpr(s) { set_name(name); } @@ -167,9 +166,9 @@ IntVar* BooleanVar::IsLessOrEqual(int64 constant) { } } -string BooleanVar::DebugString() const { - string out; - const string& var_name = name(); +std::string BooleanVar::DebugString() const { + std::string out; + const std::string& var_name = name(); if (!var_name.empty()) { out = var_name + "("; } else { @@ -222,7 +221,7 @@ class DomainIntVar : public IntVar { } } - virtual string DebugString() const { return "BitSetIterator"; } + virtual std::string DebugString() const { return "BitSetIterator"; } private: uint64* const bitset_; @@ -245,7 +244,7 @@ class DomainIntVar : public IntVar { virtual void DelayRemoveValue(int64 val) = 0; virtual void ApplyRemovedValues(DomainIntVar* var) = 0; virtual void ClearRemovedValues() = 0; - virtual string pretty_DebugString(int64 min, int64 max) const = 0; + virtual std::string pretty_DebugString(int64 min, int64 max) const = 0; virtual BitSetIterator* MakeIterator() = 0; void InitHoles() { @@ -282,7 +281,7 @@ class DomainIntVar : public IntVar { virtual Solver::DemonPriority priority() const { return Solver::VAR_PRIORITY; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Handler(%s)", var_->DebugString().c_str()); } @@ -359,9 +358,9 @@ class DomainIntVar : public IntVar { if (variable_->Bound()) { boolvar = solver()->MakeIntConst(1); } else { - const string vname = variable_->HasName() ? variable_->name() + const std::string vname = variable_->HasName() ? variable_->name() : variable_->DebugString(); - const string bname = StringPrintf("Watch<%s == %" GG_LL_FORMAT "d>", + const std::string bname = StringPrintf("Watch<%s == %" GG_LL_FORMAT "d>", vname.c_str(), value); boolvar = solver()->MakeBoolVar(bname); } @@ -497,7 +496,7 @@ class DomainIntVar : public IntVar { visitor->EndVisitConstraint(ModelVisitor::kVarValueWatcher, this); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("ValueWatcher(%s)", variable_->DebugString().c_str()); } @@ -602,9 +601,9 @@ class DomainIntVar : public IntVar { if (variable_->Min() >= value) { boolvar = solver()->MakeIntConst(1); } else { - const string vname = variable_->HasName() ? variable_->name() + const std::string vname = variable_->HasName() ? variable_->name() : variable_->DebugString(); - const string bname = StringPrintf("Watch<%s >= %" GG_LL_FORMAT "d>", + const std::string bname = StringPrintf("Watch<%s >= %" GG_LL_FORMAT "d>", vname.c_str(), value); boolvar = solver()->MakeBoolVar(bname); } @@ -729,7 +728,7 @@ class DomainIntVar : public IntVar { visitor->EndVisitConstraint(ModelVisitor::kVarBoundWatcher, this); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("BoundWatcher(%s)", variable_->DebugString().c_str()); } @@ -765,9 +764,9 @@ class DomainIntVar : public IntVar { }; // ----- Main Class ----- - DomainIntVar(Solver* const s, int64 vmin, int64 vmax, const string& name); + DomainIntVar(Solver* const s, int64 vmin, int64 vmax, const std::string& name); DomainIntVar(Solver* const s, const std::vector& sorted_values, - const string& name); + const std::string& name); virtual ~DomainIntVar(); virtual int64 Min() const { return min_.Value(); } @@ -954,10 +953,10 @@ class DomainIntVar : public IntVar { virtual int64 OldMin() const { return std::min(old_min_, min_.Value()); } virtual int64 OldMax() const { return std::max(old_max_, max_.Value()); } - virtual string DebugString() const; + virtual std::string DebugString() const; BitSet* bitset() const { return bits_; } virtual int VarType() const { return DOMAIN_INT_VAR; } - virtual string BaseName() const { return "IntegerVar"; } + virtual std::string BaseName() const { return "IntegerVar"; } friend class PlusCstDomainIntVar; friend class LinkExprAndDomainIntVar; @@ -1132,8 +1131,8 @@ class SimpleBitSet : public DomainIntVar::BitSet { } virtual uint64 Size() const { return size_.Value(); } - virtual string DebugString() const { - string out; + virtual std::string DebugString() const { + std::string out; SStringPrintf(&out, "SimpleBitSet(%" GG_LL_FORMAT "d..%" GG_LL_FORMAT "d : ", omin_, omax_); @@ -1156,8 +1155,8 @@ class SimpleBitSet : public DomainIntVar::BitSet { virtual void ClearRemovedValues() { removed_.clear(); } - virtual string pretty_DebugString(int64 min, int64 max) const { - string out; + virtual std::string pretty_DebugString(int64 min, int64 max) const { + std::string out; DCHECK(bit(min)); DCHECK(bit(max)); if (max != min) { @@ -1349,7 +1348,7 @@ class SmallBitSet : public DomainIntVar::BitSet { virtual uint64 Size() const { return size_.Value(); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("SmallBitSet(%" GG_LL_FORMAT "d..%" GG_LL_FORMAT "d : %llx)", omin_, omax_, bits_); @@ -1371,8 +1370,8 @@ class SmallBitSet : public DomainIntVar::BitSet { virtual void ClearRemovedValues() { removed_.clear(); } - virtual string pretty_DebugString(int64 min, int64 max) const { - string out; + virtual std::string pretty_DebugString(int64 min, int64 max) const { + std::string out; DCHECK(bit(min)); DCHECK(bit(max)); if (max != min) { @@ -1603,7 +1602,7 @@ class UnaryIterator : public IntVarIterator { }; DomainIntVar::DomainIntVar(Solver* const s, int64 vmin, int64 vmax, - const string& name) + const std::string& name) : IntVar(s, name), min_(vmin), max_(vmax), @@ -1618,7 +1617,7 @@ DomainIntVar::DomainIntVar(Solver* const s, int64 vmin, int64 vmax, bound_watcher_(nullptr) {} DomainIntVar::DomainIntVar(Solver* const s, const std::vector& sorted_values, - const string& name) + const std::string& name) : IntVar(s, name), min_(kint64max), max_(kint64min), @@ -1881,9 +1880,9 @@ IntVarIterator* DomainIntVar::MakeDomainIterator(bool reversible) const { new DomainIntVarDomainIterator(this, reversible)); } -string DomainIntVar::DebugString() const { - string out; - const string& var_name = name(); +std::string DomainIntVar::DebugString() const { + std::string out; + const std::string& var_name = name(); if (!var_name.empty()) { out = var_name + "("; } else { @@ -1919,7 +1918,7 @@ class ConcreteBooleanVar : public BooleanVar { virtual Solver::DemonPriority priority() const { return Solver::VAR_PRIORITY; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Handler(%s)", var_->DebugString().c_str()); } @@ -1927,7 +1926,7 @@ class ConcreteBooleanVar : public BooleanVar { ConcreteBooleanVar* const var_; }; - ConcreteBooleanVar(Solver* const s, const string& name) + ConcreteBooleanVar(Solver* const s, const std::string& name) : BooleanVar(s, name), handler_(this) {} virtual ~ConcreteBooleanVar() {} @@ -1967,7 +1966,7 @@ class ConcreteBooleanVar : public BooleanVar { class IntConst : public IntVar { public: - IntConst(Solver* const s, int64 value, const string& name = "") + IntConst(Solver* const s, int64 value, const std::string& name = "") : IntVar(s, name), value_(value) {} virtual ~IntConst() {} @@ -2018,10 +2017,10 @@ class IntConst : public IntVar { } virtual int64 OldMin() const { return value_; } virtual int64 OldMax() const { return value_; } - virtual string DebugString() const { - string out; + virtual std::string DebugString() const { + std::string out; if (solver()->HasName(this)) { - const string& var_name = name(); + const std::string& var_name = name(); SStringPrintf(&out, "%s(%" GG_LL_FORMAT "d)", var_name.c_str(), value_); } else { SStringPrintf(&out, "IntConst(%" GG_LL_FORMAT "d)", value_); @@ -2055,7 +2054,7 @@ class IntConst : public IntVar { return solver()->MakeIntConst(value_ <= constant); } - virtual string name() const { + virtual std::string name() const { if (solver()->HasName(this)) { return PropagationBaseObject::name(); } else { @@ -2086,7 +2085,7 @@ class PlusCstVar : public IntVar { virtual int64 OldMax() const { return CapAdd(var_->OldMax(), cst_); } - virtual string DebugString() const { + virtual std::string DebugString() const { if (HasName()) { return StringPrintf("%s(%s + %" GG_LL_FORMAT "d)", name().c_str(), var_->DebugString().c_str(), cst_); @@ -2327,7 +2326,7 @@ class SubCstIntVar : public IntVar { } virtual int64 OldMin() const { return CapSub(cst_, var_->OldMax()); } virtual int64 OldMax() const { return CapSub(cst_, var_->OldMin()); } - virtual string DebugString() const; + virtual std::string DebugString() const; virtual int VarType() const { return CST_SUB_VAR; } virtual void Accept(ModelVisitor* const visitor) const { @@ -2398,7 +2397,7 @@ uint64 SubCstIntVar::Size() const { return var_->Size(); } bool SubCstIntVar::Contains(int64 v) const { return var_->Contains(cst_ - v); } -string SubCstIntVar::DebugString() const { +std::string SubCstIntVar::DebugString() const { if (cst_ == 1 && var_->VarType() == BOOLEAN_VAR) { return StringPrintf("Not(%s)", var_->DebugString().c_str()); } else { @@ -2448,7 +2447,7 @@ class OppIntVar : public IntVar { } virtual int64 OldMin() const { return CapOpp(var_->OldMax()); } virtual int64 OldMax() const { return CapOpp(var_->OldMin()); } - virtual string DebugString() const; + virtual std::string DebugString() const; virtual int VarType() const { return OPP_VAR; } virtual void Accept(ModelVisitor* const visitor) const { @@ -2514,7 +2513,7 @@ uint64 OppIntVar::Size() const { return var_->Size(); } bool OppIntVar::Contains(int64 v) const { return var_->Contains(-v); } -string OppIntVar::DebugString() const { +std::string OppIntVar::DebugString() const { return StringPrintf("-(%s)", var_->DebugString().c_str()); } @@ -2568,7 +2567,7 @@ class TimesCstIntVar : public IntVar { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s * %" GG_LL_FORMAT "d)", var_->DebugString().c_str(), cst_); } @@ -3000,12 +2999,12 @@ class PlusIntExpr : public BaseIntExpr { *ma = left_->Max() + right_->Max(); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s + %s)", left_->name().c_str(), right_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s + %s)", left_->DebugString().c_str(), right_->DebugString().c_str()); } @@ -3070,12 +3069,12 @@ class SafePlusIntExpr : public BaseIntExpr { virtual bool Bound() const { return (left_->Bound() && right_->Bound()); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s + %s)", left_->name().c_str(), right_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s + %s)", left_->DebugString().c_str(), right_->DebugString().c_str()); } @@ -3110,11 +3109,11 @@ class PlusIntCstExpr : public BaseIntExpr { virtual int64 Max() const { return CapAdd(expr_->Max(), value_); } virtual void SetMax(int64 m) { expr_->SetMax(CapSub(m, value_)); } virtual bool Bound() const { return (expr_->Bound()); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s + %" GG_LL_FORMAT "d)", expr_->name().c_str(), value_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s + %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), value_); } @@ -3199,12 +3198,12 @@ class SubIntExpr : public BaseIntExpr { virtual bool Bound() const { return (left_->Bound() && right_->Bound()); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s - %s)", left_->name().c_str(), right_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s - %s)", left_->DebugString().c_str(), right_->DebugString().c_str()); } @@ -3286,11 +3285,11 @@ class SubIntCstExpr : public BaseIntExpr { virtual int64 Max() const { return CapSub(value_, expr_->Min()); } virtual void SetMax(int64 m) { expr_->SetMin(CapSub(value_, m)); } virtual bool Bound() const { return (expr_->Bound()); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%" GG_LL_FORMAT "d - %s)", value_, expr_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%" GG_LL_FORMAT "d - %s)", value_, expr_->DebugString().c_str()); } @@ -3332,10 +3331,10 @@ class OppIntExpr : public BaseIntExpr { virtual int64 Max() const { return (-expr_->Min()); } virtual void SetMax(int64 m) { expr_->SetMin(-m); } virtual bool Bound() const { return (expr_->Bound()); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(-%s)", expr_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(-%s)", expr_->DebugString().c_str()); } virtual void WhenRange(Demon* d) { expr_->WhenRange(d); } @@ -3370,12 +3369,12 @@ class TimesIntCstExpr : public BaseIntExpr { virtual bool Bound() const { return (expr_->Bound()); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s * %" GG_LL_FORMAT "d)", expr_->name().c_str(), value_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s * %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), value_); } @@ -3651,7 +3650,7 @@ class TimesIntExpr : public BaseIntExpr { const int64 rmin = right_->Min(); const int64 rmax = right_->Max(); return std::min(std::min(CapProd(lmin, rmin), CapProd(lmax, rmax)), - std::min(CapProd(lmax, rmin), CapProd(lmin, rmax))); + std::min(CapProd(lmax, rmin), CapProd(lmin, rmax))); } virtual void SetMin(int64 m); virtual int64 Max() const { @@ -3660,15 +3659,15 @@ class TimesIntExpr : public BaseIntExpr { const int64 rmin = right_->Min(); const int64 rmax = right_->Max(); return std::max(std::max(CapProd(lmin, rmin), CapProd(lmax, rmax)), - std::max(CapProd(lmax, rmin), CapProd(lmin, rmax))); + std::max(CapProd(lmax, rmin), CapProd(lmin, rmax))); } virtual void SetMax(int64 m); virtual bool Bound() const; - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s * %s)", left_->name().c_str(), right_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s * %s)", left_->DebugString().c_str(), right_->DebugString().c_str()); } @@ -3723,11 +3722,11 @@ class TimesPosIntExpr : public BaseIntExpr { virtual int64 Max() const { return (left_->Max() * right_->Max()); } virtual void SetMax(int64 m); virtual bool Bound() const; - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s * %s)", left_->name().c_str(), right_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s * %s)", left_->DebugString().c_str(), right_->DebugString().c_str()); } @@ -3781,11 +3780,11 @@ class SafeTimesPosIntExpr : public BaseIntExpr { return (left_->Max() == 0 || right_->Max() == 0 || (left_->Bound() && right_->Bound())); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s * %s)", left_->name().c_str(), right_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s * %s)", left_->DebugString().c_str(), right_->DebugString().c_str()); } @@ -3825,11 +3824,11 @@ class TimesBooleanPosIntExpr : public BaseIntExpr { virtual void Range(int64* mi, int64* ma); virtual void SetRange(int64 mi, int64 ma); virtual bool Bound() const; - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s * %s)", boolvar_->name().c_str(), expr_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s * %s)", boolvar_->DebugString().c_str(), expr_->DebugString().c_str()); } @@ -3938,11 +3937,11 @@ class TimesBooleanIntExpr : public BaseIntExpr { virtual void Range(int64* mi, int64* ma); virtual void SetRange(int64 mi, int64 ma); virtual bool Bound() const; - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s * %s)", boolvar_->name().c_str(), expr_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s * %s)", boolvar_->DebugString().c_str(), expr_->DebugString().c_str()); } @@ -4104,12 +4103,12 @@ class DivPosIntCstExpr : public BaseIntExpr { } } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s div %" GG_LL_FORMAT "d)", expr_->name().c_str(), value_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s div %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), value_); } @@ -4180,11 +4179,11 @@ class DivPosIntExpr : public BaseIntExpr { } } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s div %s)", num_->name().c_str(), denom_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s div %s)", num_->DebugString().c_str(), denom_->DebugString().c_str()); } @@ -4240,12 +4239,12 @@ class DivPosPosIntExpr : public BaseIntExpr { } } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s div %s)", num_->name().c_str(), denom_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s div %s)", num_->DebugString().c_str(), denom_->DebugString().c_str()); } @@ -4411,11 +4410,11 @@ class DivIntExpr : public BaseIntExpr { } } - virtual string name() const { + virtual std::string name() const { return StringPrintf("(%s div %s)", num_->name().c_str(), denom_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s div %s)", num_->DebugString().c_str(), denom_->DebugString().c_str()); } @@ -4489,7 +4488,7 @@ class IntAbsConstraint : public CastConstraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntAbsConstraint(%s, %s)", sub_->DebugString().c_str(), target_var_->DebugString().c_str()); } @@ -4586,11 +4585,11 @@ class IntAbs : public BaseIntExpr { virtual void WhenRange(Demon* d) { expr_->WhenRange(d); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("IntAbs(%s)", expr_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntAbs(%s)", expr_->DebugString().c_str()); } @@ -4606,7 +4605,7 @@ class IntAbs : public BaseIntExpr { int64 max_value = 0; Range(&min_value, &max_value); Solver* const s = solver(); - const string name = StringPrintf("AbsVar(%s)", expr_->name().c_str()); + const std::string name = StringPrintf("AbsVar(%s)", expr_->name().c_str()); IntVar* const target = s->MakeIntVar(min_value, max_value, name); CastConstraint* const ct = s->RevAlloc(new IntAbsConstraint(s, expr_->Var(), target)); @@ -4673,10 +4672,10 @@ class IntSquare : public BaseIntExpr { } virtual bool Bound() const { return expr_->Bound(); } virtual void WhenRange(Demon* d) { expr_->WhenRange(d); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("IntSquare(%s)", expr_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntSquare(%s)", expr_->DebugString().c_str()); } @@ -4758,12 +4757,12 @@ class BasePower : public BaseIntExpr { virtual void WhenRange(Demon* d) { expr_->WhenRange(d); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("IntPower(%s, %" GG_LL_FORMAT "d)", expr_->name().c_str(), pow_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntPower(%s, %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), pow_); } @@ -4976,11 +4975,11 @@ class MinIntExpr : public BaseIntExpr { left_->SetMax(m); } } - virtual string name() const { + virtual std::string name() const { return StringPrintf("MinIntExpr(%s, %s)", left_->name().c_str(), right_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("MinIntExpr(%s, %s)", left_->DebugString().c_str(), right_->DebugString().c_str()); } @@ -5032,12 +5031,12 @@ class MinCstIntExpr : public BaseIntExpr { return (expr_->Bound() || expr_->Min() >= value_); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("MinCstIntExpr(%s, %" GG_LL_FORMAT "d)", expr_->name().c_str(), value_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("MinCstIntExpr(%s, %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), value_); } @@ -5085,12 +5084,12 @@ class MaxIntExpr : public BaseIntExpr { right_->SetMax(m); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("MaxIntExpr(%s, %s)", left_->name().c_str(), right_->name().c_str()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("MaxIntExpr(%s, %s)", left_->DebugString().c_str(), right_->DebugString().c_str()); } @@ -5143,12 +5142,12 @@ class MaxCstIntExpr : public BaseIntExpr { return (expr_->Bound() || expr_->Max() <= value_); } - virtual string name() const { + virtual std::string name() const { return StringPrintf("MaxCstIntExpr(%s, %" GG_LL_FORMAT "d)", expr_->name().c_str(), value_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("MaxCstIntExpr(%s, %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), value_); } @@ -5256,7 +5255,7 @@ class SimpleConvexPiecewiseExpr : public BaseIntExpr { } } - virtual string name() const { + virtual std::string name() const { return StringPrintf("ConvexPiecewiseExpr(%s, ec = %" GG_LL_FORMAT "d, ed = %" GG_LL_FORMAT "d, ld = %" GG_LL_FORMAT "d, lc = %" GG_LL_FORMAT "d)", @@ -5264,7 +5263,7 @@ class SimpleConvexPiecewiseExpr : public BaseIntExpr { late_date_, late_cost_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("ConvexPiecewiseExpr(%s, ec = %" GG_LL_FORMAT "d, ed = %" GG_LL_FORMAT "d, ld = %" GG_LL_FORMAT "d, lc = %" GG_LL_FORMAT "d)", @@ -5344,13 +5343,13 @@ class SemiContinuousExpr : public BaseIntExpr { } } - virtual string name() const { + virtual std::string name() const { return StringPrintf("SemiContinuous(%s, fixed_charge = %" GG_LL_FORMAT "d, step = %" GG_LL_FORMAT "d)", expr_->name().c_str(), fixed_charge_, step_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("SemiContinuous(%s, fixed_charge = %" GG_LL_FORMAT "d, step = %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), fixed_charge_, step_); @@ -5415,13 +5414,13 @@ class SemiContinuousStepOneExpr : public BaseIntExpr { } } - virtual string name() const { + virtual std::string name() const { return StringPrintf( "SemiContinuousStepOne(%s, fixed_charge = %" GG_LL_FORMAT "d)", expr_->name().c_str(), fixed_charge_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf( "SemiContinuousStepOne(%s, fixed_charge = %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), fixed_charge_); @@ -5483,13 +5482,13 @@ class SemiContinuousStepZeroExpr : public BaseIntExpr { } } - virtual string name() const { + virtual std::string name() const { return StringPrintf( "SemiContinuousStepZero(%s, fixed_charge = %" GG_LL_FORMAT "d)", expr_->name().c_str(), fixed_charge_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf( "SemiContinuousStepZero(%s, fixed_charge = %" GG_LL_FORMAT "d)", expr_->DebugString().c_str(), fixed_charge_); @@ -5534,7 +5533,7 @@ class LinkExprAndVar : public CastConstraint { target_var_->SetRange(l, u); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("cast(%s, %s)", expr_->DebugString().c_str(), target_var_->DebugString().c_str()); } @@ -5638,7 +5637,7 @@ class ExprWithEscapeValue : public BaseIntExpr { condition_->WhenBound(d); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("ConditionExpr(%s, %s, %" GG_LL_FORMAT "d)", condition_->DebugString().c_str(), expression_->DebugString().c_str(), unperformed_value_); @@ -5703,7 +5702,7 @@ class LinkExprAndDomainIntVar : public CastConstraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("cast(%s, %s)", expr_->DebugString().c_str(), target_var_->DebugString().c_str()); } @@ -5791,14 +5790,14 @@ void RestoreBoolValue(IntVar* const var) { // ----- API ----- -IntVar* Solver::MakeIntVar(int64 min, int64 max, const string& name) { +IntVar* Solver::MakeIntVar(int64 min, int64 max, const std::string& name) { if (min == max) { return RevAlloc(new IntConst(this, min, name)); } if (min == 0 && max == 1) { return RegisterIntVar(RevAlloc(new ConcreteBooleanVar(this, name))); } else if (max - min == 1) { - const string inner_name = "inner_" + name; + const std::string inner_name = "inner_" + name; return RegisterIntVar( MakeSum(RevAlloc(new ConcreteBooleanVar(this, inner_name)), min) ->VarWithName(name)); @@ -5811,7 +5810,7 @@ IntVar* Solver::MakeIntVar(int64 min, int64 max) { return MakeIntVar(min, max, ""); } -IntVar* Solver::MakeBoolVar(const string& name) { +IntVar* Solver::MakeBoolVar(const std::string& name) { return RegisterIntVar(RevAlloc(new ConcreteBooleanVar(this, name))); } @@ -5819,7 +5818,7 @@ IntVar* Solver::MakeBoolVar() { return RegisterIntVar(RevAlloc(new ConcreteBooleanVar(this, ""))); } -IntVar* Solver::MakeIntVar(const std::vector& values, const string& name) { +IntVar* Solver::MakeIntVar(const std::vector& values, const std::string& name) { return RegisterIntVar( RevAlloc(new DomainIntVar(this, SortedNoDuplicates(values), name))); } @@ -5828,7 +5827,7 @@ IntVar* Solver::MakeIntVar(const std::vector& values) { return MakeIntVar(values, ""); } -IntVar* Solver::MakeIntVar(const std::vector& values, const string& name) { +IntVar* Solver::MakeIntVar(const std::vector& values, const std::string& name) { return RegisterIntVar(RevAlloc( new DomainIntVar(this, SortedNoDuplicates(ToInt64Vector(values)), name))); } @@ -5837,7 +5836,7 @@ IntVar* Solver::MakeIntVar(const std::vector& values) { return MakeIntVar(values, ""); } -IntVar* Solver::MakeIntConst(int64 val, const string& name) { +IntVar* Solver::MakeIntConst(int64 val, const std::string& name) { // If IntConst is going to be named after its creation, // cp_share_int_consts should be set to false otherwise names can potentially // be overwritten. @@ -5853,7 +5852,7 @@ IntVar* Solver::MakeIntConst(int64 val) { return MakeIntConst(val, ""); } // ----- Int Var and associated methods ----- namespace { -string IndexedName(const string& prefix, int index, int max_index) { +std::string IndexedName(const std::string& prefix, int index, int max_index) { #if 0 #if defined(_MSC_VER) const int digits = max_index > 0 ? @@ -5870,7 +5869,7 @@ string IndexedName(const string& prefix, int index, int max_index) { } // namespace void Solver::MakeIntVarArray(int var_count, int64 vmin, int64 vmax, - const string& name, std::vector* vars) { + const std::string& name, std::vector* vars) { for (int i = 0; i < var_count; ++i) { vars->push_back(MakeIntVar(vmin, vmax, IndexedName(name, i, var_count))); } @@ -5884,7 +5883,7 @@ void Solver::MakeIntVarArray(int var_count, int64 vmin, int64 vmax, } IntVar** Solver::MakeIntVarArray(int var_count, int64 vmin, int64 vmax, - const string& name) { + const std::string& name) { IntVar** vars = new IntVar* [var_count]; for (int i = 0; i < var_count; ++i) { vars[i] = MakeIntVar(vmin, vmax, IndexedName(name, i, var_count)); @@ -5892,7 +5891,7 @@ IntVar** Solver::MakeIntVarArray(int var_count, int64 vmin, int64 vmax, return vars; } -void Solver::MakeBoolVarArray(int var_count, const string& name, +void Solver::MakeBoolVarArray(int var_count, const std::string& name, std::vector* vars) { for (int i = 0; i < var_count; ++i) { vars->push_back(MakeBoolVar(IndexedName(name, i, var_count))); @@ -5905,7 +5904,7 @@ void Solver::MakeBoolVarArray(int var_count, std::vector* vars) { } } -IntVar** Solver::MakeBoolVarArray(int var_count, const string& name) { +IntVar** Solver::MakeBoolVarArray(int var_count, const std::string& name) { IntVar** vars = new IntVar* [var_count]; for (int i = 0; i < var_count; ++i) { vars[i] = MakeBoolVar(IndexedName(name, i, var_count)); @@ -6352,7 +6351,7 @@ IntExpr* Solver::MakeAbs(IntExpr* const e) { int64 coefficient = 1; IntExpr* expr = nullptr; if (IsProduct(e, &expr, &coefficient)) { - result = MakeProd(MakeAbs(expr), std::abs(coefficient)); + result = MakeProd(MakeAbs(expr), abs(coefficient)); } else { result = RegisterIntExpr(RevAlloc(new IntAbs(this, e))); } diff --git a/src/constraint_solver/gcc.cc b/src/constraint_solver/gcc.cc index eb4520bbd8..a3cdc2ed01 100644 --- a/src/constraint_solver/gcc.cc +++ b/src/constraint_solver/gcc.cc @@ -44,7 +44,7 @@ struct Interval { int64 max_value; // start, end of Interval int64 min_rank; int64 max_rank; // rank of min & max in bounds_[] - string DebugString() const { + std::string DebugString() const { return StringPrintf("Interval(value = [%lld, %lld], rank = [%lld, %lld])", min_value, max_value, min_rank, max_rank); } @@ -148,7 +148,7 @@ class PartialSum { int64 last_value() const { return last_value_; } - string DebugString() const { + std::string DebugString() const { return StringPrintf( "PartialSum(offset=%lld, last_value = %lld, sum = %s, ds = %s)", offset_, last_value_, IntVectorToString(sum_, ", ").c_str(), @@ -330,7 +330,7 @@ class GccConstraint : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { // TODO(user): Improve me. return "GccConstraint"; } diff --git a/src/constraint_solver/graph_constraints.cc b/src/constraint_solver/graph_constraints.cc new file mode 100644 index 0000000000..a09f6375ae --- /dev/null +++ b/src/constraint_solver/graph_constraints.cc @@ -0,0 +1,1047 @@ +// Copyright 2010-2013 Google +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#include +#include "base/unique_ptr.h" +#include +#include + +#include "base/callback.h" +#include "base/integral_types.h" +#include "base/logging.h" +#include "constraint_solver/constraint_solver.h" +#include "constraint_solver/constraint_solveri.h" +#include "util/saturated_arithmetic.h" +#include "util/string_array.h" + +namespace operations_research { +// ---------- No cycle ---------- + +// This constraint ensures there are no cycles in the variable/value graph. +// "Sink" values are values outside the range of the array of variables; they +// are used to end paths. +// The constraint does essentially two things: +// - forbid partial paths from looping back to themselves +// - ensure each variable/node can be connected to a "sink". +// If assume_paths is true, the constraint assumes the 'next' variables +// represent paths (and performs a faster propagation); otherwise the +// constraint assumes the 'next' variables represent a forest. +// TODO(user): improve code when assume_paths is false (currently does an +// expensive n^2 loop). + +namespace { +class NoCycle : public Constraint { + public: + NoCycle(Solver* const s, const std::vector& nexts, + const std::vector& active, + ResultCallback1* sink_handler, bool owner, + bool assume_paths); + virtual ~NoCycle() { + if (owner_) { + delete sink_handler_; + } + } + virtual void Post(); + virtual void InitialPropagate(); + void NextChange(int index); + void ActiveBound(int index); + void NextBound(int index); + void ComputeSupports(); + void ComputeSupport(int index); + virtual std::string DebugString() const; + + void Accept(ModelVisitor* const visitor) const { + visitor->BeginVisitConstraint(ModelVisitor::kNoCycle, this); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kNextsArgument, + nexts_); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kActiveArgument, + active_); + visitor->VisitIntegerArgument("assume_paths", assume_paths_); + visitor->VisitInt64ToBoolExtension(sink_handler_, -size(), size()); + visitor->EndVisitConstraint(ModelVisitor::kNoCycle, this); + } + + private: + int64 size() const { return nexts_.size(); } + + const std::vector nexts_; + const std::vector active_; + std::vector iterators_; + std::vector starts_; + std::vector ends_; + bool all_nexts_bound_; + std::vector outbound_supports_; + std::vector support_leaves_; + std::vector unsupported_; + ResultCallback1* sink_handler_; + std::vector sinks_; + bool owner_; + bool assume_paths_; +}; + +NoCycle::NoCycle(Solver* const s, const std::vector& nexts, + const std::vector& active, + ResultCallback1* sink_handler, bool owner, + bool assume_paths) + : Constraint(s), + nexts_(nexts), + active_(active), + iterators_(nexts.size(), nullptr), + starts_(nexts.size()), + ends_(nexts.size()), + all_nexts_bound_(false), + outbound_supports_(nexts.size(), -1), + sink_handler_(sink_handler), + owner_(owner), + assume_paths_(assume_paths) { + support_leaves_.reserve(size()); + unsupported_.reserve(size()); + for (int i = 0; i < size(); ++i) { + starts_[i] = i; + ends_[i] = i; + iterators_[i] = nexts_[i]->MakeDomainIterator(true); + } + sink_handler_->CheckIsRepeatable(); +} + +void NoCycle::InitialPropagate() { + // Reduce next domains to sinks + range of nexts + for (int i = 0; i < size(); ++i) { + outbound_supports_[i] = -1; + IntVar* next = nexts_[i]; + for (int j = next->Min(); j < 0; ++j) { + if (!sink_handler_->Run(j)) { + next->RemoveValue(j); + } + } + for (int j = next->Max(); j >= size(); --j) { + if (!sink_handler_->Run(j)) { + next->RemoveValue(j); + } + } + } + solver()->SaveAndSetValue(&all_nexts_bound_, true); + for (int i = 0; i < size(); ++i) { + if (nexts_[i]->Bound()) { + NextBound(i); + } else { + solver()->SaveAndSetValue(&all_nexts_bound_, false); + } + } + ComputeSupports(); +} + +void NoCycle::Post() { + if (size() == 0) return; + for (int i = 0; i < size(); ++i) { + IntVar* next = nexts_[i]; + Demon* support_demon = MakeConstraintDemon1( + solver(), this, &NoCycle::NextChange, "NextChange", i); + next->WhenDomain(support_demon); + Demon* active_demon = MakeConstraintDemon1( + solver(), this, &NoCycle::ActiveBound, "ActiveBound", i); + active_[i]->WhenBound(active_demon); + } + // Setting up sinks + int64 min_min = nexts_[0]->Min(); + int64 max_max = nexts_[0]->Max(); + for (int i = 1; i < size(); ++i) { + const IntVar* next = nexts_[i]; + min_min = std::min(min_min, next->Min()); + max_max = std::max(max_max, next->Max()); + } + sinks_.clear(); + for (int i = min_min; i <= max_max; ++i) { + if (sink_handler_->Run(i)) { + sinks_.push_back(i); + } + } +} + +void NoCycle::NextChange(int index) { + IntVar* const next_var = nexts_[index]; + if (next_var->Bound()) { + NextBound(index); + } + if (!all_nexts_bound_) { + bool all_nexts_bound = true; + for (int i = 0; i < size(); ++i) { + if (!nexts_[i]->Bound()) { + all_nexts_bound = false; + break; + } + } + solver()->SaveAndSetValue(&all_nexts_bound_, all_nexts_bound); + } + if (all_nexts_bound_) { + return; + } + if (!next_var->Contains(outbound_supports_[index])) { + ComputeSupport(index); + } +} + +void NoCycle::ActiveBound(int index) { + if (nexts_[index]->Bound()) { + NextBound(index); + } +} + +void NoCycle::NextBound(int index) { + if (active_[index]->Min() == 0) return; + const int64 next = nexts_[index]->Value(); + const int64 chain_start = starts_[index]; + const int64 chain_end = !sink_handler_->Run(next) ? ends_[next] : next; + Solver* const s = solver(); + s->SaveAndSetValue(&ends_[chain_start], chain_end); + if (!sink_handler_->Run(chain_end)) { + s->SaveAndSetValue(&starts_[chain_end], chain_start); + nexts_[chain_end]->RemoveValue(chain_start); + if (!assume_paths_) { + for (int i = 0; i < size(); ++i) { + int64 current = i; + bool found = (current == chain_end); + // Counter to detect implicit cycles. + int count = 0; + while (!found && count < size() && !sink_handler_->Run(current) && + nexts_[current]->Bound()) { + current = nexts_[current]->Value(); + found = (current == chain_end); + ++count; + } + if (found) { + nexts_[chain_end]->RemoveValue(i); + } + } + } + } +} + +// Compute the support tree. For each variable, find a path connecting to a +// sink. Starts partial paths from the sinks down to all unconnected variables. +// If some variables remain unconnected, make the corresponding active_ +// variable false. +// Resulting tree is used as supports for next variables. +// TODO(user): Try to see if we can find an algorithm which is less than +// quadratic to do this (note that if the tree is flat we are already linear +// for a given number of sinks). +void NoCycle::ComputeSupports() { + // unsupported_ contains nodes not connected to sinks. + unsupported_.clear(); + // supported_leaves_ contains the current frontier containing nodes surely + // connected to sinks. + support_leaves_.clear(); + // Initial phase: find direct connections to sinks and initialize + // support_leaves_ and unsupported_ accordingly. + const int sink_size = sinks_.size(); + for (int i = 0; i < size(); ++i) { + const IntVar* next = nexts_[i]; + // If node is not active, no need to try to connect it to a sink. + if (active_[i]->Max() != 0) { + const int64 current_support = outbound_supports_[i]; + // Optimization: if this node was already supported by a sink, check if + // it's still a valid support. + if (current_support >= 0 && sink_handler_->Run(current_support) && + next->Contains(current_support)) { + support_leaves_.push_back(i); + } else { + // Optimization: iterate on sinks or next domain depending on which is + // smaller. + outbound_supports_[i] = -1; + if (sink_size < next->Size()) { + for (int j = 0; j < sink_size; ++j) { + if (next->Contains(sinks_[j])) { + outbound_supports_[i] = sinks_[j]; + support_leaves_.push_back(i); + break; + } + } + } else { + for (iterators_[i]->Init(); iterators_[i]->Ok(); + iterators_[i]->Next()) { + const int64 value = iterators_[i]->Value(); + if (sink_handler_->Run(value)) { + outbound_supports_[i] = value; + support_leaves_.push_back(i); + break; + } + } + } + } + if (outbound_supports_[i] == -1) { + unsupported_.push_back(i); + } + } + } + // No need to iterate on all nodes connected to sinks but just on the ones + // added in the last iteration; leaves_begin and leaves_end mark the block + // in support_leaves_ corresponding to such nodes. + size_t leaves_begin = 0; + size_t leaves_end = support_leaves_.size(); + while (!unsupported_.empty()) { + // Try to connected unsupported nodes to nodes connected to sinks. + for (int64 unsupported_index = 0; unsupported_index < unsupported_.size(); + ++unsupported_index) { + const int64 unsupported = unsupported_[unsupported_index]; + const IntVar* const next = nexts_[unsupported]; + for (int i = leaves_begin; i < leaves_end; ++i) { + if (next->Contains(support_leaves_[i])) { + outbound_supports_[unsupported] = support_leaves_[i]; + support_leaves_.push_back(unsupported); + // Remove current node from unsupported vector. + unsupported_[unsupported_index] = unsupported_.back(); + unsupported_.pop_back(); + --unsupported_index; + break; + } + // TODO(user): evaluate same trick as with the sinks by keeping a + // bitmap with supported nodes. + } + } + // No new leaves were added, we can bail out. + if (leaves_end == support_leaves_.size()) { + break; + } + leaves_begin = leaves_end; + leaves_end = support_leaves_.size(); + } + // Mark as inactive any unsupported node. + for (int64 unsupported_index = 0; unsupported_index < unsupported_.size(); + ++unsupported_index) { + active_[unsupported_[unsupported_index]]->SetMax(0); + } +} + +void NoCycle::ComputeSupport(int index) { + // Try to reconnect the node to the support tree by finding a next node + // which is both supported and was not a descendant of the node in the tree. + if (active_[index]->Max() != 0) { + for (iterators_[index]->Init(); iterators_[index]->Ok(); + iterators_[index]->Next()) { + const int64 next = iterators_[index]->Value(); + if (sink_handler_->Run(next)) { + outbound_supports_[index] = next; + return; + } + if (next != index && next < outbound_supports_.size()) { + int64 next_support = outbound_supports_[next]; + if (next_support >= 0) { + // Check if next is not already a descendant of index. + bool ancestor_found = false; + while (next_support < outbound_supports_.size() && + !sink_handler_->Run(next_support)) { + if (next_support == index) { + ancestor_found = true; + break; + } + next_support = outbound_supports_[next_support]; + } + if (!ancestor_found) { + outbound_supports_[index] = next; + return; + } + } + } + } + } + // No support was found, rebuild the support tree. + ComputeSupports(); +} + +std::string NoCycle::DebugString() const { + return StringPrintf("NoCycle(%s)", JoinDebugStringPtr(nexts_, ", ").c_str()); +} + +// ----- Circuit constraint ----- + +class Circuit : public Constraint { + public: + Circuit(Solver* const s, const std::vector& nexts, bool sub_circuit) + : Constraint(s), + nexts_(nexts), + size_(nexts_.size()), + starts_(size_, -1), + ends_(size_, -1), + lengths_(size_, 1), + domains_(size_), + outbound_support_(size_, -1), + inbound_support_(size_, -1), + temp_support_(size_, -1), + inbound_demon_(nullptr), + outbound_demon_(nullptr), + root_(-1), + num_inactives_(0), + sub_circuit_(sub_circuit) { + for (int i = 0; i < size_; ++i) { + domains_[i] = nexts_[i]->MakeDomainIterator(true); + } + } + + virtual ~Circuit() {} + + virtual void Post() { + inbound_demon_ = MakeDelayedConstraintDemon0( + solver(), this, &Circuit::CheckReachabilityToRoot, + "CheckReachabilityToRoot"); + outbound_demon_ = MakeDelayedConstraintDemon0( + solver(), this, &Circuit::CheckReachabilityFromRoot, + "CheckReachabilityFromRoot"); + for (int i = 0; i < size_; ++i) { + if (!nexts_[i]->Bound()) { + Demon* const bound_demon = MakeConstraintDemon1( + solver(), this, &Circuit::NextBound, "NextBound", i); + nexts_[i]->WhenBound(bound_demon); + Demon* const domain_demon = MakeConstraintDemon1( + solver(), this, &Circuit::NextDomain, "NextDomain", i); + nexts_[i]->WhenDomain(domain_demon); + } + } + solver()->AddConstraint(solver()->MakeAllDifferent(nexts_)); + } + + virtual void InitialPropagate() { + Solver* const s = solver(); + if (!sub_circuit_) { + root_.SetValue(solver(), 0); + } + for (int i = 0; i < size_; ++i) { + nexts_[i]->SetRange(0, size_ - 1); + if (!sub_circuit_) { + nexts_[i]->RemoveValue(i); + } + } + for (int i = 0; i < size_; ++i) { + starts_.SetValue(s, i, i); + ends_.SetValue(s, i, i); + lengths_.SetValue(s, i, 1); + } + for (int i = 0; i < size_; ++i) { + if (nexts_[i]->Bound()) { + NextBound(i); + } + } + CheckReachabilityFromRoot(); + CheckReachabilityToRoot(); + } + + virtual std::string DebugString() const { + return StringPrintf("%sCircuit(%s)", sub_circuit_ ? "Sub" : "", + JoinDebugStringPtr(nexts_, " ").c_str()); + } + + void Accept(ModelVisitor* const visitor) const { + visitor->BeginVisitConstraint(ModelVisitor::kCircuit, this); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kNextsArgument, + nexts_); + visitor->VisitIntegerArgument(ModelVisitor::kPartialArgument, sub_circuit_); + visitor->EndVisitConstraint(ModelVisitor::kCircuit, this); + } + + private: + bool Inactive(int index) const { + return nexts_[index]->Bound() && nexts_[index]->Min() == index; + } + + void NextBound(int index) { + Solver* const s = solver(); + const int destination = nexts_[index]->Value(); + const int root = root_.Value(); + if (destination != index) { + if (root == -1) { + root_.SetValue(s, index); + } + const int new_end = ends_.Value(destination); + const int new_start = starts_.Value(index); + starts_.SetValue(s, new_end, new_start); + ends_.SetValue(s, new_start, new_end); + lengths_.SetValue(s, new_start, lengths_.Value(new_start) + + lengths_.Value(destination)); + if (sub_circuit_) { + // You are creating the only path. Nexts can no longer loop upon itself. + nexts_[destination]->RemoveValue(destination); + } else { + if (lengths_.Value(new_start) < size_ - 1 - num_inactives_.Value()) { + nexts_[new_end]->RemoveValue(new_start); + } + } + } else { + num_inactives_.Incr(solver()); + } + // TODO(user): You might get more propagation if you maintain + // num_undecided_actives_; + // then + // if (num_undecided_actives_ == 0 && + // lengths_.Value(new_start) < size_ - 1 - num_inactives_.Value()) { + // nexts_[new_end]->RemoveValue(new_start); + // } + // for both complete == true and false. + } + + void NextDomain(int index) { + if (root_.Value() == -1) { + return; + } + if (!nexts_[index]->Contains(outbound_support_[index])) { + EnqueueDelayedDemon(outbound_demon_); + } + if (!nexts_[index]->Contains(inbound_support_[index])) { + EnqueueDelayedDemon(inbound_demon_); + } + } + + void TryInsertReached(int candidate, int64 after) { + if (!reached_[after]) { + reached_[after] = true; + insertion_queue_.push_back(after); + temp_support_[candidate] = after; + } + } + + void CheckReachabilityFromRoot() { + if (root_.Value() == -1) { // Root is not yet defined. Nothing to deduce. + return; + } + + // Assign temp_support_ to a dummy value. + temp_support_.assign(size_, -1); + // Clear the spanning tree. + int processed = 0; + reached_.assign(size_, false); + insertion_queue_.clear(); + // Add the root node. + const int root_value = root_.Value(); + reached_[root_value] = true; + insertion_queue_.push_back(root_value); + // Compute reachable nodes. + while (processed < insertion_queue_.size() && + insertion_queue_.size() + num_inactives_.Value() < size_) { + const int candidate = insertion_queue_[processed++]; + IntVar* const var = nexts_[candidate]; + switch (var->Size()) { + case 1: { + TryInsertReached(candidate, var->Min()); + break; + } + case 2: { + TryInsertReached(candidate, var->Min()); + TryInsertReached(candidate, var->Max()); + break; + } + default: { + IntVarIterator* const domain = domains_[candidate]; + for (domain->Init(); domain->Ok(); domain->Next()) { + TryInsertReached(candidate, domain->Value()); + } + } + } + } + // All non reachable nodes should point to themselves in the incomplete + // case + for (int i = 0; i < size_; ++i) { + if (!reached_[i]) { + nexts_[i]->SetValue(i); + } + } + // Update the outbound_support_ vector. + outbound_support_.swap(temp_support_); + } + + void CheckReachabilityToRoot() { + // TODO(user): Improve with prev_ data structure. + if (root_.Value() == -1) { + return; + } + + insertion_queue_.clear(); + insertion_queue_.push_back(root_.Value()); + temp_support_[root_.Value()] = nexts_[root_.Value()]->Min(); + int processed = 0; + to_visit_.clear(); + for (int i = 0; i < size_; ++i) { + if (!Inactive(i) && i != root_.Value()) { + to_visit_.push_back(i); + } + } + const int inactive = num_inactives_.Value(); + while (processed < insertion_queue_.size() && + insertion_queue_.size() + inactive < size_) { + const int inserted = insertion_queue_[processed++]; + std::vector rejected; + for (int index = 0; index < to_visit_.size(); ++index) { + const int candidate = to_visit_[index]; + if (nexts_[candidate]->Contains(inserted)) { + insertion_queue_.push_back(candidate); + temp_support_[candidate] = inserted; + } else { + rejected.push_back(candidate); + } + } + to_visit_.swap(rejected); + } + for (int i = 0; i < to_visit_.size(); ++i) { + const int node = to_visit_[i]; + nexts_[node]->SetValue(node); + } + temp_support_.swap(inbound_support_); + } + + const std::vector nexts_; + const int size_; + std::vector insertion_queue_; + std::vector to_visit_; + std::vector reached_; + RevArray starts_; + RevArray ends_; + RevArray lengths_; + std::vector domains_; + std::vector outbound_support_; + std::vector inbound_support_; + std::vector temp_support_; + Demon* inbound_demon_; + Demon* outbound_demon_; + Rev root_; + NumericalRev num_inactives_; + const bool sub_circuit_; +}; + +// ----- Misc ----- + +bool GreaterThan(int64 x, int64 y) { return y >= x; } +} // namespace + +Constraint* Solver::MakeNoCycle(const std::vector& nexts, + const std::vector& active, + ResultCallback1* sink_handler, + bool assume_paths) { + CHECK_EQ(nexts.size(), active.size()); + if (sink_handler == nullptr) { + sink_handler = + NewPermanentCallback(&GreaterThan, static_cast(nexts.size())); + } + return RevAlloc( + new NoCycle(this, nexts, active, sink_handler, true, assume_paths)); +} + +Constraint* Solver::MakeNoCycle(const std::vector& nexts, + const std::vector& active, + ResultCallback1* sink_handler) { + return MakeNoCycle(nexts, active, sink_handler, true); +} + +// TODO(user): Merge NoCycle and Circuit. +Constraint* Solver::MakeCircuit(const std::vector& nexts) { + return RevAlloc(new Circuit(this, nexts, false)); +} + +Constraint* Solver::MakeSubCircuit(const std::vector& nexts) { + return RevAlloc(new Circuit(this, nexts, true)); +} + +// ----- Path cumul constraints ----- + +namespace { +class BasePathCumul : public Constraint { + public: + BasePathCumul(Solver* const s, const std::vector& nexts, + const std::vector& active, const std::vector& cumuls); + virtual ~BasePathCumul() {} + virtual void Post(); + virtual void InitialPropagate(); + void ActiveBound(int index); + virtual void NextBound(int index) = 0; + virtual bool AcceptLink(int i, int j) const = 0; + void UpdateSupport(int index); + void CumulRange(int index); + virtual std::string DebugString() const; + + protected: + int64 size() const { return nexts_.size(); } + int cumul_size() const { return cumuls_.size(); } + + const std::vector nexts_; + const std::vector active_; + const std::vector cumuls_; + RevArray prevs_; + std::vector supports_; +}; + +BasePathCumul::BasePathCumul(Solver* const s, const std::vector& nexts, + const std::vector& active, + const std::vector& cumuls) + : Constraint(s), + nexts_(nexts), + active_(active), + cumuls_(cumuls), + prevs_(cumuls.size(), -1), + supports_(nexts.size()) { + CHECK_GE(cumul_size(), size()); + for (int i = 0; i < size(); ++i) { + supports_[i] = -1; + } +} + +void BasePathCumul::InitialPropagate() { + for (int i = 0; i < size(); ++i) { + if (nexts_[i]->Bound()) { + NextBound(i); + } else { + UpdateSupport(i); + } + } +} + +void BasePathCumul::Post() { + for (int i = 0; i < size(); ++i) { + IntVar* var = nexts_[i]; + Demon* d = MakeConstraintDemon1(solver(), this, &BasePathCumul::NextBound, + "NextBound", i); + var->WhenBound(d); + Demon* ds = MakeConstraintDemon1( + solver(), this, &BasePathCumul::UpdateSupport, "UpdateSupport", i); + var->WhenDomain(ds); + Demon* active_demon = MakeConstraintDemon1( + solver(), this, &BasePathCumul::ActiveBound, "ActiveBound", i); + active_[i]->WhenBound(active_demon); + } + for (int i = 0; i < cumul_size(); ++i) { + IntVar* cumul = cumuls_[i]; + Demon* d = MakeConstraintDemon1(solver(), this, &BasePathCumul::CumulRange, + "CumulRange", i); + cumul->WhenRange(d); + } +} + +void BasePathCumul::ActiveBound(int index) { + if (nexts_[index]->Bound()) { + NextBound(index); + } +} + +void BasePathCumul::CumulRange(int index) { + if (index < size()) { + if (nexts_[index]->Bound()) { + NextBound(index); + } else { + UpdateSupport(index); + } + } + if (prevs_[index] >= 0) { + NextBound(prevs_[index]); + } else { + for (int i = 0; i < size(); ++i) { + if (index == supports_[i]) { + UpdateSupport(i); + } + } + } +} + +void BasePathCumul::UpdateSupport(int index) { + int support = supports_[index]; + if (support < 0 || !AcceptLink(index, support)) { + IntVar* var = nexts_[index]; + for (int i = var->Min(); i <= var->Max(); ++i) { + if (i != support && AcceptLink(index, i)) { + supports_[index] = i; + return; + } + } + active_[index]->SetMax(0); + } +} + +std::string BasePathCumul::DebugString() const { + std::string out = "PathCumul("; + for (int i = 0; i < size(); ++i) { + out += nexts_[i]->DebugString() + " " + cumuls_[i]->DebugString(); + } + out += ")"; + return out; +} + +// cumuls[next[i]] = cumuls[i] + transits[i] + +class PathCumul : public BasePathCumul { + public: + PathCumul(Solver* const s, const std::vector& nexts, + const std::vector& active, const std::vector& cumuls, + const std::vector& transits) + : BasePathCumul(s, nexts, active, cumuls), transits_(transits) {} + virtual ~PathCumul() {} + virtual void Post(); + virtual void NextBound(int index); + virtual bool AcceptLink(int i, int j) const; + void TransitRange(int index); + + void Accept(ModelVisitor* const visitor) const { + visitor->BeginVisitConstraint(ModelVisitor::kPathCumul, this); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kNextsArgument, + nexts_); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kActiveArgument, + active_); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kCumulsArgument, + cumuls_); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kTransitsArgument, + transits_); + visitor->EndVisitConstraint(ModelVisitor::kPathCumul, this); + } + + private: + const std::vector transits_; +}; + +void PathCumul::Post() { + BasePathCumul::Post(); + for (int i = 0; i < size(); ++i) { + Demon* transit_demon = MakeConstraintDemon1( + solver(), this, &PathCumul::TransitRange, "TransitRange", i); + transits_[i]->WhenRange(transit_demon); + } +} + +void PathCumul::NextBound(int index) { + if (active_[index]->Min() == 0) return; + const int64 next = nexts_[index]->Value(); + IntVar* cumul = cumuls_[index]; + IntVar* cumul_next = cumuls_[next]; + IntVar* transit = transits_[index]; + cumul_next->SetMin(cumul->Min() + transit->Min()); + cumul_next->SetMax(CapAdd(cumul->Max(), transit->Max())); + cumul->SetMin(CapSub(cumul_next->Min(), transit->Max())); + cumul->SetMax(CapSub(cumul_next->Max(), transit->Min())); + transit->SetMin(CapSub(cumul_next->Min(), cumul->Max())); + transit->SetMax(CapSub(cumul_next->Max(), cumul->Min())); + if (prevs_[next] < 0) { + prevs_.SetValue(solver(), next, index); + } +} + +void PathCumul::TransitRange(int index) { + if (nexts_[index]->Bound()) { + NextBound(index); + } else { + UpdateSupport(index); + } + if (prevs_[index] >= 0) { + NextBound(prevs_[index]); + } else { + for (int i = 0; i < size(); ++i) { + if (index == supports_[i]) { + UpdateSupport(i); + } + } + } +} + +bool PathCumul::AcceptLink(int i, int j) const { + const IntVar* const cumul_i = cumuls_[i]; + const IntVar* const cumul_j = cumuls_[j]; + const IntVar* const transit_i = transits_[i]; + return transit_i->Min() <= CapSub(cumul_j->Max(), cumul_i->Min()) && + CapSub(cumul_j->Min(), cumul_i->Max()) <= transit_i->Max(); +} + +// cumuls[next[i]] = cumuls[i] + transit_evaluator(i, next[i]) + +class ResultCallback2PathCumul : public BasePathCumul { + public: + ResultCallback2PathCumul(Solver* const s, const std::vector& nexts, + const std::vector& active, + const std::vector& cumuls, + Solver::IndexEvaluator2* transit_evaluator); + virtual ~ResultCallback2PathCumul() {} + virtual void NextBound(int index); + virtual bool AcceptLink(int i, int j) const; + + void Accept(ModelVisitor* const visitor) const { + visitor->BeginVisitConstraint(ModelVisitor::kPathCumul, this); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kNextsArgument, + nexts_); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kActiveArgument, + active_); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kCumulsArgument, + cumuls_); + // TODO(user): Visit transit correctly. + // visitor->VisitIntegerVariableArrayArgument( + // ModelVisitor::kTransitsArgument, + // transit_evaluator); + visitor->EndVisitConstraint(ModelVisitor::kPathCumul, this); + } + + private: + std::unique_ptr transits_evaluator_; +}; + +ResultCallback2PathCumul::ResultCallback2PathCumul( + Solver* const s, const std::vector& nexts, + const std::vector& active, const std::vector& cumuls, + Solver::IndexEvaluator2* transit_evaluator) + : BasePathCumul(s, nexts, active, cumuls), + transits_evaluator_(transit_evaluator) { + transits_evaluator_->CheckIsRepeatable(); +} + +void ResultCallback2PathCumul::NextBound(int index) { + if (active_[index]->Min() == 0) return; + const int64 next = nexts_[index]->Value(); + IntVar* cumul = cumuls_[index]; + IntVar* cumul_next = cumuls_[next]; + const int64 transit = transits_evaluator_->Run(index, next); + cumul_next->SetMin(cumul->Min() + transit); + cumul_next->SetMax(CapAdd(cumul->Max(), transit)); + cumul->SetMin(CapSub(cumul_next->Min(), transit)); + cumul->SetMax(CapSub(cumul_next->Max(), transit)); + if (prevs_[next] < 0) { + prevs_.SetValue(solver(), next, index); + } +} + +bool ResultCallback2PathCumul::AcceptLink(int i, int j) const { + const IntVar* const cumul_i = cumuls_[i]; + const IntVar* const cumul_j = cumuls_[j]; + const int64 transit = transits_evaluator_->Run(i, j); + return transit <= CapSub(cumul_j->Max(), cumul_i->Min()) && + CapSub(cumul_j->Min(), cumul_i->Max()) <= transit; +} + +// ----- ResulatCallback2SlackPathCumul ----- + +class ResultCallback2SlackPathCumul : public BasePathCumul { + public: + ResultCallback2SlackPathCumul(Solver* const s, const std::vector& nexts, + const std::vector& active, + const std::vector& cumuls, + const std::vector& slacks, + Solver::IndexEvaluator2* transit_evaluator); + virtual ~ResultCallback2SlackPathCumul() {} + virtual void Post(); + virtual void NextBound(int index); + virtual bool AcceptLink(int i, int j) const; + void SlackRange(int index); + + void Accept(ModelVisitor* const visitor) const { + visitor->BeginVisitConstraint(ModelVisitor::kPathCumul, this); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kNextsArgument, + nexts_); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kActiveArgument, + active_); + visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kCumulsArgument, + cumuls_); + // TODO(user): Visit transit correctly. + // visitor->VisitIntegerVariableArrayArgument( + // ModelVisitor::kTransitsArgument, + // transit_evaluator); + visitor->EndVisitConstraint(ModelVisitor::kPathCumul, this); + } + + private: + const std::vector slacks_; + std::unique_ptr transits_evaluator_; +}; + +ResultCallback2SlackPathCumul::ResultCallback2SlackPathCumul( + Solver* const s, const std::vector& nexts, + const std::vector& active, const std::vector& cumuls, + const std::vector& slacks, Solver::IndexEvaluator2* transit_evaluator) + : BasePathCumul(s, nexts, active, cumuls), + slacks_(slacks), + transits_evaluator_(transit_evaluator) { + transits_evaluator_->CheckIsRepeatable(); +} + +void ResultCallback2SlackPathCumul::Post() { + BasePathCumul::Post(); + for (int i = 0; i < size(); ++i) { + Demon* slack_demon = MakeConstraintDemon1( + solver(), this, &ResultCallback2SlackPathCumul::SlackRange, + "SlackRange", i); + slacks_[i]->WhenRange(slack_demon); + } +} + +void ResultCallback2SlackPathCumul::SlackRange(int index) { + if (nexts_[index]->Bound()) { + NextBound(index); + } else { + UpdateSupport(index); + } + if (prevs_[index] >= 0) { + NextBound(prevs_[index]); + } else { + for (int i = 0; i < size(); ++i) { + if (index == supports_[i]) { + UpdateSupport(i); + } + } + } +} + +void ResultCallback2SlackPathCumul::NextBound(int index) { + if (active_[index]->Min() == 0) return; + const int64 next = nexts_[index]->Value(); + IntVar* const cumul = cumuls_[index]; + IntVar* const cumul_next = cumuls_[next]; + IntVar* const slack = slacks_[index]; + const int64 transit = transits_evaluator_->Run(index, next); + const int64 cumul_next_minus_transit_min = CapSub(cumul_next->Min(), transit); + const int64 cumul_next_minus_transit_max = CapSub(cumul_next->Max(), transit); + cumul_next->SetMin(CapAdd(CapAdd(cumul->Min(), transit), slack->Min())); + cumul_next->SetMax(CapAdd(CapAdd(cumul->Max(), transit), slack->Max())); + cumul->SetMin(CapSub(cumul_next_minus_transit_min, slack->Max())); + cumul->SetMax(CapSub(cumul_next_minus_transit_max, slack->Min())); + slack->SetMin(CapSub(cumul_next_minus_transit_min, cumul->Max())); + slack->SetMax(CapSub(cumul_next_minus_transit_max, cumul->Min())); + if (prevs_[next] < 0) { + prevs_.SetValue(solver(), next, index); + } +} + +bool ResultCallback2SlackPathCumul::AcceptLink(int i, int j) const { + const IntVar* const cumul_i = cumuls_[i]; + const IntVar* const cumul_j = cumuls_[j]; + const IntVar* const slack = slacks_[i]; + const int64 transit = transits_evaluator_->Run(i, j); + return CapAdd(transit, slack->Min()) <= + CapSub(cumul_j->Max(), cumul_i->Min()) && + CapSub(cumul_j->Min(), cumul_i->Max()) <= + CapAdd(slack->Max(), transit); +} +} // namespace + +Constraint* Solver::MakePathCumul(const std::vector& nexts, + const std::vector& active, + const std::vector& cumuls, + const std::vector& transits) { + CHECK_EQ(nexts.size(), active.size()); + CHECK_EQ(transits.size(), nexts.size()); + return RevAlloc(new PathCumul(this, nexts, active, cumuls, transits)); +} + +Constraint* Solver::MakePathCumul(const std::vector& nexts, + const std::vector& active, + const std::vector& cumuls, + Solver::IndexEvaluator2* transit_evaluator) { + CHECK_EQ(nexts.size(), active.size()); + return RevAlloc(new ResultCallback2PathCumul(this, nexts, active, cumuls, + transit_evaluator)); +} + +Constraint* Solver::MakePathCumul(const std::vector& nexts, + const std::vector& active, + const std::vector& cumuls, + const std::vector& slacks, + Solver::IndexEvaluator2* transit_evaluator) { + CHECK_EQ(nexts.size(), active.size()); + return RevAlloc(new ResultCallback2SlackPathCumul(this, nexts, active, cumuls, + slacks, transit_evaluator)); +} +} // namespace operations_research diff --git a/src/constraint_solver/hybrid.cc b/src/constraint_solver/hybrid.cc index c5ea4f5fe6..a0dfc0abac 100644 --- a/src/constraint_solver/hybrid.cc +++ b/src/constraint_solver/hybrid.cc @@ -105,7 +105,7 @@ class SimplexConnection : public SearchMonitor { } } - virtual string DebugString() const { return "SimplexConnection"; } + virtual std::string DebugString() const { return "SimplexConnection"; } private: std::unique_ptr > builder_; @@ -139,11 +139,11 @@ class Linearizer : public ModelParser { virtual ~Linearizer() {} // Begin/End visit element. - virtual void BeginVisitModel(const string& solver_name) { BeginVisit(true); } + virtual void BeginVisitModel(const std::string& solver_name) { BeginVisit(true); } - virtual void EndVisitModel(const string& solver_name) { EndVisit(); } + virtual void EndVisitModel(const std::string& solver_name) { EndVisit(); } - virtual void BeginVisitConstraint(const string& type_name, + virtual void BeginVisitConstraint(const std::string& type_name, const Constraint* const constraint) { if (!constraint->IsCastConstraint() && (IS_TYPE(type_name, kEquality) || IS_TYPE(type_name, kLessOrEqual) || @@ -155,7 +155,7 @@ class Linearizer : public ModelParser { } } - virtual void EndVisitConstraint(const string& type_name, + virtual void EndVisitConstraint(const std::string& type_name, const Constraint* const constraint) { if (!constraint->IsCastConstraint()) { if (IS_TYPE(type_name, kEquality)) { @@ -170,18 +170,18 @@ class Linearizer : public ModelParser { } EndVisit(); } - virtual void BeginVisitExtension(const string& type) { BeginVisit(true); } - virtual void EndVisitExtension(const string& type) { + virtual void BeginVisitExtension(const std::string& type) { BeginVisit(true); } + virtual void EndVisitExtension(const std::string& type) { if (IS_TYPE(type, kObjectiveExtension)) { VisitObjective(); } EndVisit(); } - virtual void BeginVisitIntegerExpression(const string& type_name, + virtual void BeginVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) { BeginVisit(true); } - virtual void EndVisitIntegerExpression(const string& type_name, + virtual void EndVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) { if (IS_TYPE(type_name, kSum)) { VisitSum(expr); @@ -200,7 +200,7 @@ class Linearizer : public ModelParser { } virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { RegisterExpression(variable); RegisterExpression(delegate); @@ -229,24 +229,24 @@ class Linearizer : public ModelParser { } virtual void VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate) {} // Visit integer arguments. - virtual void VisitIntegerArgument(const string& arg_name, int64 value) { + virtual void VisitIntegerArgument(const std::string& arg_name, int64 value) { if (DoVisit()) { Top()->SetIntegerArgument(arg_name, value); } } - virtual void VisitIntegerArrayArgument(const string& arg_name, + virtual void VisitIntegerArrayArgument(const std::string& arg_name, const std::vector& values) { if (DoVisit()) { Top()->SetIntegerArrayArgument(arg_name, values); } } - virtual void VisitIntegerMatrixArgument(const string& arg_name, + virtual void VisitIntegerMatrixArgument(const std::string& arg_name, const IntTupleSet& values) { if (DoVisit()) { Top()->SetIntegerMatrixArgument(arg_name, values); @@ -254,7 +254,7 @@ class Linearizer : public ModelParser { } // Visit integer expression argument. - virtual void VisitIntegerExpressionArgument(const string& arg_name, + virtual void VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument) { if (DoVisit()) { Top()->SetIntegerExpressionArgument(arg_name, argument); @@ -263,7 +263,7 @@ class Linearizer : public ModelParser { } virtual void VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { if (DoVisit()) { Top()->SetIntegerVariableArrayArgument(arg_name, arguments); for (int i = 0; i < arguments.size(); ++i) { @@ -273,13 +273,13 @@ class Linearizer : public ModelParser { } // Visit interval argument. - virtual void VisitIntervalArgument(const string& arg_name, + virtual void VisitIntervalArgument(const std::string& arg_name, IntervalVar* const argument) {} virtual void VisitIntervalArrayArgument( - const string& arg_name, const std::vector& argument) {} + const std::string& arg_name, const std::vector& argument) {} - virtual string DebugString() const { return "Linearizer"; } + virtual std::string DebugString() const { return "Linearizer"; } private: void BeginVisit(bool active) { @@ -590,7 +590,7 @@ class AutomaticLinearization : public SearchMonitor { } } - virtual string DebugString() const { return "AutomaticLinearization"; } + virtual std::string DebugString() const { return "AutomaticLinearization"; } private: MPSolver mp_solver_; diff --git a/src/constraint_solver/interval.cc b/src/constraint_solver/interval.cc index 72e75036f8..bd9d65b385 100644 --- a/src/constraint_solver/interval.cc +++ b/src/constraint_solver/interval.cc @@ -110,7 +110,7 @@ class MirrorIntervalVar : public IntervalVar { visitor->VisitIntervalVariable(this, ModelVisitor::kMirrorOperation, 0, t_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("MirrorInterval(%s)", t_->DebugString().c_str()); } @@ -320,7 +320,7 @@ class IntervalVarRelaxedMax : public AlwaysPerformedIntervalVarWrapper { underlying()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntervalVarRelaxedMax(%s)", underlying()->DebugString().c_str()); } @@ -370,7 +370,7 @@ class IntervalVarRelaxedMin : public AlwaysPerformedIntervalVarWrapper { underlying()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntervalVarRelaxedMin(%s)", underlying()->DebugString().c_str()); } @@ -388,7 +388,7 @@ class BaseIntervalVar : public IntervalVar { virtual Solver::DemonPriority priority() const { return Solver::VAR_PRIORITY; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Handler(%s)", var_->DebugString().c_str()); } @@ -406,7 +406,7 @@ class BaseIntervalVar : public IntervalVar { BaseIntervalVar* const var_; }; - BaseIntervalVar(Solver* const s, const string& name) + BaseIntervalVar(Solver* const s, const std::string& name) : IntervalVar(s, name), in_process_(false), handler_(this), @@ -420,7 +420,7 @@ class BaseIntervalVar : public IntervalVar { void ClearInProcess() { in_process_ = false; } - virtual string BaseName() const { return "IntervalVar"; } + virtual std::string BaseName() const { return "IntervalVar"; } bool InProcess() const { return in_process_; } @@ -611,8 +611,8 @@ class RangeVar : public IntExpr { return cast_var_; } - string DebugString() const { - string out = StringPrintf("%" GG_LL_FORMAT "d", min_.Value()); + std::string DebugString() const { + std::string out = StringPrintf("%" GG_LL_FORMAT "d", min_.Value()); if (!Bound()) { StringAppendF(&out, " .. %" GG_LL_FORMAT "d", max_.Value()); } @@ -725,7 +725,7 @@ class PerformedVar : public BooleanVar { } } - virtual string DebugString() const { + virtual std::string DebugString() const { switch (value_) { case 0: return "false"; @@ -747,9 +747,9 @@ class PerformedVar : public BooleanVar { class FixedDurationIntervalVar : public BaseIntervalVar { public: FixedDurationIntervalVar(Solver* const s, int64 start_min, int64 start_max, - int64 duration, bool optional, const string& name); + int64 duration, bool optional, const std::string& name); // Unperformed interval. - FixedDurationIntervalVar(Solver* const s, const string& name); + FixedDurationIntervalVar(Solver* const s, const std::string& name); virtual ~FixedDurationIntervalVar() {} virtual int64 StartMin() const; @@ -798,7 +798,7 @@ class FixedDurationIntervalVar : public BaseIntervalVar { } virtual void WhenPerformedBound(Demon* const d) { performed_.WhenBound(d); } virtual void Process(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual void Accept(ModelVisitor* const visitor) const { visitor->VisitIntervalVariable(this, "", 0, NullInterval()); @@ -830,14 +830,14 @@ class FixedDurationIntervalVar : public BaseIntervalVar { FixedDurationIntervalVar::FixedDurationIntervalVar( Solver* const s, int64 start_min, int64 start_max, int64 duration, - bool optional, const string& name) + bool optional, const std::string& name) : BaseIntervalVar(s, name), start_(s, this, start_min, start_max), duration_(duration), performed_(s, this, optional) {} FixedDurationIntervalVar::FixedDurationIntervalVar(Solver* const s, - const string& name) + const std::string& name) : BaseIntervalVar(s, name), start_(s, this, 0, 0), duration_(0), @@ -956,8 +956,8 @@ void FixedDurationIntervalVar::Push() { DCHECK(!in_process_); } -string FixedDurationIntervalVar::DebugString() const { - const string& var_name = name(); +std::string FixedDurationIntervalVar::DebugString() const { + const std::string& var_name = name(); if (performed_.Max() == 0) { if (!var_name.empty()) { return StringPrintf("%s(performed = false)", var_name.c_str()); @@ -965,7 +965,7 @@ string FixedDurationIntervalVar::DebugString() const { return "IntervalVar(performed = false)"; } } else { - string out; + std::string out; if (!var_name.empty()) { out = var_name + "(start = "; } else { @@ -984,9 +984,9 @@ class FixedDurationPerformedIntervalVar : public BaseIntervalVar { public: FixedDurationPerformedIntervalVar(Solver* const s, int64 start_min, int64 start_max, int64 duration, - const string& name); + const std::string& name); // Unperformed interval. - FixedDurationPerformedIntervalVar(Solver* const s, const string& name); + FixedDurationPerformedIntervalVar(Solver* const s, const std::string& name); virtual ~FixedDurationPerformedIntervalVar() {} virtual int64 StartMin() const; @@ -1025,7 +1025,7 @@ class FixedDurationPerformedIntervalVar : public BaseIntervalVar { virtual bool WasPerformedBound() const { return true; } virtual void WhenPerformedBound(Demon* const d) {} virtual void Process(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual void Accept(ModelVisitor* const visitor) const { visitor->VisitIntervalVariable(this, "", 0, NullInterval()); @@ -1049,13 +1049,13 @@ class FixedDurationPerformedIntervalVar : public BaseIntervalVar { FixedDurationPerformedIntervalVar::FixedDurationPerformedIntervalVar( Solver* const s, int64 start_min, int64 start_max, int64 duration, - const string& name) + const std::string& name) : BaseIntervalVar(s, name), start_(s, this, start_min, start_max), duration_(duration) {} FixedDurationPerformedIntervalVar::FixedDurationPerformedIntervalVar( - Solver* const s, const string& name) + Solver* const s, const std::string& name) : BaseIntervalVar(s, name), start_(s, this, 0, 0), duration_(0) {} void FixedDurationPerformedIntervalVar::Process() { @@ -1151,9 +1151,9 @@ void FixedDurationPerformedIntervalVar::Push() { DCHECK(!in_process_); } -string FixedDurationPerformedIntervalVar::DebugString() const { - string out; - const string& var_name = name(); +std::string FixedDurationPerformedIntervalVar::DebugString() const { + std::string out; + const std::string& var_name = name(); if (!var_name.empty()) { out = var_name + "(start = "; } else { @@ -1169,7 +1169,7 @@ string FixedDurationPerformedIntervalVar::DebugString() const { class StartVarPerformedIntervalVar : public IntervalVar { public: StartVarPerformedIntervalVar(Solver* const s, IntVar* const start_var, - int64 duration, const string& name); + int64 duration, const std::string& name); virtual ~StartVarPerformedIntervalVar() {} virtual int64 StartMin() const; @@ -1207,7 +1207,7 @@ class StartVarPerformedIntervalVar : public IntervalVar { virtual void SetPerformed(bool val); virtual bool WasPerformedBound() const { return true; } virtual void WhenPerformedBound(Demon* const d) {} - virtual string DebugString() const; + virtual std::string DebugString() const; virtual IntExpr* StartExpr() { return start_var_; } virtual IntExpr* DurationExpr() { return solver()->MakeIntConst(duration_); } @@ -1236,7 +1236,7 @@ class StartVarPerformedIntervalVar : public IntervalVar { StartVarPerformedIntervalVar::StartVarPerformedIntervalVar(Solver* const s, IntVar* const var, int64 duration, - const string& name) + const std::string& name) : IntervalVar(s, name), start_var_(var), duration_(duration) {} int64 StartVarPerformedIntervalVar::StartMin() const { @@ -1310,9 +1310,9 @@ void StartVarPerformedIntervalVar::SetPerformed(bool val) { } } -string StartVarPerformedIntervalVar::DebugString() const { - string out; - const string& var_name = name(); +std::string StartVarPerformedIntervalVar::DebugString() const { + std::string out; + const std::string& var_name = name(); if (!var_name.empty()) { out = var_name + "(start = "; } else { @@ -1333,7 +1333,7 @@ string StartVarPerformedIntervalVar::DebugString() const { class FixedInterval : public IntervalVar { public: FixedInterval(Solver* const s, int64 start, int64 duration, - const string& name); + const std::string& name); virtual ~FixedInterval() {} virtual int64 StartMin() const { return start_; } @@ -1371,7 +1371,7 @@ class FixedInterval : public IntervalVar { virtual void SetPerformed(bool val); virtual bool WasPerformedBound() const { return true; } virtual void WhenPerformedBound(Demon* const d) {} - virtual string DebugString() const; + virtual std::string DebugString() const; virtual void Accept(ModelVisitor* const visitor) const { visitor->VisitIntervalVariable(this, "", 0, NullInterval()); @@ -1397,7 +1397,7 @@ class FixedInterval : public IntervalVar { }; FixedInterval::FixedInterval(Solver* const s, int64 start, int64 duration, - const string& name) + const std::string& name) : IntervalVar(s, name), start_(start), duration_(duration) {} void FixedInterval::SetStartMin(int64 m) { @@ -1460,9 +1460,9 @@ void FixedInterval::SetPerformed(bool val) { } } -string FixedInterval::DebugString() const { - string out; - const string& var_name = name(); +std::string FixedInterval::DebugString() const { + std::string out; + const std::string& var_name = name(); if (!var_name.empty()) { out = var_name + "(start = "; } else { @@ -1481,7 +1481,7 @@ class VariableDurationIntervalVar : public BaseIntervalVar { VariableDurationIntervalVar(Solver* const s, int64 start_min, int64 start_max, int64 duration_min, int64 duration_max, int64 end_min, int64 end_max, bool optional, - const string& name) + const std::string& name) : BaseIntervalVar(s, name), start_(s, this, std::max(start_min, end_min - duration_max), std::min(start_max, end_max - duration_min)), @@ -1688,8 +1688,8 @@ class VariableDurationIntervalVar : public BaseIntervalVar { performed_.UpdatePreviousValueAndApplyPostponedValue(); } - virtual string DebugString() const { - const string& var_name = name(); + virtual std::string DebugString() const { + const std::string& var_name = name(); if (performed_.Max() != 1) { if (!var_name.empty()) { return StringPrintf("%s(performed = false)", var_name.c_str()); @@ -1697,7 +1697,7 @@ class VariableDurationIntervalVar : public BaseIntervalVar { return "IntervalVar(performed = false)"; } } else { - string out; + std::string out; if (!var_name.empty()) { out = var_name + "(start = "; } else { @@ -1759,7 +1759,7 @@ class VariableDurationIntervalVar : public BaseIntervalVar { class FixedDurationSyncedIntervalVar : public IntervalVar { public: FixedDurationSyncedIntervalVar(IntervalVar* const t, int64 duration, - int64 offset, const string& name) + int64 offset, const std::string& name) : IntervalVar(t->solver(), name), t_(t), duration_(duration), @@ -1865,7 +1865,7 @@ class FixedDurationIntervalVarStartSyncedOnStart visitor->VisitIntervalVariable( this, ModelVisitor::kStartSyncOnStartOperation, offset_, t_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf( "IntervalStartSyncedOnStart(%s, duration = %" GG_LL_FORMAT "d, offset = %" GG_LL_FORMAT "d)", @@ -1923,7 +1923,7 @@ class FixedDurationIntervalVarStartSyncedOnEnd visitor->VisitIntervalVariable(this, ModelVisitor::kStartSyncOnEndOperation, offset_, t_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("IntervalStartSyncedOnEnd(%s, duration = %" GG_LL_FORMAT "d, offset = %" GG_LL_FORMAT "d)", t_->DebugString().c_str(), duration_, offset_); @@ -1963,14 +1963,14 @@ void IntervalVar::WhenAnything(Demon* const d) { } IntervalVar* Solver::MakeFixedInterval(int64 start, int64 duration, - const string& name) { + const std::string& name) { return RevAlloc(new FixedInterval(this, start, duration, name)); } IntervalVar* Solver::MakeFixedDurationIntervalVar(int64 start_min, int64 start_max, int64 duration, bool optional, - const string& name) { + const std::string& name) { if (start_min == start_max && !optional) { return MakeFixedInterval(start_min, duration, name); } else if (!optional) { @@ -1984,13 +1984,13 @@ IntervalVar* Solver::MakeFixedDurationIntervalVar(int64 start_min, void Solver::MakeFixedDurationIntervalVarArray(int count, int64 start_min, int64 start_max, int64 duration, bool optional, - const string& name, + const std::string& name, std::vector* array) { CHECK_GT(count, 0); CHECK(array != nullptr); array->clear(); for (int i = 0; i < count; ++i) { - const string var_name = StringPrintf("%s%i", name.c_str(), i); + const std::string var_name = StringPrintf("%s%i", name.c_str(), i); array->push_back(MakeFixedDurationIntervalVar( start_min, start_max, duration, optional, var_name)); } @@ -1998,7 +1998,7 @@ void Solver::MakeFixedDurationIntervalVarArray(int count, int64 start_min, IntervalVar* Solver::MakeFixedDurationIntervalVar(IntVar* const start_variable, int64 duration, - const string& name) { + const std::string& name) { CHECK(start_variable != nullptr); CHECK_GE(duration, 0); return RegisterIntervalVar(RevAlloc( @@ -2006,12 +2006,12 @@ IntervalVar* Solver::MakeFixedDurationIntervalVar(IntVar* const start_variable, } void Solver::MakeFixedDurationIntervalVarArray( - const std::vector& start_variables, int64 duration, const string& name, + const std::vector& start_variables, int64 duration, const std::string& name, std::vector* array) { CHECK(array != nullptr); array->clear(); for (int i = 0; i < start_variables.size(); ++i) { - const string var_name = StringPrintf("%s%i", name.c_str(), i); + const std::string var_name = StringPrintf("%s%i", name.c_str(), i); array->push_back( MakeFixedDurationIntervalVar(start_variables[i], duration, var_name)); } @@ -2021,12 +2021,12 @@ void Solver::MakeFixedDurationIntervalVarArray( // the corresponding start variables. void Solver::MakeFixedDurationIntervalVarArray( const std::vector& start_variables, const std::vector& durations, - const string& name, std::vector* array) { + const std::string& name, std::vector* array) { CHECK(array != nullptr); CHECK_EQ(start_variables.size(), durations.size()); array->clear(); for (int i = 0; i < start_variables.size(); ++i) { - const string var_name = StringPrintf("%s%i", name.c_str(), i); + const std::string var_name = StringPrintf("%s%i", name.c_str(), i); array->push_back(MakeFixedDurationIntervalVar(start_variables[i], durations[i], var_name)); } @@ -2034,12 +2034,12 @@ void Solver::MakeFixedDurationIntervalVarArray( void Solver::MakeFixedDurationIntervalVarArray( const std::vector& start_variables, const std::vector& durations, - const string& name, std::vector* array) { + const std::string& name, std::vector* array) { CHECK(array != nullptr); CHECK_EQ(start_variables.size(), durations.size()); array->clear(); for (int i = 0; i < start_variables.size(); ++i) { - const string var_name = StringPrintf("%s%i", name.c_str(), i); + const std::string var_name = StringPrintf("%s%i", name.c_str(), i); array->push_back(MakeFixedDurationIntervalVar(start_variables[i], durations[i], var_name)); } @@ -2050,7 +2050,7 @@ void Solver::MakeFixedDurationIntervalVarArray( IntervalVar* Solver::MakeIntervalVar(int64 start_min, int64 start_max, int64 duration_min, int64 duration_max, int64 end_min, int64 end_max, - bool optional, const string& name) { + bool optional, const std::string& name) { return RegisterIntervalVar(RevAlloc(new VariableDurationIntervalVar( this, start_min, start_max, duration_min, duration_max, end_min, end_max, optional, name))); @@ -2059,13 +2059,13 @@ IntervalVar* Solver::MakeIntervalVar(int64 start_min, int64 start_max, void Solver::MakeIntervalVarArray(int count, int64 start_min, int64 start_max, int64 duration_min, int64 duration_max, int64 end_min, int64 end_max, bool optional, - const string& name, + const std::string& name, std::vector* const array) { CHECK_GT(count, 0); CHECK(array != nullptr); array->clear(); for (int i = 0; i < count; ++i) { - const string var_name = StringPrintf("%s%i", name.c_str(), i); + const std::string var_name = StringPrintf("%s%i", name.c_str(), i); array->push_back(MakeIntervalVar(start_min, start_max, duration_min, duration_max, end_min, end_max, optional, var_name)); diff --git a/src/constraint_solver/io.cc b/src/constraint_solver/io.cc index b031df3019..dd29eabd86 100644 --- a/src/constraint_solver/io.cc +++ b/src/constraint_solver/io.cc @@ -11,8 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include #include +#include #include "base/hash.h" #include "base/unique_ptr.h" #include @@ -92,7 +92,7 @@ class CPModelLoader { std::vector* to_fill); template - bool ScanArguments(const string& type, const P& proto, A* to_fill) { + bool ScanArguments(const std::string& type, const P& proto, A* to_fill) { const int index = tags_.Index(type); for (int i = 0; i < proto.arguments_size(); ++i) { if (ScanOneArgument(index, proto.arguments(i), to_fill)) { @@ -102,9 +102,9 @@ class CPModelLoader { return false; } - int TagIndex(const string& tag) const { return tags_.Index(tag); } + int TagIndex(const std::string& tag) const { return tags_.Index(tag); } - void AddTag(const string& tag) { tags_.Add(tag); } + void AddTag(const std::string& tag) { tags_.Add(tag); } // TODO(user): Use. void SetSequenceVariable(int index, SequenceVar* const var) {} @@ -114,7 +114,7 @@ class CPModelLoader { std::vector expressions_; std::vector intervals_; std::vector sequences_; - VectorMap tags_; + VectorMap tags_; }; Constraint* SetIsEqual(IntVar* const var, const std::vector& values, @@ -136,10 +136,10 @@ class FirstPassVisitor : public ModelVisitor { FirstPassVisitor() {} // Needed for Visual Studio. virtual ~FirstPassVisitor() {} - virtual string DebugString() const { return "FirstPassVisitor"; } + virtual std::string DebugString() const { return "FirstPassVisitor"; } // Begin/End visit element. - virtual void BeginVisitModel(const string& solver_name) { + virtual void BeginVisitModel(const std::string& solver_name) { // Reset statistics. expression_map_.clear(); delegate_map_.clear(); @@ -149,12 +149,12 @@ class FirstPassVisitor : public ModelVisitor { sequence_list_.clear(); } - virtual void EndVisitConstraint(const string& type_name, + virtual void EndVisitConstraint(const std::string& type_name, const Constraint* const constraint) { Register(constraint); } - virtual void EndVisitIntegerExpression(const string& type_name, + virtual void EndVisitIntegerExpression(const std::string& type_name, const IntExpr* const expression) { Register(expression); } @@ -169,7 +169,7 @@ class FirstPassVisitor : public ModelVisitor { } virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { delegate->Accept(this); delegate_map_[variable] = delegate; @@ -177,7 +177,7 @@ class FirstPassVisitor : public ModelVisitor { } virtual void VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate) { if (delegate != nullptr) { delegate->Accept(this); @@ -193,39 +193,39 @@ class FirstPassVisitor : public ModelVisitor { } // Visit integer expression argument. - virtual void VisitIntegerExpressionArgument(const string& arg_name, + virtual void VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument) { VisitSubArgument(argument); } virtual void VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { VisitSubArgument(arguments[i]); } } // Visit interval argument. - virtual void VisitIntervalArgument(const string& arg_name, + virtual void VisitIntervalArgument(const std::string& arg_name, IntervalVar* const argument) { VisitSubArgument(argument); } virtual void VisitIntervalArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { VisitSubArgument(arguments[i]); } } // Visit sequence argument. - virtual void VisitSequenceArgument(const string& arg_name, + virtual void VisitSequenceArgument(const std::string& arg_name, SequenceVar* const argument) { VisitSubArgument(argument); } virtual void VisitSequenceArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { VisitSubArgument(arguments[i]); } @@ -307,7 +307,7 @@ class FirstPassVisitor : public ModelVisitor { } } - const string filename_; + const std::string filename_; hash_map expression_map_; hash_map interval_map_; hash_map sequence_map_; @@ -323,15 +323,15 @@ class FirstPassVisitor : public ModelVisitor { class ArgumentHolder { public: template - void ExportToProto(VectorMap* const tags, P* const proto) const { - for (ConstIter> it(integer_argument_); !it.at_end(); + void ExportToProto(VectorMap* const tags, P* const proto) const { + for (ConstIter> it(integer_argument_); !it.at_end(); ++it) { CPArgumentProto* const arg_proto = proto->add_arguments(); arg_proto->set_argument_index(tags->Add(it->first)); arg_proto->set_integer_value(it->second); } - for (ConstIter>> it(integer_array_argument_); + for (ConstIter>> it(integer_array_argument_); !it.at_end(); ++it) { CPArgumentProto* const arg_proto = proto->add_arguments(); arg_proto->set_argument_index(tags->Add(it->first)); @@ -340,7 +340,7 @@ class ArgumentHolder { } } - for (ConstIter>>> it( + for (ConstIter>>> it( integer_matrix_argument_); !it.at_end(); ++it) { CPArgumentProto* const arg_proto = proto->add_arguments(); @@ -357,14 +357,14 @@ class ArgumentHolder { } } - for (ConstIter> it(integer_expression_argument_); + for (ConstIter> it(integer_expression_argument_); !it.at_end(); ++it) { CPArgumentProto* const arg_proto = proto->add_arguments(); arg_proto->set_argument_index(tags->Add(it->first)); arg_proto->set_integer_expression_index(it->second); } - for (ConstIter>> it( + for (ConstIter>> it( integer_variable_array_argument_); !it.at_end(); ++it) { CPArgumentProto* const arg_proto = proto->add_arguments(); @@ -374,14 +374,14 @@ class ArgumentHolder { } } - for (ConstIter> it(interval_argument_); !it.at_end(); + for (ConstIter> it(interval_argument_); !it.at_end(); ++it) { CPArgumentProto* const arg_proto = proto->add_arguments(); arg_proto->set_argument_index(tags->Add(it->first)); arg_proto->set_interval_index(it->second); } - for (ConstIter>> it(interval_array_argument_); + for (ConstIter>> it(interval_array_argument_); !it.at_end(); ++it) { CPArgumentProto* const arg_proto = proto->add_arguments(); arg_proto->set_argument_index(tags->Add(it->first)); @@ -390,14 +390,14 @@ class ArgumentHolder { } } - for (ConstIter> it(sequence_argument_); !it.at_end(); + for (ConstIter> it(sequence_argument_); !it.at_end(); ++it) { CPArgumentProto* const arg_proto = proto->add_arguments(); arg_proto->set_argument_index(tags->Add(it->first)); arg_proto->set_sequence_index(it->second); } - for (ConstIter>> it(sequence_array_argument_); + for (ConstIter>> it(sequence_array_argument_); !it.at_end(); ++it) { CPArgumentProto* const arg_proto = proto->add_arguments(); arg_proto->set_argument_index(tags->Add(it->first)); @@ -407,24 +407,24 @@ class ArgumentHolder { } } - const string& type_name() const { return type_name_; } + const std::string& type_name() const { return type_name_; } - void set_type_name(const string& type_name) { type_name_ = type_name; } + void set_type_name(const std::string& type_name) { type_name_ = type_name; } - void set_integer_argument(const string& arg_name, int64 value) { + void set_integer_argument(const std::string& arg_name, int64 value) { integer_argument_[arg_name] = value; } - void set_integer_array_argument(const string& arg_name, + void set_integer_array_argument(const std::string& arg_name, const std::vector& values) { integer_array_argument_[arg_name] = values; } - void set_integer_matrix_argument(const string& arg_name, + void set_integer_matrix_argument(const std::string& arg_name, const IntTupleSet& values) { const int rows = values.NumTuples(); const int columns = values.Arity(); - std::pair> matrix = make_pair(columns, std::vector()); + std::pair> matrix = std::make_pair(columns, std::vector()); integer_matrix_argument_[arg_name] = matrix; std::vector* const vals = &integer_matrix_argument_[arg_name].second; for (int i = 0; i < rows; ++i) { @@ -434,62 +434,62 @@ class ArgumentHolder { } } - void set_integer_expression_argument(const string& arg_name, int index) { + void set_integer_expression_argument(const std::string& arg_name, int index) { integer_expression_argument_[arg_name] = index; } - void set_integer_variable_array_argument(const string& arg_name, + void set_integer_variable_array_argument(const std::string& arg_name, const int* const indices, int size) { for (int i = 0; i < size; ++i) { integer_variable_array_argument_[arg_name].push_back(indices[i]); } } - void set_interval_argument(const string& arg_name, int index) { + void set_interval_argument(const std::string& arg_name, int index) { interval_argument_[arg_name] = index; } - void set_interval_array_argument(const string& arg_name, + void set_interval_array_argument(const std::string& arg_name, const int* const indices, int size) { for (int i = 0; i < size; ++i) { interval_array_argument_[arg_name].push_back(indices[i]); } } - void set_sequence_argument(const string& arg_name, int index) { + void set_sequence_argument(const std::string& arg_name, int index) { sequence_argument_[arg_name] = index; } - void set_sequence_array_argument(const string& arg_name, + void set_sequence_array_argument(const std::string& arg_name, const int* const indices, int size) { for (int i = 0; i < size; ++i) { sequence_array_argument_[arg_name].push_back(indices[i]); } } - int64 FindIntegerArgumentWithDefault(const string& arg_name, int64 def) { + int64 FindIntegerArgumentWithDefault(const std::string& arg_name, int64 def) { return FindWithDefault(integer_argument_, arg_name, def); } - int64 FindIntegerArgumentOrDie(const string& arg_name) { + int64 FindIntegerArgumentOrDie(const std::string& arg_name) { return FindOrDie(integer_argument_, arg_name); } - int64 FindIntegerExpressionArgumentOrDie(const string& arg_name) { + int64 FindIntegerExpressionArgumentOrDie(const std::string& arg_name) { return FindOrDie(integer_expression_argument_, arg_name); } private: - string type_name_; - hash_map integer_expression_argument_; - hash_map integer_argument_; - hash_map interval_argument_; - hash_map sequence_argument_; - hash_map> integer_array_argument_; - hash_map>> integer_matrix_argument_; - hash_map> integer_variable_array_argument_; - hash_map> interval_array_argument_; - hash_map> sequence_array_argument_; + std::string type_name_; + hash_map integer_expression_argument_; + hash_map integer_argument_; + hash_map interval_argument_; + hash_map sequence_argument_; + hash_map> integer_array_argument_; + hash_map>> integer_matrix_argument_; + hash_map> integer_variable_array_argument_; + hash_map> interval_array_argument_; + hash_map> sequence_array_argument_; }; // ----- Second Pass Visitor ----- @@ -515,9 +515,9 @@ class SecondPassVisitor : public ModelVisitor { virtual ~SecondPassVisitor() {} - virtual string DebugString() const { return "SecondPassVisitor"; } + virtual std::string DebugString() const { return "SecondPassVisitor"; } - virtual void BeginVisitModel(const string& model_name) { + virtual void BeginVisitModel(const std::string& model_name) { model_proto_->set_model(model_name); model_proto_->set_version(kModelVersion); PushArgumentHolder(); @@ -537,7 +537,7 @@ class SecondPassVisitor : public ModelVisitor { } } - virtual void EndVisitModel(const string& model_name) { + virtual void EndVisitModel(const std::string& model_name) { for (ConstIter> it(extensions_); !it.at_end(); ++it) { WriteModelExtension(*it); @@ -549,12 +549,12 @@ class SecondPassVisitor : public ModelVisitor { } } - virtual void BeginVisitConstraint(const string& type_name, + virtual void BeginVisitConstraint(const std::string& type_name, const Constraint* const constraint) { PushArgumentHolder(); } - virtual void EndVisitConstraint(const string& type_name, + virtual void EndVisitConstraint(const std::string& type_name, const Constraint* const constraint) { // We ignore cast constraints, they will be regenerated automatically. if (constraint->IsCastConstraint()) { @@ -570,12 +570,12 @@ class SecondPassVisitor : public ModelVisitor { PopArgumentHolder(); } - virtual void BeginVisitIntegerExpression(const string& type_name, + virtual void BeginVisitIntegerExpression(const std::string& type_name, const IntExpr* const expression) { PushArgumentHolder(); } - virtual void EndVisitIntegerExpression(const string& type_name, + virtual void EndVisitIntegerExpression(const std::string& type_name, const IntExpr* const expression) { const int index = model_proto_->expressions_size(); CPIntegerExpressionProto* const expression_proto = @@ -584,36 +584,36 @@ class SecondPassVisitor : public ModelVisitor { PopArgumentHolder(); } - virtual void BeginVisitExtension(const string& type_name) { + virtual void BeginVisitExtension(const std::string& type_name) { PushExtension(type_name); } - virtual void EndVisitExtension(const string& type_name) { + virtual void EndVisitExtension(const std::string& type_name) { PopAndSaveExtension(); } - virtual void VisitIntegerArgument(const string& arg_name, int64 value) { + virtual void VisitIntegerArgument(const std::string& arg_name, int64 value) { top()->set_integer_argument(arg_name, value); } - virtual void VisitIntegerArrayArgument(const string& arg_name, + virtual void VisitIntegerArrayArgument(const std::string& arg_name, const std::vector& values) { top()->set_integer_array_argument(arg_name, values); } - virtual void VisitIntegerMatrixArgument(const string& arg_name, + virtual void VisitIntegerMatrixArgument(const std::string& arg_name, const IntTupleSet& values) { top()->set_integer_matrix_argument(arg_name, values); } - virtual void VisitIntegerExpressionArgument(const string& arg_name, + virtual void VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument) { top()->set_integer_expression_argument(arg_name, FindExpressionIndexOrDie(argument)); } virtual void VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { std::vector indices; for (int i = 0; i < arguments.size(); ++i) { indices.push_back(FindExpressionIndexOrDie(arguments[i])); @@ -622,13 +622,13 @@ class SecondPassVisitor : public ModelVisitor { indices.size()); } - virtual void VisitIntervalArgument(const string& arg_name, + virtual void VisitIntervalArgument(const std::string& arg_name, IntervalVar* argument) { top()->set_interval_argument(arg_name, FindIntervalIndexOrDie(argument)); } virtual void VisitIntervalArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { std::vector indices; for (int i = 0; i < arguments.size(); ++i) { indices.push_back(FindIntervalIndexOrDie(arguments[i])); @@ -637,13 +637,13 @@ class SecondPassVisitor : public ModelVisitor { indices.size()); } - virtual void VisitSequenceArgument(const string& arg_name, + virtual void VisitSequenceArgument(const std::string& arg_name, SequenceVar* argument) { top()->set_sequence_argument(arg_name, FindSequenceIndexOrDie(argument)); } virtual void VisitSequenceArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { std::vector indices; for (int i = 0; i < arguments.size(); ++i) { indices.push_back(FindSequenceIndexOrDie(arguments[i])); @@ -696,7 +696,7 @@ class SecondPassVisitor : public ModelVisitor { } virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { const int index = model_proto_->expressions_size(); CPIntegerExpressionProto* const var_proto = model_proto_->add_expressions(); @@ -711,7 +711,7 @@ class SecondPassVisitor : public ModelVisitor { } virtual void VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate) { if (delegate != nullptr) { const int index = model_proto_->intervals_size(); @@ -782,7 +782,7 @@ class SecondPassVisitor : public ModelVisitor { } } - int TagIndex(const string& tag) { return tags_.Add(tag); } + int TagIndex(const std::string& tag) { return tags_.Add(tag); } private: void WriteModelExtension(ArgumentHolder* const holder) { @@ -834,7 +834,7 @@ class SecondPassVisitor : public ModelVisitor { template void ExportToProto(const A* const argument, P* const proto, - const string& type_name, int index) { + const std::string& type_name, int index) { CHECK(proto != nullptr); CHECK(argument != nullptr); proto->set_index(index); @@ -861,7 +861,7 @@ class SecondPassVisitor : public ModelVisitor { extensions_.clear(); } - void PushExtension(const string& type_name) { + void PushExtension(const std::string& type_name) { PushArgumentHolder(); holders_.back()->set_type_name(type_name); } @@ -901,7 +901,7 @@ class SecondPassVisitor : public ModelVisitor { std::vector holders_; std::vector extensions_; - VectorMap tags_; + VectorMap tags_; }; // ---------- Model Protocol Reader ---------- @@ -932,7 +932,7 @@ class ArrayWithOffset : public BaseObject { values_[index - index_min_] = value; } - virtual string DebugString() const { return "ArrayWithOffset"; } + virtual std::string DebugString() const { return "ArrayWithOffset"; } private: const int64 index_min_; @@ -1053,11 +1053,11 @@ Constraint* BuildCircuit(CPModelLoader* const builder, std::vector vars; VERIFY(builder->ScanArguments(ModelVisitor::kNextsArgument, proto, &vars)); int64 v; - VERIFY(builder->ScanArguments(ModelVisitor::kCompleteArgument, proto, &v)); + VERIFY(builder->ScanArguments(ModelVisitor::kPartialArgument, proto, &v)); if (v == 1) { - return builder->solver()->MakeCircuit(vars); - } else { return builder->solver()->MakeSubCircuit(vars); + } else { + return builder->solver()->MakeCircuit(vars); } } @@ -1128,7 +1128,7 @@ Constraint* BuildCumulative(CPModelLoader* const builder, int64 capacity; VERIFY(builder->ScanArguments(ModelVisitor::kCapacityArgument, proto, &capacity)); - string name; + std::string name; if (proto.has_name()) { name = proto.name(); } @@ -1522,7 +1522,7 @@ IntervalVar* BuildIntervalVariable(CPModelLoader* const builder, VERIFY_EQ(duration_max, duration_min); VERIFY_EQ(end_max - duration_max, start_max); VERIFY_EQ(end_min - duration_min, start_min); - const string name = proto.name(); + const std::string name = proto.name(); if (start_min == start_max) { return solver->MakeFixedInterval(start_min, duration_min, name); } else { @@ -2591,45 +2591,45 @@ bool Solver::UpgradeModel(CPModelProto* const proto) { return true; } -void Solver::RegisterBuilder(const string& tag, +void Solver::RegisterBuilder(const std::string& tag, ConstraintBuilder* const builder) { InsertOrDie(&constraint_builders_, tag, builder); } -void Solver::RegisterBuilder(const string& tag, +void Solver::RegisterBuilder(const std::string& tag, IntegerExpressionBuilder* const builder) { InsertOrDie(&expression_builders_, tag, builder); } -void Solver::RegisterBuilder(const string& tag, +void Solver::RegisterBuilder(const std::string& tag, IntervalVariableBuilder* const builder) { InsertOrDie(&interval_builders_, tag, builder); } -void Solver::RegisterBuilder(const string& tag, +void Solver::RegisterBuilder(const std::string& tag, SequenceVariableBuilder* const builder) { InsertOrDie(&sequence_builders_, tag, builder); } -Solver::ConstraintBuilder* Solver::GetConstraintBuilder(const string& tag) +Solver::ConstraintBuilder* Solver::GetConstraintBuilder(const std::string& tag) const { return FindPtrOrNull(constraint_builders_, tag); } Solver::IntegerExpressionBuilder* Solver::GetIntegerExpressionBuilder( - const string& tag) const { + const std::string& tag) const { return FindPtrOrNull(expression_builders_, tag); } Solver::IntervalVariableBuilder* Solver::GetIntervalVariableBuilder( - const string& tag) const { + const std::string& tag) const { IntervalVariableBuilder* const builder = FindPtrOrNull(interval_builders_, tag); return builder; } Solver::SequenceVariableBuilder* Solver::GetSequenceVariableBuilder( - const string& tag) const { + const std::string& tag) const { SequenceVariableBuilder* const builder = FindPtrOrNull(sequence_builders_, tag); return builder; diff --git a/src/constraint_solver/local_search.cc b/src/constraint_solver/local_search.cc index 67802245d9..9bf51378f5 100644 --- a/src/constraint_solver/local_search.cc +++ b/src/constraint_solver/local_search.cc @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include #include #include "base/hash.h" #include "base/hash.h" @@ -380,7 +379,7 @@ class SimpleLNS : public BaseLNS { ~SimpleLNS() {} virtual void InitFragments() { index_ = 0; } virtual bool NextFragment(std::vector* fragment); - virtual string DebugString() const { return "SimpleLNS"; } + virtual std::string DebugString() const { return "SimpleLNS"; } private: int index_; @@ -414,7 +413,7 @@ class RandomLNS : public BaseLNS { ~RandomLNS() {} virtual bool NextFragment(std::vector* fragment); - virtual string DebugString() const { return "RandomLNS"; } + virtual std::string DebugString() const { return "RandomLNS"; } private: ACMRandom rand_; @@ -462,7 +461,7 @@ class MoveTowardTargetLS : public IntVarLocalSearchOperator { virtual ~MoveTowardTargetLS() {} - virtual string DebugString() const { return "MoveTowardTargetLS"; } + virtual std::string DebugString() const { return "MoveTowardTargetLS"; } protected: // Make a neighbor assigning one variable to its target value. @@ -559,7 +558,7 @@ class IncrementValue : public ChangeValue { virtual ~IncrementValue() {} virtual int64 ModifyValue(int64 index, int64 value) { return value + 1; } - virtual string DebugString() const { return "IncrementValue"; } + virtual std::string DebugString() const { return "IncrementValue"; } }; // Decrements the current value of variables. @@ -570,7 +569,7 @@ class DecrementValue : public ChangeValue { virtual ~DecrementValue() {} virtual int64 ModifyValue(int64 index, int64 value) { return value - 1; } - virtual string DebugString() const { return "DecrementValue"; } + virtual std::string DebugString() const { return "DecrementValue"; } }; } // namespace @@ -880,7 +879,7 @@ class TwoOpt : public PathOperator { virtual bool MakeNeighbor(); virtual bool IsIncremental() const { return true; } - virtual string DebugString() const { return "TwoOpt"; } + virtual std::string DebugString() const { return "TwoOpt"; } protected: virtual bool OnSamePathAsPreviousBase(int64 base_index) { @@ -950,7 +949,7 @@ class Relocate : public PathOperator { virtual ~Relocate() {} virtual bool MakeNeighbor(); - virtual string DebugString() const { return "Relocate"; } + virtual std::string DebugString() const { return "Relocate"; } protected: virtual bool OnSamePathAsPreviousBase(int64 base_index) { @@ -995,7 +994,7 @@ class Exchange : public PathOperator { virtual ~Exchange() {} virtual bool MakeNeighbor(); - virtual string DebugString() const { return "Exchange"; } + virtual std::string DebugString() const { return "Exchange"; } }; bool Exchange::MakeNeighbor() { @@ -1035,7 +1034,7 @@ class Cross : public PathOperator { virtual ~Cross() {} virtual bool MakeNeighbor(); - virtual string DebugString() const { return "Cross"; } + virtual std::string DebugString() const { return "Cross"; } }; bool Cross::MakeNeighbor() { @@ -1117,7 +1116,7 @@ class MakeActiveOperator : public BaseInactiveNodeToPathOperator { virtual ~MakeActiveOperator() {} virtual bool MakeNeighbor(); - virtual string DebugString() const { return "MakeActiveOperator"; } + virtual std::string DebugString() const { return "MakeActiveOperator"; } }; bool MakeActiveOperator::MakeNeighbor() { @@ -1146,7 +1145,7 @@ class MakeInactiveOperator : public PathOperator { return MakeChainInactive(base, Next(base)); } - virtual string DebugString() const { return "MakeInactiveOperator"; } + virtual std::string DebugString() const { return "MakeInactiveOperator"; } }; // ----- MakeChainInactiveOperator ----- @@ -1168,7 +1167,7 @@ class MakeChainInactiveOperator : public PathOperator { return MakeChainInactive(BaseNode(0), BaseNode(1)); } - virtual string DebugString() const { return "MakeChainInactiveOperator"; } + virtual std::string DebugString() const { return "MakeChainInactiveOperator"; } protected: virtual bool OnSamePathAsPreviousBase(int64 base_index) { @@ -1203,7 +1202,7 @@ class SwapActiveOperator : public BaseInactiveNodeToPathOperator { virtual ~SwapActiveOperator() {} virtual bool MakeNeighbor(); - virtual string DebugString() const { return "SwapActiveOperator"; } + virtual std::string DebugString() const { return "SwapActiveOperator"; } }; bool SwapActiveOperator::MakeNeighbor() { @@ -1236,7 +1235,7 @@ class ExtendedSwapActiveOperator : public BaseInactiveNodeToPathOperator { virtual ~ExtendedSwapActiveOperator() {} virtual bool MakeNeighbor(); - virtual string DebugString() const { return "ExtendedSwapActiveOperator"; } + virtual std::string DebugString() const { return "ExtendedSwapActiveOperator"; } }; bool ExtendedSwapActiveOperator::MakeNeighbor() { @@ -1271,7 +1270,7 @@ class TSPOpt : public PathOperator { virtual ~TSPOpt() {} virtual bool MakeNeighbor(); - virtual string DebugString() const { return "TSPOpt"; } + virtual std::string DebugString() const { return "TSPOpt"; } private: std::vector > cost_; @@ -1337,7 +1336,7 @@ class TSPLns : public PathOperator { virtual ~TSPLns() {} virtual bool MakeNeighbor(); - virtual string DebugString() const { return "TSPLns"; } + virtual std::string DebugString() const { return "TSPLns"; } protected: virtual bool MakeOneNeighbor(); @@ -1470,7 +1469,7 @@ class NearestNeighbors { void Initialize(); const std::vector& Neighbors(int index) const; - virtual string DebugString() const { return "NearestNeighbors"; } + virtual std::string DebugString() const { return "NearestNeighbors"; } private: void ComputeNearest(int row); @@ -1578,7 +1577,7 @@ class LinKernighan : public PathOperator { virtual ~LinKernighan(); virtual bool MakeNeighbor(); - virtual string DebugString() const { return "LinKernighan"; } + virtual std::string DebugString() const { return "LinKernighan"; } private: virtual void OnNodeInitialization(); @@ -1731,7 +1730,7 @@ class PathLNS : public PathOperator { virtual ~PathLNS() {} virtual bool MakeNeighbor(); - virtual string DebugString() const { return "PathLNS"; } + virtual std::string DebugString() const { return "PathLNS"; } private: inline bool ChainsAreFullPaths() const { return chunk_size_ == 0; } @@ -1806,7 +1805,7 @@ class NeighborhoodLimit : public LocalSearchOperator { return operator_->MakeNextNeighbor(delta, deltadelta); } - virtual string DebugString() const { return "NeighborhoodLimit"; } + virtual std::string DebugString() const { return "NeighborhoodLimit"; } private: LocalSearchOperator* const operator_; @@ -1831,7 +1830,7 @@ class CompoundOperator : public LocalSearchOperator { virtual void Start(const Assignment* assignment); virtual bool MakeNextNeighbor(Assignment* delta, Assignment* deltadelta); - virtual string DebugString() const { return "CompoundOperator"; } + virtual std::string DebugString() const { return "CompoundOperator"; } private: class OperatorComparator { @@ -1891,7 +1890,7 @@ void CompoundOperator::Start(const Assignment* assignment) { } OperatorComparator comparator(evaluator_.get(), operator_indices_[index_]); std::sort(operator_indices_.get(), operator_indices_.get() + size_, - comparator); + comparator); index_ = 0; } } @@ -1963,7 +1962,7 @@ class RandomCompoundOperator : public LocalSearchOperator { virtual void Start(const Assignment* assignment); virtual bool MakeNextNeighbor(Assignment* delta, Assignment* deltadelta); - virtual string DebugString() const { return "RandomCompoundOperator"; } + virtual std::string DebugString() const { return "RandomCompoundOperator"; } private: const int size_; @@ -2003,7 +2002,7 @@ bool RandomCompoundOperator::MakeNextNeighbor(Assignment* delta, for (int i = 0; i < size_; ++i) { indices[i] = i; } - random_shuffle(indices.begin(), indices.end(), rand_); + std::random_shuffle(indices.begin(), indices.end(), rand_); for (int i = 0; i < size_; ++i) { if (operators_[indices[i]]->MakeNextNeighbor(delta, deltadelta)) { return true; @@ -2241,7 +2240,7 @@ class VariableDomainFilter : public LocalSearchFilter { virtual bool Accept(const Assignment* delta, const Assignment* deltadelta); virtual void Synchronize(const Assignment* assignment) {} - virtual string DebugString() const { return "VariableDomainFilter"; } + virtual std::string DebugString() const { return "VariableDomainFilter"; } }; bool VariableDomainFilter::Accept(const Assignment* delta, @@ -2329,7 +2328,7 @@ class ObjectiveFilter : public IntVarLocalSearchFilter { int64* obj_value) = 0; virtual bool IsIncremental() const { return true; } - virtual string DebugString() const { return "ObjectiveFilter"; } + virtual std::string DebugString() const { return "ObjectiveFilter"; } protected: const int primary_vars_size_; @@ -2664,7 +2663,7 @@ class FindOneNeighbor : public DecisionBuilder { const std::vector& filters); virtual ~FindOneNeighbor() {} virtual Decision* Next(Solver* const solver); - virtual string DebugString() const { return "FindOneNeighbor"; } + virtual std::string DebugString() const { return "FindOneNeighbor"; } private: bool FilterAccept(const Assignment* delta, const Assignment* deltadelta); @@ -2835,7 +2834,7 @@ class LocalSearchPhaseParameters : public BaseObject { limit_(limit), filters_(filters) {} ~LocalSearchPhaseParameters() {} - virtual string DebugString() const { return "LocalSearchPhaseParameters"; } + virtual std::string DebugString() const { return "LocalSearchPhaseParameters"; } SolutionPool* solution_pool() const { return solution_pool_; } LocalSearchOperator* ls_operator() const { return ls_operator_; } @@ -2924,7 +2923,7 @@ class NestedSolveDecision : public Decision { virtual ~NestedSolveDecision() {} virtual void Apply(Solver* const solver); virtual void Refute(Solver* const solver); - virtual string DebugString() const { return "NestedSolveDecision"; } + virtual std::string DebugString() const { return "NestedSolveDecision"; } int state() const { return state_; } private: @@ -3001,7 +3000,7 @@ class LocalSearch : public DecisionBuilder { const std::vector& filters); virtual ~LocalSearch(); virtual Decision* Next(Solver* const solver); - virtual string DebugString() const { return "LocalSearch"; } + virtual std::string DebugString() const { return "LocalSearch"; } virtual void Accept(ModelVisitor* const visitor) const; protected: @@ -3213,7 +3212,7 @@ class DefaultSolutionPool : public SolutionPool { virtual bool SyncNeeded(Assignment* const local_assignment) { return false; } - virtual string DebugString() const { return "DefaultSolutionPool"; } + virtual std::string DebugString() const { return "DefaultSolutionPool"; } private: std::unique_ptr reference_assignment_; diff --git a/src/constraint_solver/model_cache.cc b/src/constraint_solver/model_cache.cc index 2e17646d64..51b9c2deaa 100644 --- a/src/constraint_solver/model_cache.cc +++ b/src/constraint_solver/model_cache.cc @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include +#include #include #include "base/commandlineflags.h" diff --git a/src/constraint_solver/mtsearch.cc b/src/constraint_solver/mtsearch.cc index 4ef6096d42..6781796be9 100644 --- a/src/constraint_solver/mtsearch.cc +++ b/src/constraint_solver/mtsearch.cc @@ -205,7 +205,7 @@ class MtSolutionReceiver : public SearchMonitor { virtual void EnterSearch() { support_->MasterEnterSearch(); } virtual void ExitSearch() { support_->MasterExitSearch(); } - virtual string DebugString() const { return "MtSolutionReceiver"; } + virtual std::string DebugString() const { return "MtSolutionReceiver"; } private: MtSolveSupport* const support_; @@ -235,7 +235,7 @@ class MtSolutionDispatcher : public SearchMonitor { return false; } - virtual string DebugString() const { return "MtSolutionDispatcher"; } + virtual std::string DebugString() const { return "MtSolutionDispatcher"; } private: MtSolveSupport* const support_; @@ -534,7 +534,7 @@ class MTSharingSolutionPool : public SolutionPool { } } - virtual string DebugString() const { return "MTSharingSolutionPool"; } + virtual std::string DebugString() const { return "MTSharingSolutionPool"; } private: std::unique_ptr reference_assignment_; diff --git a/src/constraint_solver/nogoods.cc b/src/constraint_solver/nogoods.cc index a88b0233ef..ac6fc17d79 100644 --- a/src/constraint_solver/nogoods.cc +++ b/src/constraint_solver/nogoods.cc @@ -51,7 +51,7 @@ class NoGoodTerm { virtual TermStatus Evaluate() const = 0; virtual void Refute() = 0; - virtual string DebugString() const = 0; + virtual std::string DebugString() const = 0; private: DISALLOW_COPY_AND_ASSIGN(NoGoodTerm); @@ -86,7 +86,7 @@ class IntegerVariableNoGoodTerm : public NoGoodTerm { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s %s %lld)", integer_variable_->name().c_str(), assign_ ? "==" : "!=", value_); } @@ -146,7 +146,7 @@ bool NoGood::Apply(Solver* const solver) { return false; } -string NoGood::DebugString() const { +std::string NoGood::DebugString() const { return StringPrintf("(%s)", JoinDebugStringPtr(terms_, " && ").c_str()); } @@ -176,7 +176,7 @@ class NaiveNoGoodManager : public NoGoodManager { } } - string DebugString() const { + std::string DebugString() const { return StringPrintf("NaiveNoGoodManager(%d)", NoGoodCount()); } diff --git a/src/constraint_solver/pack.cc b/src/constraint_solver/pack.cc index 4bca2ec39e..ddf0fcbb0a 100644 --- a/src/constraint_solver/pack.cc +++ b/src/constraint_solver/pack.cc @@ -13,9 +13,8 @@ // Packing constraints -#include -#include #include +#include #include "base/unique_ptr.h" #include #include @@ -51,7 +50,7 @@ class Dimension : public BaseObject { virtual void PropagateUnassigned(const std::vector& assigned, const std::vector& unassigned) = 0; virtual void EndPropagate() = 0; - virtual string DebugString() const { return "Dimension"; } + virtual std::string DebugString() const { return "Dimension"; } virtual void Accept(ModelVisitor* const visitor) const = 0; Solver* solver() const { return solver_; } @@ -177,7 +176,7 @@ class InitialPropagateData : public BaseObject { const std::vector& assigned() const { return assigned_; } const std::vector& unassigned() const { return unassigned_; } - virtual string DebugString() const { return "InitialPropagateData"; } + virtual std::string DebugString() const { return "InitialPropagateData"; } private: std::vector> undecided_; @@ -381,8 +380,8 @@ void Pack::OneDomain(int var_index) { EnqueueDelayedDemon(demon_); } -string Pack::DebugString() const { - string result = "Pack(["; +std::string Pack::DebugString() const { + std::string result = "Pack(["; for (int i = 0; i < vars_.size(); ++i) { result += vars_[i]->DebugString() + " "; } @@ -896,7 +895,7 @@ class DimensionWeightedSumEqVar : public Dimension { virtual ~DimensionWeightedSumEqVar() {} - virtual string DebugString() const { return "DimensionWeightedSumEqVar"; } + virtual std::string DebugString() const { return "DimensionWeightedSumEqVar"; } virtual void Post() { for (int i = 0; i < bins_count_; ++i) { @@ -1034,7 +1033,7 @@ class DimensionWeightedCallback2SumEqVar : public Dimension { virtual ~DimensionWeightedCallback2SumEqVar() {} - virtual string DebugString() const { + virtual std::string DebugString() const { return "DimensionWeightedCallback2SumEqVar"; } @@ -1503,7 +1502,7 @@ class VariableUsageDimension : public Dimension { const std::vector& unassigned) {} virtual void EndPropagate() {} - virtual string DebugString() const { return "VariableUsageDimension"; } + virtual std::string DebugString() const { return "VariableUsageDimension"; } virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitExtension( diff --git a/src/constraint_solver/range_cst.cc b/src/constraint_solver/range_cst.cc index dac4c56671..914d8716ed 100644 --- a/src/constraint_solver/range_cst.cc +++ b/src/constraint_solver/range_cst.cc @@ -44,7 +44,7 @@ class RangeEquality : public Constraint { right_->SetRange(left_->Min(), left_->Max()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return left_->DebugString() + " == " + right_->DebugString(); } @@ -72,7 +72,7 @@ class RangeLessOrEqual : public Constraint { virtual ~RangeLessOrEqual() {} virtual void Post(); virtual void InitialPropagate(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual IntVar* Var() { return solver()->MakeIsLessOrEqualVar(left_, right_); } @@ -108,7 +108,7 @@ void RangeLessOrEqual::InitialPropagate() { } } -string RangeLessOrEqual::DebugString() const { +std::string RangeLessOrEqual::DebugString() const { return left_->DebugString() + " <= " + right_->DebugString(); } @@ -121,7 +121,7 @@ class RangeGreaterOrEqual : public Constraint { virtual ~RangeGreaterOrEqual() {} virtual void Post(); virtual void InitialPropagate(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual IntVar* Var() { return solver()->MakeIsGreaterOrEqualVar(left_, right_); } @@ -157,7 +157,7 @@ void RangeGreaterOrEqual::InitialPropagate() { } } -string RangeGreaterOrEqual::DebugString() const { +std::string RangeGreaterOrEqual::DebugString() const { return left_->DebugString() + " >= " + right_->DebugString(); } @@ -170,7 +170,7 @@ class RangeLess : public Constraint { virtual ~RangeLess() {} virtual void Post(); virtual void InitialPropagate(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual IntVar* Var() { return solver()->MakeIsLessVar(left_, right_); } virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kLess, this); @@ -203,7 +203,7 @@ void RangeLess::InitialPropagate() { } } -string RangeLess::DebugString() const { +std::string RangeLess::DebugString() const { return left_->DebugString() + " < " + right_->DebugString(); } @@ -216,7 +216,7 @@ class RangeGreater : public Constraint { virtual ~RangeGreater() {} virtual void Post(); virtual void InitialPropagate(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual IntVar* Var() { return solver()->MakeIsGreaterVar(left_, right_); } virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kGreater, this); @@ -249,7 +249,7 @@ void RangeGreater::InitialPropagate() { } } -string RangeGreater::DebugString() const { +std::string RangeGreater::DebugString() const { return left_->DebugString() + " > " + right_->DebugString(); } @@ -262,7 +262,7 @@ class DiffVar : public Constraint { virtual ~DiffVar() {} virtual void Post(); virtual void InitialPropagate(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual IntVar* Var() { return solver()->MakeIsDifferentVar(left_, right_); } virtual void Accept(ModelVisitor* const visitor) const { @@ -305,7 +305,7 @@ void DiffVar::InitialPropagate() { } } -string DiffVar::DebugString() const { +std::string DiffVar::DebugString() const { return left_->DebugString() + " != " + right_->DebugString(); } @@ -380,7 +380,7 @@ class IsEqualCt : public CastConstraint { } } - string DebugString() const { + std::string DebugString() const { return StringPrintf("IsEqualCt(%s, %s, %s)", left_->DebugString().c_str(), right_->DebugString().c_str(), target_var_->DebugString().c_str()); @@ -460,7 +460,7 @@ class IsDifferentCt : public CastConstraint { } } - string DebugString() const { + std::string DebugString() const { return StringPrintf( "IsDifferentCt(%s, %s, %s)", left_->DebugString().c_str(), right_->DebugString().c_str(), target_var_->DebugString().c_str()); @@ -515,7 +515,7 @@ class IsLessOrEqualCt : public CastConstraint { } } - string DebugString() const { + std::string DebugString() const { return StringPrintf( "IsLessOrEqualCt(%s, %s, %s)", left_->DebugString().c_str(), right_->DebugString().c_str(), target_var_->DebugString().c_str()); @@ -569,7 +569,7 @@ class IsLessCt : public CastConstraint { } } - string DebugString() const { + std::string DebugString() const { return StringPrintf("IsLessCt(%s, %s, %s)", left_->DebugString().c_str(), right_->DebugString().c_str(), target_var_->DebugString().c_str()); @@ -688,11 +688,11 @@ IntVar* Solver::MakeIsEqualVar(IntExpr* const v1, IntExpr* const v2) { if (cache != nullptr) { return cache->Var(); } else { - string name1 = v1->name(); + std::string name1 = v1->name(); if (name1.empty()) { name1 = v1->DebugString(); } - string name2 = v2->name(); + std::string name2 = v2->name(); if (name2.empty()) { name2 = v2->DebugString(); } @@ -751,11 +751,11 @@ IntVar* Solver::MakeIsDifferentVar(IntExpr* const v1, IntExpr* const v2) { if (reverse_cache != nullptr) { boolvar = MakeDifference(1, reverse_cache)->Var(); } else { - string name1 = v1->name(); + std::string name1 = v1->name(); if (name1.empty()) { name1 = v1->DebugString(); } - string name2 = v2->name(); + std::string name2 = v2->name(); if (name2.empty()) { name2 = v2->DebugString(); } @@ -795,11 +795,11 @@ IntVar* Solver::MakeIsLessOrEqualVar(IntExpr* const left, if (cache != nullptr) { return cache->Var(); } else { - string name1 = left->name(); + std::string name1 = left->name(); if (name1.empty()) { name1 = left->DebugString(); } - string name2 = right->name(); + std::string name2 = right->name(); if (name2.empty()) { name2 = right->DebugString(); } @@ -838,11 +838,11 @@ IntVar* Solver::MakeIsLessVar(IntExpr* const left, IntExpr* const right) { if (cache != nullptr) { return cache->Var(); } else { - string name1 = left->name(); + std::string name1 = left->name(); if (name1.empty()) { name1 = left->DebugString(); } - string name2 = right->name(); + std::string name2 = right->name(); if (name2.empty()) { name2 = right->DebugString(); } diff --git a/src/constraint_solver/resource.cc b/src/constraint_solver/resource.cc index ac5797d16b..93e1d906d3 100644 --- a/src/constraint_solver/resource.cc +++ b/src/constraint_solver/resource.cc @@ -20,7 +20,6 @@ // In addition, it implements the SequenceVar that allows ranking decisions // on a set of interval variables. -#include #include #include "base/hash.h" #include @@ -64,7 +63,7 @@ namespace { // TODO(user): Tie breaking. -// Comparison methods, used by the STL std::sort. +// Comparison methods, used by the STL sort. template bool StartMinLessThan(Task* const w1, Task* const w2) { return (w1->interval->StartMin() < w2->interval->StartMin()); @@ -95,7 +94,7 @@ struct DisjunctiveTask { explicit DisjunctiveTask(IntervalVar* const interval_) : interval(interval_), index(-1) {} - string DebugString() const { return interval->DebugString(); } + std::string DebugString() const { return interval->DebugString(); } IntervalVar* interval; int index; @@ -112,7 +111,7 @@ struct CumulativeTask { int64 EnergyMin() const { return interval->DurationMin() * demand; } - string DebugString() const { + std::string DebugString() const { return StringPrintf("Task{ %s, demand: %" GG_LL_FORMAT "d }", interval->DebugString().c_str(), demand); } @@ -147,7 +146,7 @@ struct ThetaNode { return total_processing == 0LL && total_ect == kint64min; } - string DebugString() const { + std::string DebugString() const { return StringPrintf("ThetaNode{ p = %" GG_LL_FORMAT "d, e = %" GG_LL_FORMAT "d }", total_processing, total_ect < 0LL ? -1LL : total_ect); @@ -252,7 +251,7 @@ struct LambdaThetaNode { void Compute(const LambdaThetaNode& left, const LambdaThetaNode& right) { energy = left.energy + right.energy; energetic_end_min = std::max(right.energetic_end_min, - left.energetic_end_min + right.energy); + left.energetic_end_min + right.energy); const int64 energy_left_opt = left.energy_opt + right.energy; const int64 energy_right_opt = left.energy + right.energy_opt; if (energy_left_opt > energy_right_opt) { @@ -402,12 +401,12 @@ NotLast::NotLast(Solver* const solver, const std::vector& interval bool NotLast::Propagate() { // ---- Init ---- std::sort(by_start_max_.begin(), by_start_max_.end(), - StartMaxLessThan); + StartMaxLessThan); std::sort(by_end_max_.begin(), by_end_max_.end(), - EndMaxLessThan); + EndMaxLessThan); // Update start min positions std::sort(by_start_min_.begin(), by_start_min_.end(), - StartMinLessThan); + StartMinLessThan); for (int i = 0; i < by_start_min_.size(); ++i) { by_start_min_[i]->index = i; } @@ -519,7 +518,7 @@ EdgeFinderAndDetectablePrecedences::EdgeFinderAndDetectablePrecedences( void EdgeFinderAndDetectablePrecedences::UpdateEst() { std::sort(by_start_min_.begin(), by_start_min_.end(), - StartMinLessThan); + StartMinLessThan); for (int i = 0; i < size(); ++i) { by_start_min_[i]->index = i; } @@ -529,7 +528,7 @@ void EdgeFinderAndDetectablePrecedences::OverloadChecking() { // Initialization. UpdateEst(); std::sort(by_end_max_.begin(), by_end_max_.end(), - EndMaxLessThan); + EndMaxLessThan); theta_tree_.Clear(); for (int i = 0; i < size(); ++i) { @@ -550,9 +549,9 @@ bool EdgeFinderAndDetectablePrecedences::DetectablePrecedences() { // Propagate in one direction std::sort(by_end_min_.begin(), by_end_min_.end(), - EndMinLessThan); + EndMinLessThan); std::sort(by_start_max_.begin(), by_start_max_.end(), - StartMaxLessThan); + StartMaxLessThan); theta_tree_.Clear(); int j = 0; for (int i = 0; i < size(); ++i) { @@ -602,7 +601,7 @@ bool EdgeFinderAndDetectablePrecedences::EdgeFinder() { // Push in one direction. std::sort(by_end_max_.begin(), by_end_max_.end(), - EndMaxLessThan); + EndMaxLessThan); lt_tree_.Clear(); for (int i = 0; i < size(); ++i) { lt_tree_.Insert(*by_start_min_[i]); @@ -830,7 +829,7 @@ class RankedPropagator : public Constraint { : 0; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf( "RankedPropagator([%s], nexts = [%s], intervals = [%s])", partial_sequence_.DebugString().c_str(), @@ -859,7 +858,7 @@ class FullDisjunctiveConstraint : public DisjunctiveConstraint { public: FullDisjunctiveConstraint(Solver* const s, const std::vector& intervals, - const string& name) + const std::string& name) : DisjunctiveConstraint(s, intervals, name), sequence_var_(nullptr), straight_(s, intervals, false), @@ -912,7 +911,7 @@ class FullDisjunctiveConstraint : public DisjunctiveConstraint { return sequence_var_; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("FullDisjunctiveConstraint([%s])", JoinDebugStringPtr(intervals_, ",").c_str()); } @@ -931,7 +930,7 @@ class FullDisjunctiveConstraint : public DisjunctiveConstraint { return; } Solver* const s = solver(); - const string& ct_name = name(); + const std::string& ct_name = name(); const int num_intervals = intervals_.size(); const int num_nodes = intervals_.size() + 1; int64 horizon = 0; @@ -1044,10 +1043,10 @@ struct DualCapacityThetaNode { const DualCapacityThetaNode& right) { energy = left.energy + right.energy; energetic_end_min = std::max(left.energetic_end_min + right.energy, - right.energetic_end_min); + right.energetic_end_min); residual_energetic_end_min = std::max(left.residual_energetic_end_min + right.energy, - right.residual_energetic_end_min); + right.residual_energetic_end_min); } // Amount of resource consumed by the Theta set, in units of demand X time. @@ -1213,13 +1212,13 @@ class UpdatesForADemand { DISALLOW_COPY_AND_ASSIGN(UpdatesForADemand); }; -// Returns min(a * b, kint64max). a is positive. +// Returns std::min(a * b, kint64max). a is positive. int64 SafeProduct(int64 a, int64 b) { DCHECK_GE(a, 0); const bool is_positive = b >= 0; b = std::max(b, -b); // abs(b) for int64. - // Note max(kint64min, -kint64min) = kint64min, so when b == kint64min, + // Note std::max(kint64min, -kint64min) = kint64min, so when b == kint64min, // the following DCHECK fails. DCHECK_GE(b, 0); const int kint64SurelyOverflow = 63; @@ -1296,25 +1295,25 @@ class EdgeFinder : public Constraint { LOG(FATAL) << "Should Not Be Visited"; } - virtual string DebugString() const { return "EdgeFinder"; } + virtual std::string DebugString() const { return "EdgeFinder"; } private: // Sets the fields in a proper state to run the propagation algorithm. void InitPropagation() { // Clear the update stack new_start_min_.clear(); - // std::sort y start min. + // sort y start min. std::sort(by_start_min_.begin(), by_start_min_.end(), - StartMinLessThan); + StartMinLessThan); for (int i = 0; i < by_start_min_.size(); ++i) { by_start_min_[i]->index = i; } // Sort by end max. std::sort(by_end_max_.begin(), by_end_max_.end(), - EndMaxLessThan); + EndMaxLessThan); // Sort by end min. std::sort(by_end_min_.begin(), by_end_min_.end(), - EndMinLessThan); + EndMinLessThan); // Clear tree. lt_tree_.Clear(); // Clear updates @@ -1564,7 +1563,7 @@ class CumulativeTimeTable : public Constraint { LOG(FATAL) << "Should not be visited"; } - virtual string DebugString() const { return "CumulativeTimeTable"; } + virtual std::string DebugString() const { return "CumulativeTimeTable"; } private: // Build the usage profile. Runs in O(n log n). @@ -1584,7 +1583,7 @@ class CumulativeTimeTable : public Constraint { } // Sort std::sort(profile_non_unique_time_.begin(), profile_non_unique_time_.end(), - TimeLessThan); + TimeLessThan); // Build profile with unique times profile_unique_time_.clear(); profile_unique_time_.push_back(ProfileDelta(kint64min, 0)); @@ -1613,7 +1612,7 @@ class CumulativeTimeTable : public Constraint { // Update the start min for all tasks. Runs in O(n^2) and Omega(n). void PushTasks() { std::sort(by_start_min_.begin(), by_start_min_.end(), - StartMinLessThan); + StartMinLessThan); int64 usage = 0; int profile_index = 0; for (int task_index = 0; task_index < NumTasks(); ++task_index) { @@ -1706,7 +1705,7 @@ class CumulativeConstraint : public Constraint { public: CumulativeConstraint(Solver* const s, const std::vector& intervals, const std::vector& demands, int64 capacity, - const string& name) + const std::string& name) : Constraint(s), capacity_(capacity), intervals_(intervals), @@ -1752,7 +1751,7 @@ class CumulativeConstraint : public Constraint { visitor->EndVisitConstraint(ModelVisitor::kCumulative, this); } - virtual string DebugString() const { return "CumulativeConstraint"; } + virtual std::string DebugString() const { return "CumulativeConstraint"; } private: // Post temporal disjunctions for tasks that cannot overlap. @@ -1796,7 +1795,7 @@ class CumulativeConstraint : public Constraint { if (high_demand_intervals.size() >= 2) { // If there are less than 2 such intervals, the constraint would do // nothing - string seq_name = StrCat(name(), "-HighDemandSequence"); + std::string seq_name = StrCat(name(), "-HighDemandSequence"); constraint = solver()->MakeDisjunctiveConstraint(high_demand_intervals, seq_name); } @@ -1878,7 +1877,7 @@ class CumulativeConstraint : public Constraint { // ----- Public class ----- DisjunctiveConstraint::DisjunctiveConstraint( - Solver* const s, const std::vector& intervals, const string& name) + Solver* const s, const std::vector& intervals, const std::string& name) : Constraint(s), intervals_(intervals) { if (!name.empty()) { set_name(name); @@ -1890,13 +1889,13 @@ DisjunctiveConstraint::~DisjunctiveConstraint() {} // ---------- Factory methods ---------- DisjunctiveConstraint* Solver::MakeDisjunctiveConstraint( - const std::vector& intervals, const string& name) { + const std::vector& intervals, const std::string& name) { return RevAlloc(new FullDisjunctiveConstraint(this, intervals, name)); } Constraint* Solver::MakeCumulative(const std::vector& intervals, const std::vector& demands, int64 capacity, - const string& name) { + const std::string& name) { CHECK_EQ(intervals.size(), demands.size()); for (int i = 0; i < intervals.size(); ++i) { CHECK_GE(demands[i], 0); @@ -1910,13 +1909,13 @@ Constraint* Solver::MakeCumulative(const std::vector& intervals, Constraint* Solver::MakeCumulative(const std::vector& intervals, const std::vector& demands, int64 capacity, - const string& name) { + const std::string& name) { return MakeCumulative(intervals, ToInt64Vector(demands), capacity, name); } Constraint* Solver::MakeCumulative(const std::vector& intervals, const std::vector& demands, - IntVar* const capacity, const string& name) { + IntVar* const capacity, const std::string& name) { CHECK_EQ(intervals.size(), demands.size()); for (int i = 0; i < intervals.size(); ++i) { CHECK_GE(demands[i], 0); @@ -1943,7 +1942,7 @@ Constraint* Solver::MakeCumulative(const std::vector& intervals, std::vector o_vars; // Optional variables. std::vector o_coefs; for (int64 mult = 1; mult <= delta_capacity; mult *= 2) { - const string name = + const std::string name = StringPrintf("VariableCapacity<%" GG_LL_FORMAT "d>", mult); IntervalVar* const var = MakeFixedDurationIntervalVar( horizon_min, horizon_min, total_duration, true, name); @@ -1961,7 +1960,7 @@ Constraint* Solver::MakeCumulative(const std::vector& intervals, Constraint* Solver::MakeCumulative(const std::vector& intervals, const std::vector& demands, - IntVar* const capacity, const string& name) { + IntVar* const capacity, const std::string& name) { return MakeCumulative(intervals, ToInt64Vector(demands), capacity, name); } } // namespace operations_research diff --git a/src/constraint_solver/routing.cc b/src/constraint_solver/routing.cc index bae68ed00c..d1b8eff730 100644 --- a/src/constraint_solver/routing.cc +++ b/src/constraint_solver/routing.cc @@ -188,7 +188,7 @@ class LightFunctionElementConstraint : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return "LightFunctionElementConstraint"; } @@ -240,7 +240,7 @@ class LightFunctionElement2Constraint : public Constraint { } virtual void InitialPropagate() { IndexBound(); } - virtual string DebugString() const { + virtual std::string DebugString() const { return "LightFunctionElement2Constraint"; } @@ -299,8 +299,8 @@ class MakeRelocateNeighborsOperator : public PathOperator { Solver::IndexEvaluator2* arc_evaluator) : PathOperator(vars, secondary_vars, 2), arc_evaluator_(arc_evaluator) { int64 max_next = -1; - for (int i = 0; i < vars.size(); ++i) { - max_next = std::max(max_next, vars[i]->Max()); + for (const IntVar* const var : vars) { + max_next = std::max(max_next, var->Max()); } prevs_.resize(max_next + 1, -1); } @@ -324,7 +324,7 @@ class MakeRelocateNeighborsOperator : public PathOperator { } return MoveChainAndRepair(before_chain, chain_end, destination); } - virtual string DebugString() const { return "RelocateNeighbors"; } + virtual std::string DebugString() const { return "RelocateNeighbors"; } private: virtual void OnNodeInitialization() { @@ -509,24 +509,24 @@ class PairRelocateOperator : public PathOperator { public: PairRelocateOperator(const std::vector& vars, const std::vector& secondary_vars, - const RoutingModel::NodePairs& pairs) + const RoutingModel::NodePairs& node_pairs) : PathOperator(vars, secondary_vars, 3) { int64 index_max = 0; - for (int i = 0; i < vars.size(); ++i) { - index_max = std::max(index_max, vars[i]->Max()); + for (const IntVar* const var : vars) { + index_max = std::max(index_max, var->Max()); } prevs_.resize(index_max + 1, -1); is_first_.resize(index_max + 1, false); - int max_pair_index = -1; - for (int i = 0; i < pairs.size(); ++i) { - max_pair_index = std::max(max_pair_index, pairs[i].first); - max_pair_index = std::max(max_pair_index, pairs[i].second); + int64 max_pair_index = -1; + for (const std::pair node_pair : node_pairs) { + max_pair_index = std::max(max_pair_index, node_pair.first); + max_pair_index = std::max(max_pair_index, node_pair.second); } pairs_.resize(max_pair_index + 1, -1); - for (int i = 0; i < pairs.size(); ++i) { - pairs_[pairs[i].first] = pairs[i].second; - pairs_[pairs[i].second] = pairs[i].first; - is_first_[pairs[i].first] = true; + for (const std::pair node_pair : node_pairs) { + pairs_[node_pair.first] = node_pair.second; + pairs_[node_pair.second] = node_pair.first; + is_first_[node_pair.first] = true; } } virtual ~PairRelocateOperator() {} @@ -752,7 +752,7 @@ RoutingModel::RoutingModel(int nodes, int vehicles) RoutingModel::RoutingModel( int nodes, int vehicles, - const std::vector >& start_end) + const std::vector >& start_ends) : nodes_(nodes), vehicles_(vehicles), no_cycle_constraint_(nullptr), @@ -783,15 +783,15 @@ RoutingModel::RoutingModel( lns_limit_(nullptr) { SolverParameters parameters; solver_.reset(new Solver("Routing", parameters)); - CHECK_EQ(vehicles, start_end.size()); + CHECK_EQ(vehicles, start_ends.size()); hash_set depot_set; - for (int i = 0; i < start_end.size(); ++i) { - depot_set.insert(start_end[i].first); - depot_set.insert(start_end[i].second); + for (const std::pair start_end : start_ends) { + depot_set.insert(start_end.first); + depot_set.insert(start_end.second); } start_end_count_ = depot_set.size(); Initialize(); - SetStartEnd(start_end); + SetStartEnd(start_ends); } RoutingModel::RoutingModel(int nodes, int vehicles, @@ -830,15 +830,15 @@ RoutingModel::RoutingModel(int nodes, int vehicles, CHECK_EQ(vehicles, starts.size()); CHECK_EQ(vehicles, ends.size()); hash_set depot_set; - std::vector > start_end(starts.size()); + std::vector > start_ends(starts.size()); for (int i = 0; i < starts.size(); ++i) { depot_set.insert(starts[i]); depot_set.insert(ends[i]); - start_end[i] = std::make_pair(starts[i], ends[i]); + start_ends[i] = std::make_pair(starts[i], ends[i]); } start_end_count_ = depot_set.size(); Initialize(); - SetStartEnd(start_end); + SetStartEnd(start_ends); } void RoutingModel::Initialize() { @@ -885,7 +885,7 @@ void RoutingModel::AddNoCycleConstraintInternal() { bool RoutingModel::AddDimension(NodeEvaluator2* evaluator, int64 slack_max, int64 capacity, bool fix_start_cumul_to_zero, - const string& dimension_name) { + const std::string& dimension_name) { return AddDimensionWithCapacityInternal(evaluator, slack_max, capacity, nullptr, fix_start_cumul_to_zero, dimension_name); @@ -894,7 +894,7 @@ bool RoutingModel::AddDimension(NodeEvaluator2* evaluator, int64 slack_max, bool RoutingModel::AddDimensionWithVehicleCapacity( NodeEvaluator2* evaluator, int64 slack_max, VehicleEvaluator* vehicle_capacity, bool fix_start_cumul_to_zero, - const string& dimension_name) { + const std::string& dimension_name) { return AddDimensionWithCapacityInternal( evaluator, slack_max, kint64max, vehicle_capacity, fix_start_cumul_to_zero, dimension_name); @@ -903,7 +903,7 @@ bool RoutingModel::AddDimensionWithVehicleCapacity( bool RoutingModel::AddDimensionWithCapacityInternal( NodeEvaluator2* evaluator, int64 slack_max, int64 capacity, VehicleEvaluator* vehicle_capacity, bool fix_start_cumul_to_zero, - const string& dimension_name) { + const std::string& dimension_name) { CheckDepot(); if (!HasDimension(dimension_name)) { const DimensionIndex dimension_index(dimensions_.size()); @@ -931,7 +931,7 @@ bool RoutingModel::AddDimensionWithCapacityInternal( bool RoutingModel::AddConstantDimension(int64 value, int64 capacity, bool fix_start_cumul_to_zero, - const string& dimension_name) { + const std::string& dimension_name) { ConstantEvaluator* evaluator = solver_->RevAlloc(new ConstantEvaluator(value)); return AddDimension( @@ -941,7 +941,7 @@ bool RoutingModel::AddConstantDimension(int64 value, int64 capacity, bool RoutingModel::AddVectorDimension(const int64* values, int64 capacity, bool fix_start_cumul_to_zero, - const string& dimension_name) { + const std::string& dimension_name) { VectorEvaluator* const evaluator = solver_->RevAlloc(new VectorEvaluator(values, nodes_, this)); return AddDimension(NewPermanentCallback(evaluator, &VectorEvaluator::Value), @@ -951,40 +951,38 @@ bool RoutingModel::AddVectorDimension(const int64* values, int64 capacity, bool RoutingModel::AddMatrixDimension(const int64* const* values, int64 capacity, bool fix_start_cumul_to_zero, - const string& dimension_name) { + const std::string& dimension_name) { MatrixEvaluator* const evaluator = solver_->RevAlloc(new MatrixEvaluator(values, nodes_, this)); return AddDimension(NewPermanentCallback(evaluator, &MatrixEvaluator::Value), 0, capacity, fix_start_cumul_to_zero, dimension_name); } -void RoutingModel::GetAllDimensions(std::vector* dimension_names) const { +void RoutingModel::GetAllDimensions(std::vector* dimension_names) const { CHECK(dimension_names != nullptr); dimension_names->clear(); - for (ConstIter > it( - dimension_name_to_index_); - !it.at_end(); ++it) { - dimension_names->push_back(it->first); + for (const auto& dimension_name_index : dimension_name_to_index_) { + dimension_names->push_back(dimension_name_index.first); } } -bool RoutingModel::HasDimension(const string& dimension_name) const { +bool RoutingModel::HasDimension(const std::string& dimension_name) const { return ContainsKey(dimension_name_to_index_, dimension_name); } RoutingModel::DimensionIndex RoutingModel::GetDimensionIndex( - const string& dimension_name) const { + const std::string& dimension_name) const { return FindWithDefault(dimension_name_to_index_, dimension_name, kNoDimension); } const RoutingDimension& RoutingModel::GetDimensionOrDie( - const string& dimension_name) const { + const std::string& dimension_name) const { return *dimensions_[FindOrDie(dimension_name_to_index_, dimension_name)]; } RoutingDimension* RoutingModel::GetMutableDimension( - const string& dimension_name) const { + const std::string& dimension_name) const { const DimensionIndex index = GetDimensionIndex(dimension_name); if (index != kNoDimension) { return dimensions_[index]; @@ -993,9 +991,9 @@ RoutingDimension* RoutingModel::GetMutableDimension( } void RoutingModel::AddAllActive() { - for (int i = 0; i < Size(); ++i) { - if (active_[i]->Max() != 0) { - active_[i]->SetValue(1); + for (IntVar* const active : active_) { + if (active->Max() != 0) { + active->SetValue(1); } } } @@ -1040,7 +1038,7 @@ static int64 ReturnZero(A a, B b) { } // Some C++ versions used in the open-source export don't support comparison -// functors for std::map; so we need a comparator class instead. +// functors for STL containers; so we need a comparator class instead. struct CostClassComparator { bool operator()(const RoutingModel::CostClass& a, const RoutingModel::CostClass& b) const { @@ -1062,9 +1060,7 @@ void RoutingModel::ComputeCostClasses() { NewPermanentCallback(&ReturnZero); owned_node_callbacks_.insert(zero_evaluator); evaluator_to_cached_evaluator[nullptr] = zero_evaluator; - for (int vehicle = 0; vehicle < transit_cost_of_vehicle_.size(); ++vehicle) { - NodeEvaluator2* const uncached_evaluator = - transit_cost_of_vehicle_[vehicle]; + for (NodeEvaluator2* const uncached_evaluator : transit_cost_of_vehicle_) { if (uncached_evaluator == nullptr) continue; // Already mapped. NodeEvaluator2** cached_evaluator = &LookupOrInsert(&evaluator_to_cached_evaluator, uncached_evaluator, @@ -1095,12 +1091,11 @@ void RoutingModel::ComputeCostClasses() { evaluator_to_cached_evaluator, transit_cost_of_vehicle_[vehicle]); CostClass cost_class(cached_evaluator); // Insert the dimension data in a canonical way. - for (DimensionIndex i(0); i < dimensions_.size(); ++i) { - const RoutingDimension& dimension = *dimensions_[i]; - const int64 coeff = dimension.vehicle_span_cost_coefficients()[vehicle]; + for (const RoutingDimension* const dimension : dimensions_) { + const int64 coeff = dimension->vehicle_span_cost_coefficients()[vehicle]; if (coeff == 0) continue; cost_class.dimension_transit_evaluator_and_cost_coefficient.push_back( - std::make_pair(dimension.transit_evaluator(), coeff)); + std::make_pair(dimension->transit_evaluator(), coeff)); } std::sort(cost_class.dimension_transit_evaluator_and_cost_coefficient.begin(), cost_class.dimension_transit_evaluator_and_cost_coefficient.end()); @@ -1154,9 +1149,9 @@ void RoutingModel::AddDisjunctionInternal(const std::vector& nodes, disjunction_nodes[i] = node_to_index_[nodes[i]]; } disjunctions_.back().penalty = penalty; - for (int i = 0; i < nodes.size(); ++i) { + for (const NodeIndex node : nodes) { // TODO(user): support multiple disjunction per node - node_to_disjunction_[node_to_index_[nodes[i]]] = DisjunctionIndex(size); + node_to_disjunction_[node_to_index_[node]] = DisjunctionIndex(size); } } @@ -1194,18 +1189,18 @@ void RoutingModel::SetDepot(NodeIndex depot) { } void RoutingModel::SetStartEnd( - const std::vector >& start_end) { + const std::vector >& start_ends) { if (is_depot_set_) { LOG(WARNING) << "A depot has already been specified, ignoring new ones"; return; } - CHECK_EQ(start_end.size(), vehicles_); + CHECK_EQ(start_ends.size(), vehicles_); const int size = Size(); hash_set starts; hash_set ends; - for (int i = 0; i < vehicles_; ++i) { - const NodeIndex start = start_end[i].first; - const NodeIndex end = start_end[i].second; + for (const std::pair start_end : start_ends) { + const NodeIndex start = start_end.first; + const NodeIndex end = start_end.second; CHECK_GE(start, 0); CHECK_GE(end, 0); CHECK_LE(start, nodes_); @@ -1226,7 +1221,7 @@ void RoutingModel::SetStartEnd( hash_set node_set; index_to_vehicle_.resize(size + vehicles_, kUnassigned); for (int i = 0; i < vehicles_; ++i) { - const NodeIndex start = start_end[i].first; + const NodeIndex start = start_ends[i].first; if (node_set.count(start) == 0) { node_set.insert(start); const int start_index = node_to_index_[start]; @@ -1241,7 +1236,7 @@ void RoutingModel::SetStartEnd( } } for (int i = 0; i < vehicles_; ++i) { - NodeIndex end = start_end[i].second; + NodeIndex end = start_ends[i].second; index_to_node_[index] = end; ends_[i] = index; CHECK_LE(size, index); @@ -1376,8 +1371,8 @@ void RoutingModel::CloseModel() { // is_bound_to_end_ variables constraints. solver_->AddConstraint( solver_->MakePathCumul(nexts_, active_, is_bound_to_end_, zero_transit)); - for (int i = 0; i < vehicles_; ++i) { - is_bound_to_end_[ends_[i]]->SetValue(1); + for (const int64 end : ends_) { + is_bound_to_end_[end]->SetValue(1); } std::vector cost_elements; @@ -1394,9 +1389,9 @@ void RoutingModel::CloseModel() { } } // Dimension span costs - for (DimensionIndex i(0); i < dimensions_.size(); ++i) { - dimensions_[i]->SetupGlobalSpanCost(&cost_elements); - dimensions_[i]->SetupSlackCosts(&cost_elements); + for (const RoutingDimension* dimension : dimensions_) { + dimension->SetupGlobalSpanCost(&cost_elements); + dimension->SetupSlackCosts(&cost_elements); } // Penalty costs for (DisjunctionIndex i(0); i < disjunctions_.size(); ++i) { @@ -1406,8 +1401,8 @@ void RoutingModel::CloseModel() { } } // Soft cumul upper bound costs - for (DimensionIndex index(0); index < dimensions_.size(); ++index) { - dimensions_[index]->SetupCumulVarSoftUpperBoundCosts(&cost_elements); + for (const RoutingDimension* dimension : dimensions_) { + dimension->SetupCumulVarSoftUpperBoundCosts(&cost_elements); } cost_ = solver_->MakeSum(cost_elements)->Var(); cost_->set_name("Cost"); @@ -1496,7 +1491,7 @@ class RouteConstructor { node_to_chain_index_(nodes_number, -1), node_to_vehicle_class_index_(nodes_number, -1) { { - std::vector dimension_names; + std::vector dimension_names; model_->GetAllDimensions(&dimension_names); dimensions_.assign(dimension_names.size(), nullptr); for (int i = 0; i < dimension_names.size(); ++i) { @@ -1504,8 +1499,8 @@ class RouteConstructor { } } cumuls_.resize(dimensions_.size()); - for (MutableIter > > it(cumuls_); !it.at_end(); ++it) { - it->resize(nodes_number_); + for (std::vector& cumuls : cumuls_) { + cumuls.resize(nodes_number_); } new_possible_cumuls_.resize(dimensions_.size()); } @@ -1523,13 +1518,13 @@ class RouteConstructor { } } - for (ConstIter > it(links_list_); !it.at_end(); ++it) { + for (const Link& link : links_list_) { model_->solver()->TopPeriodicCheck(); - const int node1 = it->link.first; - const int node2 = it->link.second; - const int vehicle_class = it->vehicle_class; - const int64 start_depot = it->start_depot; - const int64 end_depot = it->end_depot; + const int node1 = link.link.first; + const int node2 = link.link.second; + const int vehicle_class = link.vehicle_class; + const int64 start_depot = link.start_depot; + const int64 end_depot = link.end_depot; // Initialisation of cumuls_ if the nodes are encountered for first time if (node_to_vehicle_class_index_[node1] < 0) { @@ -1721,7 +1716,7 @@ class RouteConstructor { CHECK_GE(non_depot_node, 0); const int64 depot_threashold = std::max(dimension.SlackVar(non_depot_node)->Max(), - dimension.CumulVar(non_depot_node)->Max()); + dimension.CumulVar(non_depot_node)->Max()); int64 available_from_tail1 = cumuls_[dimension_index][tail1] + dimension.GetTransitValue(tail1, head2); @@ -1897,18 +1892,16 @@ class RouteConstructor { if (merge) { if (UpdateAssignment(routes_[index1], routes_[index2])) { // Connection Route1 -> Route2 - for (int node_index = 0; node_index < routes_[index2].size(); - ++node_index) { - const int node = routes_[index2][node_index]; + for (const int node : routes_[index2]) { in_route_[node] = index1; routes_[index1].push_back(node); } for (int dimension_index = 0; dimension_index < dimensions_.size(); ++dimension_index) { - for (ConstIter > it( - new_possible_cumuls_[dimension_index]); - !it.at_end(); ++it) { - cumuls_[dimension_index][it->first] = it->second; + for (const std::pair new_possible_cumul : + new_possible_cumuls_[dimension_index]) { + cumuls_[dimension_index][new_possible_cumul.first] = + new_possible_cumul.second; } } deleted_routes_.insert(index2); @@ -1954,7 +1947,7 @@ void GetVehicleClasses(const RoutingModel& model, model.GetCostClassIndexOfVehicle(vehicle))); } std::sort(vehicle_classes->begin(), vehicle_classes->end(), - &VehicleClass::LessThan); + &VehicleClass::LessThan); vehicle_classes->erase( std::unique(vehicle_classes->begin(), vehicle_classes->end(), &VehicleClass::Equals), @@ -2025,12 +2018,10 @@ class SavingsBuilder : public DecisionBuilder { for (int node = 0; node < nodes_number_; ++node) { model_->solver()->TopPeriodicCheck(); std::vector costs_from_node(nodes_number_); - for (int neighbor_index = 0; neighbor_index < neighbors_[node].size(); - ++neighbor_index) { + for (const int neighbor : neighbors_[node]) { // TODO(user): Take vehicle class into account here. - const int64 cost = - model_->GetHomogeneousCost(node, neighbors_[node][neighbor_index]); - costs_from_node[neighbors_[node][neighbor_index]] = cost; + const int64 cost = model_->GetHomogeneousCost(node, neighbor); + costs_from_node[neighbor] = cost; } costs_.push_back(costs_from_node); } @@ -2040,26 +2031,21 @@ class SavingsBuilder : public DecisionBuilder { } void CreateSavingsList() { - for (ConstIter > it(vehicle_classes_); !it.at_end(); - ++it) { - int64 start_depot = it->start_depot; - int64 end_depot = it->end_depot; - int vehicle_class_index = it->vehicle_class_index; + for (const VehicleClass& vehicle_class : vehicle_classes_) { + int64 start_depot = vehicle_class.start_depot; + int64 end_depot = vehicle_class.end_depot; + int vehicle_class_index = vehicle_class.vehicle_class_index; for (int node = 0; node < nodes_number_; ++node) { model_->solver()->TopPeriodicCheck(); - for (int neighbor_index = 0; neighbor_index < neighbors_[node].size(); - ++neighbor_index) { + for (const int neighbor : neighbors_[node]) { if (node != start_depot && node != end_depot && - neighbors_[node][neighbor_index] != start_depot && - neighbors_[node][neighbor_index] != end_depot && - node != neighbors_[node][neighbor_index]) { + neighbor != start_depot && neighbor != end_depot && + node != neighbor) { const double saving = - costs_[node][start_depot] + - costs_[end_depot][neighbors_[node][neighbor_index]] - - route_shape_parameter_ * - costs_[node][neighbors_[node][neighbor_index]]; - Link link(std::make_pair(node, neighbors_[node][neighbor_index]), - saving, vehicle_class_index, start_depot, end_depot); + costs_[node][start_depot] + costs_[end_depot][neighbor] - + route_shape_parameter_ * costs_[node][neighbor]; + Link link(std::make_pair(node, neighbor), saving, + vehicle_class_index, start_depot, end_depot); savings_list_.push_back(link); } } @@ -2071,7 +2057,7 @@ class SavingsBuilder : public DecisionBuilder { RoutingModel* const model_; std::unique_ptr route_constructor_; const bool check_assignment_; - std::vector dimensions_; + std::vector dimensions_; int64 nodes_number_; int depot_; std::vector > costs_; @@ -2146,8 +2132,8 @@ void SweepArranger::ArrangeNodes(std::vector* nodes) { : sweep_nodes.begin() + (sector + 1) * size; std::sort(begin, end, SweepNodeAngleComparator); } - for (ConstIter > it(sweep_nodes); !it.at_end(); ++it) { - nodes->push_back(it->node); + for (const SweepNode& sweep_node : sweep_nodes) { + nodes->push_back(sweep_node.node); } } @@ -2244,9 +2230,7 @@ class FastOnePathBuilder : public DecisionBuilder { index = next; std::vector alternates; model_->GetDisjunctionIndicesFromIndex(index, &alternates); - for (int alternate_index = 0; alternate_index < alternates.size(); - ++alternate_index) { - const int alternate = alternates[alternate_index]; + for (const int alternate : alternates) { if (index != alternate) { assignment->Add(nexts[alternate]); assignment->SetValue(nexts[alternate], alternate); @@ -2553,10 +2537,8 @@ bool RoutingModel::ReplaceUnusedVehicle(int unused_vehicle, int active_vehicle, } // Update dimensions: update transits at the start. - for (DimensionIndex dimension_index(0); dimension_index < dimensions_.size(); - ++dimension_index) { - const RoutingDimension& dimension = *dimensions_[dimension_index]; - const std::vector& transit_variables = dimension.transits(); + for (const RoutingDimension* const dimension : dimensions_) { + const std::vector& transit_variables = dimension->transits(); IntVar* const unused_vehicle_transit_var = transit_variables[unused_vehicle_start]; IntVar* const active_vehicle_transit_var = @@ -2569,7 +2551,7 @@ bool RoutingModel::ReplaceUnusedVehicle(int unused_vehicle, int active_vehicle, contains_active_vehicle_transit_var) { // TODO(user): clarify the expected trigger rate of this LOG. LOG(INFO) << "The assignment contains transit variable for dimension '" - << dimension.name() << "' for some vehicles, but not for all"; + << dimension->name() << "' for some vehicles, but not for all"; return false; } if (contains_unused_vehicle_transit_var) { @@ -2584,7 +2566,7 @@ bool RoutingModel::ReplaceUnusedVehicle(int unused_vehicle, int active_vehicle, } // Update dimensions: update cumuls at the end. - const std::vector& cumul_variables = dimension.cumuls(); + const std::vector& cumul_variables = dimension->cumuls(); IntVar* const unused_vehicle_cumul_var = cumul_variables[unused_vehicle_end]; IntVar* const active_vehicle_cumul_var = @@ -2761,7 +2743,7 @@ const char* RoutingModel::RoutingStrategyName(RoutingStrategy strategy) { } // static -bool RoutingModel::ParseRoutingStrategy(const string& strategy_str, +bool RoutingModel::ParseRoutingStrategy(const std::string& strategy_str, RoutingStrategy* strategy) { for (int i = 0;; ++i) { const RoutingStrategy cur_strategy = static_cast(i); @@ -2792,7 +2774,7 @@ const char* RoutingModel::RoutingMetaheuristicName( // static bool RoutingModel::ParseRoutingMetaheuristic( - const string& metaheuristic_str, RoutingMetaheuristic* metaheuristic) { + const std::string& metaheuristic_str, RoutingMetaheuristic* metaheuristic) { for (int i = 0;; ++i) { const RoutingMetaheuristic cur_metaheuristic = static_cast(i); @@ -2805,7 +2787,7 @@ bool RoutingModel::ParseRoutingMetaheuristic( } } -bool RoutingModel::WriteAssignment(const string& file_name) const { +bool RoutingModel::WriteAssignment(const std::string& file_name) const { if (collect_assignments_->solution_count() == 1 && assignment_ != nullptr) { assignment_->Copy(collect_assignments_->solution(0)); return assignment_->Save(file_name); @@ -2814,7 +2796,7 @@ bool RoutingModel::WriteAssignment(const string& file_name) const { } } -Assignment* RoutingModel::ReadAssignment(const string& file_name) { +Assignment* RoutingModel::ReadAssignment(const std::string& file_name) { QuietCloseModel(); CHECK(assignment_ != nullptr); if (assignment_->Load(file_name)) { @@ -2872,8 +2854,7 @@ bool RoutingModel::RoutesToAssignment(const std::vector > return false; } - for (int i = 0; i < route.size(); ++i) { - const NodeIndex to_node = route[i]; + for (const NodeIndex to_node : route) { if (to_node < 0 || to_node >= nodes()) { LOG(ERROR) << "Invalid node index: " << to_node; return false; @@ -3074,7 +3055,7 @@ bool RoutingModel::IsVehicleUsed(const Assignment& assignment, return !IsEnd(assignment.Value(start_var)); } -const std::vector& RoutingModel::CumulVars(const string& dimension_name) +const std::vector& RoutingModel::CumulVars(const std::string& dimension_name) const { return GetDimensionOrDie(dimension_name).cumuls(); } @@ -3117,11 +3098,8 @@ int64 RoutingModel::GetArcCostForFirstSolution(int64 i, int64 j) { int64 RoutingModel::GetDimensionTransitCostSum( int64 i, int64 j, const CostClass& cost_class) const { int64 cost = 0; - for (int k = 0; - k < cost_class.dimension_transit_evaluator_and_cost_coefficient.size(); - ++k) { - const std::pair evaluator_and_coefficient = - cost_class.dimension_transit_evaluator_and_cost_coefficient[k]; + for (const std::pair evaluator_and_coefficient : + cost_class.dimension_transit_evaluator_and_cost_coefficient) { DCHECK_GT(evaluator_and_coefficient.second, 0); cost += evaluator_and_coefficient.second * evaluator_and_coefficient.first->Run(i, j); @@ -3235,9 +3213,9 @@ int64 RoutingModel::UnperformedPenalty(int64 var_index) { return disjunctions_[disjunction_index].penalty; } -string RoutingModel::DebugOutputAssignment( +std::string RoutingModel::DebugOutputAssignment( const Assignment& solution_assignment, - const string& dimension_to_print) const { + const std::string& dimension_to_print) const { for (int i = 0; i < Size(); ++i) { if (!solution_assignment.Bound(NextVar(i))) { LOG(DFATAL) @@ -3246,8 +3224,8 @@ string RoutingModel::DebugOutputAssignment( return ""; } } - string output; - std::vector dimension_names(1, dimension_to_print); + std::string output; + std::vector dimension_names(1, dimension_to_print); if (dimension_to_print == "") { GetAllDimensions(&dimension_names); } @@ -3262,7 +3240,7 @@ string RoutingModel::DebugOutputAssignment( StringAppendF(&output, "%" GG_LL_FORMAT "d Vehicle(%" GG_LL_FORMAT "d) ", index, solution_assignment.Value(vehicle)); - for (RoutingDimension* dimension : dimensions_) { + for (const RoutingDimension* const dimension : dimensions_) { const IntVar* const var = dimension->CumulVar(index); StringAppendF(&output, "%s(%" GG_LL_FORMAT "d..%" GG_LL_FORMAT "d) ", dimension->name().c_str(), solution_assignment.Min(var), @@ -3493,8 +3471,7 @@ RoutingModel::GetOrCreateLocalSearchFilters() { std::vector path_cumul_filters; RoutingLocalSearchFilter* path_cumul_filter = nullptr; if (FLAGS_routing_use_path_cumul_filter) { - for (DimensionIndex dimension_index(0); - dimension_index < dimensions_.size(); ++dimension_index) { + for (const RoutingDimension* dimension : dimensions_) { Callback1* objective_callback = nullptr; if (path_cumul_filter != nullptr) { objective_callback = NewPermanentCallback( @@ -3502,7 +3479,7 @@ RoutingModel::GetOrCreateLocalSearchFilters() { &RoutingLocalSearchFilter::InjectObjectiveValue); } path_cumul_filter = MakePathCumulFilter( - *this, *dimensions_[dimension_index], objective_callback); + *this, *dimension, objective_callback); path_cumul_filters.push_back(path_cumul_filter); } // Due to the way cost injection is setup, path filters have to be @@ -3522,10 +3499,9 @@ RoutingModel::GetOrCreateLocalSearchFilters() { if (FLAGS_routing_use_objective_filter) { Callback1* objective_callback = nullptr; if (node_disjunction_filter != nullptr) { - objective_callback = - NewPermanentCallback( - node_disjunction_filter, - &RoutingLocalSearchFilter::InjectObjectiveValue); + objective_callback = NewPermanentCallback( + node_disjunction_filter, + &RoutingLocalSearchFilter::InjectObjectiveValue); } else if (path_cumul_filter != nullptr) { objective_callback = NewPermanentCallback( path_cumul_filter, &RoutingLocalSearchFilter::InjectObjectiveValue); @@ -3551,8 +3527,8 @@ RoutingModel::GetOrCreateLocalSearchFilters() { } if (FLAGS_routing_use_pickup_and_delivery_filter && pickup_delivery_pairs_.size() > 0) { - filters_.push_back(MakeNodePrecedenceFilter(*this, - pickup_delivery_pairs_)); + filters_.push_back( + MakeNodePrecedenceFilter(*this, pickup_delivery_pairs_)); } if (FLAGS_routing_use_path_cumul_filter) { // Must be added after NodeDisjunctionFilter and ObjectiveFilter. @@ -3566,15 +3542,13 @@ const std::vector& RoutingModel::GetOrCreateFeasibilityFilters() { if (feasibility_filters_.empty()) { if (FLAGS_routing_use_path_cumul_filter) { - for (DimensionIndex dimension_index(0); - dimension_index < dimensions_.size(); ++dimension_index) { - feasibility_filters_.push_back(MakePathCumulFilter( - *this, *dimensions_[dimension_index], nullptr)); + for (const RoutingDimension* const dimension : dimensions_) { + feasibility_filters_.push_back( + MakePathCumulFilter(*this, *dimension, nullptr)); } } if (FLAGS_routing_use_disjunction_filter && !disjunctions_.empty()) { - feasibility_filters_.push_back( - MakeNodeDisjunctionFilter(*this, nullptr)); + feasibility_filters_.push_back(MakeNodeDisjunctionFilter(*this, nullptr)); } feasibility_filters_.push_back(solver_->MakeVariableDomainFilter()); if (FLAGS_routing_use_pickup_and_delivery_filter && @@ -3590,15 +3564,13 @@ DecisionBuilder* RoutingModel::CreateSolutionFinalizer() { std::vector decision_builders; decision_builders.push_back(solver_->MakePhase( nexts_, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MIN_VALUE)); - for (ConstIter > it(variables_minimized_by_finalizer_); - !it.at_end(); ++it) { + for (IntVar* const variable : variables_minimized_by_finalizer_) { decision_builders.push_back(solver_->MakePhase( - *it, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MIN_VALUE)); + variable, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MIN_VALUE)); } - for (ConstIter > it(variables_maximized_by_finalizer_); - !it.at_end(); ++it) { + for (IntVar* const variable : variables_maximized_by_finalizer_) { decision_builders.push_back(solver_->MakePhase( - *it, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MAX_VALUE)); + variable, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MAX_VALUE)); } return solver_->Compose(decision_builders); } @@ -3825,12 +3797,11 @@ void RoutingModel::SetupMetaheuristics() { void RoutingModel::SetupAssignmentCollector() { Assignment* full_assignment = solver_->MakeAssignment(); - for (ConstIter > it(dimensions_); - !it.at_end(); ++it) { - full_assignment->Add((*it)->cumuls()); + for (const RoutingDimension* const dimension : dimensions_) { + full_assignment->Add(dimension->cumuls()); } - for (int i = 0; i < extra_vars_.size(); ++i) { - full_assignment->Add(extra_vars_[i]); + for (IntVar* const extra_var : extra_vars_) { + full_assignment->Add(extra_var); } full_assignment->Add(nexts_); full_assignment->Add(active_); @@ -3929,23 +3900,23 @@ int64 RoutingModel::GetCost(int64 i, int64 j, int64 v) { int64 RoutingModel::GetVehicleClassCost(int64 i, int64 j, int64 c) { return GetArcCostForClass(i, j, c); } -void RoutingModel::SetDimensionTransitCost(const string& name, int64 coeff) { +void RoutingModel::SetDimensionTransitCost(const std::string& name, int64 coeff) { GetMutableDimension(name)->SetSpanCostCoefficientForAllVehicles(coeff); } -int64 RoutingModel::GetDimensionTransitCost(const string& name) const { +int64 RoutingModel::GetDimensionTransitCost(const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name).vehicle_span_cost_coefficients()[0] : 0; } -void RoutingModel::SetDimensionSpanCost(const string& name, int64 coeff) { +void RoutingModel::SetDimensionSpanCost(const std::string& name, int64 coeff) { GetMutableDimension(name)->SetGlobalSpanCostCoefficient(coeff); } -int64 RoutingModel::GetDimensionSpanCost(const string& name) const { +int64 RoutingModel::GetDimensionSpanCost(const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name).global_span_cost_coefficient() : 0; } -int64 RoutingModel::GetTransitValue(const string& dimension_name, +int64 RoutingModel::GetTransitValue(const std::string& dimension_name, int64 from_index, int64 to_index) const { DimensionIndex dimension_index(-1); if (FindCopy(dimension_name_to_index_, dimension_name, &dimension_index)) { @@ -3954,85 +3925,85 @@ int64 RoutingModel::GetTransitValue(const string& dimension_name, return 0; } } -void RoutingModel::SetCumulVarSoftUpperBound(NodeIndex node, const string& name, +void RoutingModel::SetCumulVarSoftUpperBound(NodeIndex node, const std::string& name, int64 ub, int64 coeff) { GetMutableDimension(name)->SetCumulVarSoftUpperBound(node, ub, coeff); } bool RoutingModel::HasCumulVarSoftUpperBound(NodeIndex node, - const string& name) const { + const std::string& name) const { return HasDimension(name) && GetDimensionOrDie(name).HasCumulVarSoftUpperBound(node); } int64 RoutingModel::GetCumulVarSoftUpperBound(NodeIndex node, - const string& name) const { + const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name).GetCumulVarSoftUpperBound(node) : kint64max; } int64 RoutingModel::GetCumulVarSoftUpperBoundCoefficient( - NodeIndex node, const string& name) const { + NodeIndex node, const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name) .GetCumulVarSoftUpperBoundCoefficient(node) : 0; } void RoutingModel::SetStartCumulVarSoftUpperBound(int vehicle, - const string& name, int64 ub, + const std::string& name, int64 ub, int64 coeff) { GetMutableDimension(name)->SetStartCumulVarSoftUpperBound(vehicle, ub, coeff); } bool RoutingModel::HasStartCumulVarSoftUpperBound(int vehicle, - const string& name) const { + const std::string& name) const { return HasDimension(name) && GetDimensionOrDie(name).HasStartCumulVarSoftUpperBound(vehicle); } int64 RoutingModel::GetStartCumulVarSoftUpperBound(int vehicle, - const string& name) const { + const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name).GetStartCumulVarSoftUpperBound(vehicle) : kint64max; } int64 RoutingModel::GetStartCumulVarSoftUpperBoundCoefficient( - int vehicle, const string& name) const { + int vehicle, const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name) .GetStartCumulVarSoftUpperBoundCoefficient(vehicle) : 0; } -void RoutingModel::SetEndCumulVarSoftUpperBound(int vehicle, const string& name, +void RoutingModel::SetEndCumulVarSoftUpperBound(int vehicle, const std::string& name, int64 ub, int64 coeff) { GetMutableDimension(name)->SetEndCumulVarSoftUpperBound(vehicle, ub, coeff); } bool RoutingModel::HasEndCumulVarSoftUpperBound(int vehicle, - const string& name) const { + const std::string& name) const { return HasDimension(name) && GetDimensionOrDie(name).HasEndCumulVarSoftUpperBound(vehicle); } int64 RoutingModel::GetEndCumulVarSoftUpperBound(int vehicle, - const string& name) const { + const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name).GetEndCumulVarSoftUpperBound(vehicle) : kint64max; } int64 RoutingModel::GetEndCumulVarSoftUpperBoundCoefficient( - int vehicle, const string& name) const { + int vehicle, const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name) .GetEndCumulVarSoftUpperBoundCoefficient(vehicle) : 0; } -IntVar* RoutingModel::CumulVar(int64 index, const string& name) const { +IntVar* RoutingModel::CumulVar(int64 index, const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name).CumulVar(index) : nullptr; } -IntVar* RoutingModel::TransitVar(int64 index, const string& name) const { +IntVar* RoutingModel::TransitVar(int64 index, const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name).TransitVar(index) : nullptr; } -IntVar* RoutingModel::SlackVar(int64 index, const string& name) const { +IntVar* RoutingModel::SlackVar(int64 index, const std::string& name) const { return HasDimension(name) ? GetDimensionOrDie(name).SlackVar(index) : nullptr; } // END(DEPRECATED) -RoutingDimension::RoutingDimension(RoutingModel* model, const string& name) +RoutingDimension::RoutingDimension(RoutingModel* model, const std::string& name) : global_span_cost_coefficient_(0), model_(model), name_(name) { CHECK(model != nullptr); vehicle_span_cost_coefficients_.assign(model->vehicles(), 0); @@ -4071,7 +4042,7 @@ class LightRangeLessOrEqual : public Constraint { virtual ~LightRangeLessOrEqual() {} virtual void Post(); virtual void InitialPropagate(); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual IntVar* Var() { return solver()->MakeIsLessOrEqualVar(left_, right_); } @@ -4120,7 +4091,7 @@ void LightRangeLessOrEqual::CheckRange() { } } -string LightRangeLessOrEqual::DebugString() const { +std::string LightRangeLessOrEqual::DebugString() const { return left_->DebugString() + " < " + right_->DebugString(); } @@ -4363,8 +4334,7 @@ void RoutingDimension::SetupCumulVarSoftUpperBoundCosts( std::vector* cost_elements) const { CHECK(cost_elements != nullptr); Solver* const solver = model_->solver(); - for (int i = 0; i < cumul_var_soft_upper_bound_.size(); ++i) { - const SoftBound& soft_bound = cumul_var_soft_upper_bound_[i]; + for (const SoftBound& soft_bound : cumul_var_soft_upper_bound_) { if (soft_bound.var != nullptr) { IntVar* const cost_var = solver->MakeSemiContinuousExpr( @@ -4431,8 +4401,8 @@ void RoutingDimension::SetupSlackCosts(std::vector* cost_elements) cons model_->AddVariableMaximizedByFinalizer(cumuls_[model_->Start(i)]); model_->AddVariableMinimizedByFinalizer(cumuls_[model_->End(i)]); } - for (int var_index = 0; var_index < model_->Size(); ++var_index) { - model_->AddVariableMinimizedByFinalizer(slacks_[var_index]); + for (IntVar* const slack : slacks_) { + model_->AddVariableMinimizedByFinalizer(slack); } // Add the span cost element for the slacks (the transit component is already diff --git a/src/constraint_solver/routing.h b/src/constraint_solver/routing.h index aa69091272..fd28e2cd60 100644 --- a/src/constraint_solver/routing.h +++ b/src/constraint_solver/routing.h @@ -278,7 +278,7 @@ struct RoutingSearchParameters { bool dfs; // Routing: first solution heuristic. See RoutingStrategyName() in // the code to get a full list. - string first_solution; + std::string first_solution; // Dive (left-branch) for first solution. bool use_first_solution_dive; // Optimization step. @@ -409,7 +409,7 @@ class RoutingModel { // their transit evaluator (the raw version that takes var index, not Node // Index) and their span cost coefficient, we just store those. // This is sorted by the natural operator < (and *not* by DimensionIndex). - std::vector > + std::vector> dimension_transit_evaluator_and_cost_coefficient; explicit CostClass(NodeEvaluator2* arc_cost_evaluator) @@ -478,13 +478,13 @@ class RoutingModel { // (and doesn't create the new dimension). // Takes ownership of the callback 'evaluator'. bool AddDimension(NodeEvaluator2* evaluator, int64 slack_max, int64 capacity, - bool fix_start_cumul_to_zero, const string& name); + bool fix_start_cumul_to_zero, const std::string& name); // Takes ownership of both 'evaluator' and 'vehicle_capacity' callbacks. bool AddDimensionWithVehicleCapacity(NodeEvaluator2* evaluator, int64 slack_max, VehicleEvaluator* vehicle_capacity, bool fix_start_cumul_to_zero, - const string& name); + const std::string& name); // Creates a dimension where the transit variable is constrained to be // equal to 'value'; 'capacity' is the upper bound of the cumul variables. // 'name' is the name used to reference the dimension; this name is used to @@ -492,7 +492,7 @@ class RoutingModel { // Returns false if a dimension with the same name has already been created // (and doesn't create the new dimension). bool AddConstantDimension(int64 value, int64 capacity, - bool fix_start_cumul_to_zero, const string& name); + bool fix_start_cumul_to_zero, const std::string& name); // Creates a dimension where the transit variable is constrained to be // equal to 'values[i]' for node i; 'capacity' is the upper bound of // the cumul variables. 'name' is the name used to reference the dimension; @@ -501,7 +501,7 @@ class RoutingModel { // Returns false if a dimension with the same name has already been created // (and doesn't create the new dimension). bool AddVectorDimension(const int64* values, int64 capacity, - bool fix_start_cumul_to_zero, const string& name); + bool fix_start_cumul_to_zero, const std::string& name); // Creates a dimension where the transit variable is constrained to be // equal to 'values[i][next(i)]' for node i; 'capacity' is the upper bound of // the cumul variables. 'name' is the name used to reference the dimension; @@ -510,27 +510,27 @@ class RoutingModel { // Returns false if a dimension with the same name has already been created // (and doesn't create the new dimension). bool AddMatrixDimension(const int64* const* values, int64 capacity, - bool fix_start_cumul_to_zero, const string& name); + bool fix_start_cumul_to_zero, const std::string& name); // Outputs the names of all dimensions added to the routing engine. // TODO(user): rename. - void GetAllDimensions(std::vector* dimension_names) const; + void GetAllDimensions(std::vector* dimension_names) const; // Returns true if a dimension exists for a given dimension name. - bool HasDimension(const string& dimension_name) const; + bool HasDimension(const std::string& dimension_name) const; // Returns a dimension from its name. Dies if the dimension does not exist. - const RoutingDimension& GetDimensionOrDie(const string& dimension_name) const; + const RoutingDimension& GetDimensionOrDie(const std::string& dimension_name) const; // Returns a dimension from its name. Returns nullptr if the dimension does // not exist. - RoutingDimension* GetMutableDimension(const string& dimension_name) const; + RoutingDimension* GetMutableDimension(const std::string& dimension_name) const; // Set the given dimension as "primary constrained". As of August 2013, this // is only used by ArcIsMoreConstrainedThanArc(). // "dimension" must be the name of an existing dimension, or be empty, in // which case there will not be a primary dimension after this call. - void SetPrimaryConstrainedDimension(const string& dimension_name) { + void SetPrimaryConstrainedDimension(const std::string& dimension_name) { DCHECK(dimension_name.empty() || HasDimension(dimension_name)); primary_constrained_dimension_ = dimension_name; } - // Get the primary constrained dimension, or an empty string if it is unset. - const string& GetPrimaryConstrainedDimension() const { + // Get the primary constrained dimension, or an empty std::string if it is unset. + const std::string& GetPrimaryConstrainedDimension() const { return primary_constrained_dimension_; } // Constrains all nodes to be active (to belong to a route). @@ -607,6 +607,12 @@ class RoutingModel { pickup_delivery_pairs_.push_back( std::make_pair(NodeToIndex(node1), NodeToIndex(node2))); } +#ifndef SWIG + // Returns pickup and delivery pairs currently in the model. + const NodePairs& GetPickupAndDeliveryPairs() const { + return pickup_delivery_pairs_; + } +#endif // Get the "unperformed" penalty of a node. This is only well defined if the // node is only part of a single Disjunction involving only itself, and that // disjunction has a penalty. In all other cases, including forced active @@ -729,11 +735,11 @@ class RoutingModel { // Writes the current solution to a file containing an AssignmentProto. // Returns false if the file cannot be opened or if there is no current // solution. - bool WriteAssignment(const string& file_name) const; + bool WriteAssignment(const std::string& file_name) const; // Reads an assignment from a file and returns the current solution. // Returns nullptr if the file cannot be opened or if the assignment is not // valid. - Assignment* ReadAssignment(const string& file_name); + Assignment* ReadAssignment(const std::string& file_name); // Restores an assignment as a solution in the routing model and returns the // new solution. Returns nullptr if the assignment is not valid. Assignment* RestoreAssignment(const Assignment& solution); @@ -889,8 +895,8 @@ class RoutingModel { // feasible intervals of the CumulVar for dimension "dimension_to_print" // at each step of the routes. // If "dimension_to_print" is omitted, all dimensions will be printed. - string DebugOutputAssignment(const Assignment& solution_assignment, - const string& dimension_to_print) const; + std::string DebugOutputAssignment(const Assignment& solution_assignment, + const std::string& dimension_to_print) const; // Returns the underlying constraint solver. Can be used to add extra // constraints and/or modify search algoithms. @@ -928,11 +934,11 @@ class RoutingModel { // values. See the .cc for the name conversions. The rule of thumb is: // RoutingModel::ROUTING_PATH_CHEAPEST_ARC <-> "PathCheapestArc". static const char* RoutingStrategyName(RoutingStrategy strategy); - static bool ParseRoutingStrategy(const string& strategy_str, + static bool ParseRoutingStrategy(const std::string& strategy_str, RoutingStrategy* strategy); static const char* RoutingMetaheuristicName( RoutingMetaheuristic metaheuristic); - static bool ParseRoutingMetaheuristic(const string& metaheuristic_str, + static bool ParseRoutingMetaheuristic(const std::string& metaheuristic_str, RoutingMetaheuristic* metaheuristic); // DEPRECATED METHODS. @@ -952,31 +958,31 @@ class RoutingModel { int64 GetVehicleClassCost(int64 i, int64 j, int64 c); // GetArcCostForClass() // All the methods below are replaced by public methods of the // RoutingDimension class. See that class. - void SetDimensionTransitCost(const string& d, int64 c); - int64 GetDimensionTransitCost(const string& d) const; - void SetDimensionSpanCost(const string& d, int64 c); - int64 GetDimensionSpanCost(const string& d) const; - int64 GetTransitValue(const string& d, int64 from, int64 to) const; + void SetDimensionTransitCost(const std::string& d, int64 c); + int64 GetDimensionTransitCost(const std::string& d) const; + void SetDimensionSpanCost(const std::string& d, int64 c); + int64 GetDimensionSpanCost(const std::string& d) const; + int64 GetTransitValue(const std::string& d, int64 from, int64 to) const; #ifndef SWIG - const std::vector& CumulVars(const string& dimension_name) const; + const std::vector& CumulVars(const std::string& dimension_name) const; #endif // All the methods below are replaced by public methods with the same name // on the RoutingDimension class. See those. - IntVar* CumulVar(int64 index, const string& dimension_name) const; - IntVar* TransitVar(int64 index, const string& dimension_name) const; - IntVar* SlackVar(int64 index, const string& dimension_name) const; - void SetCumulVarSoftUpperBound(NodeIndex, const string&, int64, int64); - bool HasCumulVarSoftUpperBound(NodeIndex, const string&) const; - int64 GetCumulVarSoftUpperBound(NodeIndex, const string&) const; - int64 GetCumulVarSoftUpperBoundCoefficient(NodeIndex, const string&) const; - void SetStartCumulVarSoftUpperBound(int, const string&, int64, int64); - bool HasStartCumulVarSoftUpperBound(int, const string&) const; - int64 GetStartCumulVarSoftUpperBound(int, const string&) const; - int64 GetStartCumulVarSoftUpperBoundCoefficient(int, const string&) const; - void SetEndCumulVarSoftUpperBound(int, const string&, int64, int64); - bool HasEndCumulVarSoftUpperBound(int, const string&) const; - int64 GetEndCumulVarSoftUpperBound(int, const string&) const; - int64 GetEndCumulVarSoftUpperBoundCoefficient(int, const string&) const; + IntVar* CumulVar(int64 index, const std::string& dimension_name) const; + IntVar* TransitVar(int64 index, const std::string& dimension_name) const; + IntVar* SlackVar(int64 index, const std::string& dimension_name) const; + void SetCumulVarSoftUpperBound(NodeIndex, const std::string&, int64, int64); + bool HasCumulVarSoftUpperBound(NodeIndex, const std::string&) const; + int64 GetCumulVarSoftUpperBound(NodeIndex, const std::string&) const; + int64 GetCumulVarSoftUpperBoundCoefficient(NodeIndex, const std::string&) const; + void SetStartCumulVarSoftUpperBound(int, const std::string&, int64, int64); + bool HasStartCumulVarSoftUpperBound(int, const std::string&) const; + int64 GetStartCumulVarSoftUpperBound(int, const std::string&) const; + int64 GetStartCumulVarSoftUpperBoundCoefficient(int, const std::string&) const; + void SetEndCumulVarSoftUpperBound(int, const std::string&, int64, int64); + bool HasEndCumulVarSoftUpperBound(int, const std::string&) const; + int64 GetEndCumulVarSoftUpperBound(int, const std::string&) const; + int64 GetEndCumulVarSoftUpperBoundCoefficient(int, const std::string&) const; private: // Local search move operator usable in routing. @@ -1032,8 +1038,8 @@ class RoutingModel { int64 slack_max, int64 capacity, VehicleEvaluator* vehicle_capacity, bool fix_start_cumul_to_zero, - const string& dimension_name); - DimensionIndex GetDimensionIndex(const string& dimension_name) const; + const std::string& dimension_name); + DimensionIndex GetDimensionIndex(const std::string& dimension_name) const; void ComputeCostClasses(); int64 GetArcCostForClassInternal(int64 from_index, int64 to_index, CostClassIndex cost_class_index); @@ -1116,9 +1122,9 @@ class RoutingModel { // - or nexts_[i] is bound and is_bound_to_end_[nexts_[i].Value()] is true. std::vector is_bound_to_end_; // Dimensions - hash_map dimension_name_to_index_; + hash_map dimension_name_to_index_; ITIVector dimensions_; - string primary_constrained_dimension_; + std::string primary_constrained_dimension_; // Costs IntVar* cost_; std::vector transit_cost_of_vehicle_; @@ -1297,7 +1303,7 @@ class RoutingDimension { // for a variable index. If no soft upper bound has been set, 0 is returned. int64 GetCumulVarSoftUpperBoundCoefficientFromIndex(int64 index) const; // Returns the name of the dimension. - const string& name() const { return name_; } + const std::string& name() const { return name_; } // Accessors. int64 GetSpanCostCoefficientForVehicle(int vehicle) const { @@ -1320,7 +1326,7 @@ class RoutingDimension { int64 coefficient; }; - RoutingDimension(RoutingModel* model, const string& name); + RoutingDimension(RoutingModel* model, const std::string& name); void Initialize(RoutingModel::VehicleEvaluator* vehicle_capacity, int64 capacity, RoutingModel::NodeEvaluator2* transit_evaluator, @@ -1345,7 +1351,7 @@ class RoutingDimension { std::vector vehicle_span_cost_coefficients_; std::vector cumul_var_soft_upper_bound_; RoutingModel* const model_; - const string name_; + const std::string name_; friend class RoutingModel; @@ -1405,24 +1411,29 @@ class IntVarFilteredDecisionBuilder : public DecisionBuilder { bool Commit(); // Modifies the current solution by setting the variable of index 'index' to // value 'value'. - void SetValue(int index, int64 value) { - delta_->FastAdd(vars_[index])->SetValue(value); - delta_indices_.push_back(index); + void SetValue(int64 index, int64 value) { + if (!is_in_delta_[index]) { + delta_->FastAdd(vars_[index])->SetValue(value); + delta_indices_.push_back(index); + is_in_delta_[index] = true; + } else { + delta_->SetValue(vars_[index], value); + } } // Returns the value of the variable of index 'index' in the last committed // solution. - int64 Value(int index) const { + int64 Value(int64 index) const { return assignment_->IntVarContainer().Element(index).Value(); } // Returns true if the variable of index 'index' is in the current solution. - bool Contains(int index) const { + bool Contains(int64 index) const { return assignment_->IntVarContainer().Element(index).Var() != nullptr; } // Returns the number of variables the decision builder is trying to // instantiate. int Size() const { return vars_.size(); } // Returns the variable of index 'index'. - IntVar* Var(int index) const { return vars_[index]; } + IntVar* Var(int64 index) const { return vars_[index]; } private: // Sets all variables currently bound to their value in the current solution. @@ -1437,6 +1448,7 @@ class IntVarFilteredDecisionBuilder : public DecisionBuilder { Assignment* const assignment_; Assignment* const delta_; std::vector delta_indices_; + std::vector is_in_delta_; const Assignment* const empty_; std::vector filters_; }; @@ -1452,14 +1464,34 @@ class RoutingFilteredDecisionBuilder : public IntVarFilteredDecisionBuilder { bool InitializeRoutes(); // Returns the end of the start chain of vehicle, int GetStartChainEnd(int vehicle) const { return start_chain_ends_[vehicle]; } - // Make nodes in the same disjunction as node unperformed. - void MakeDisjunctionNodesUnperformed(int node); + // Make nodes in the same disjunction as 'node' unperformed. 'node' is a + // variable index corresponding to a node. + void MakeDisjunctionNodesUnperformed(int64 node); // Make all unassigned nodes unperformed. void MakeUnassignedNodesUnperformed(); private: RoutingModel* const model_; - std::vector start_chain_ends_; + std::vector start_chain_ends_; +}; + +class CheapestInsertionFilteredDecisionBuilder + : public RoutingFilteredDecisionBuilder { + public: + // Takes ownership of evaluator. + CheapestInsertionFilteredDecisionBuilder( + RoutingModel* model, ResultCallback2* evaluator, + const std::vector& filters); + virtual ~CheapestInsertionFilteredDecisionBuilder() {} + + protected: + // Inserts 'node' just after 'predecessor', and just before 'successor', + // resulting in the following subsequence: predecessor -> node -> successor. + // If 'node' is part of a disjunction, other nodes of the disjunction are made + // unperformed. + void InsertBetween(int64 node, int64 predecessor, int64 successor); + + std::unique_ptr > evaluator_; }; // Filtered-base decision builder which builds a solution by inserting @@ -1467,7 +1499,7 @@ class RoutingFilteredDecisionBuilder : public IntVarFilteredDecisionBuilder { // an arc-based cost callback. The node selected for insertion is the one // which minimizes insertion cost. class GlobalCheapestInsertionFilteredDecisionBuilder - : public RoutingFilteredDecisionBuilder { + : public CheapestInsertionFilteredDecisionBuilder { public: // Takes ownership of evaluator. GlobalCheapestInsertionFilteredDecisionBuilder( @@ -1479,10 +1511,11 @@ class GlobalCheapestInsertionFilteredDecisionBuilder private: // Computes the possible insertions for all non-inserted nodes and sorts them // according to the current cost evaluator. + // Each std::pair of the output represents an already performed node, + // followed by a non-inserted node that should be set as the "Next" of the + // former. void ComputeEvaluatorSortedInsertions( - std::vector >* sorted_insertions); - - std::unique_ptr > evaluator_; + std::vector >* sorted_insertions); }; // Filtered-base decision builder which builds a solution by inserting @@ -1490,7 +1523,7 @@ class GlobalCheapestInsertionFilteredDecisionBuilder // an arc-based cost callback. Node selected for insertion are considered in // the order they were created in the model. class LocalCheapestInsertionFilteredDecisionBuilder - : public RoutingFilteredDecisionBuilder { + : public CheapestInsertionFilteredDecisionBuilder { public: // Takes ownership of evaluator. LocalCheapestInsertionFilteredDecisionBuilder( @@ -1500,12 +1533,25 @@ class LocalCheapestInsertionFilteredDecisionBuilder virtual bool BuildSolution(); private: - // Computes the possible insertion neighbors of node 'index' and sorts them + // Computes the possible insertion positions of 'node' and sorts them // according to the current cost evaluator. - void ComputeEvaluatorSortedNeighbors(int index, - std::vector* sorted_neighbors); - - std::unique_ptr > evaluator_; + // 'node' is a variable index corresponding to a node, 'sorted_positions' is a + // vector of variable indices corresponding to nodes after which 'node' can be + // inserted. + void ComputeEvaluatorSortedPositions(int64 node, + std::vector* sorted_positions); + // Like ComputeEvaluatorSortedPositions, subject to the additional + // restrictions that the node may only be inserted after node 'start' on the + // route. For convenience, this method also needs the node that is right after + // 'start' on the route. + void ComputeEvaluatorSortedPositionsOnRouteAfter( + int64 node, int64 start, int64 next_after_start, + std::vector* sorted_positions); + // Helper method to the ComputeEvaluatorSortedPositions* methods; the output + // is a list of unsorted pairs of (cost, position to insert the node). + void AppendEvaluatedPositionsAfter( + int64 node_to_insert, int64 start, int64 next_after_start, + std::vector >* valued_positions); }; // Filtered-base decision builder based on the addition heuristic, extending @@ -1531,7 +1577,9 @@ class CheapestAdditionFilteredDecisionBuilder }; // Returns a sorted vector of nodes which can come next in the route after // node 'from'. - virtual void SortPossibleNexts(int from, std::vector* sorted_nexts) = 0; + // 'from' is a variable index corresponding to a node, 'sorted_nexts' is a + // vector of variable indices corresponding to nodes which can follow 'from'. + virtual void SortPossibleNexts(int64 from, std::vector* sorted_nexts) = 0; }; // A CheapestAdditionFilteredDecisionBuilder where the notion of 'cheapest arc' @@ -1548,7 +1596,7 @@ class EvaluatorCheapestAdditionFilteredDecisionBuilder private: // Next nodes are sorted according to the current evaluator. - virtual void SortPossibleNexts(int from, std::vector* sorted_nexts); + virtual void SortPossibleNexts(int64 from, std::vector* sorted_nexts); std::unique_ptr > evaluator_; }; @@ -1567,7 +1615,7 @@ class ComparatorCheapestAdditionFilteredDecisionBuilder private: // Next nodes are sorted according to the current comparator. - virtual void SortPossibleNexts(int from, std::vector* sorted_nexts); + virtual void SortPossibleNexts(int64 from, std::vector* sorted_nexts); std::unique_ptr > comparator_; }; @@ -1594,8 +1642,7 @@ class RoutingLocalSearchFilter : public IntVarLocalSearchFilter { }; RoutingLocalSearchFilter* MakeNodeDisjunctionFilter( - const RoutingModel& routing_model, - Callback1* objective_callback); + const RoutingModel& routing_model, Callback1* objective_callback); RoutingLocalSearchFilter* MakePathCumulFilter( const RoutingModel& routing_model, const RoutingDimension& dimension, Callback1* objective_callback); diff --git a/src/constraint_solver/routing_search.cc b/src/constraint_solver/routing_search.cc index a6809f935a..d0a7b405bf 100644 --- a/src/constraint_solver/routing_search.cc +++ b/src/constraint_solver/routing_search.cc @@ -87,24 +87,26 @@ class NodeDisjunctionFilter : public RoutingLocalSearchFilter { } } int64 new_objective_value = injected_objective_value_ + penalty_value_; - for (ConstIter>> it( - disjunction_active_deltas); - !it.at_end(); ++it) { - const int active_nodes = active_per_disjunction_[it->first] + it->second; + for (const std::pair + disjunction_active_delta : disjunction_active_deltas) { + const int active_nodes = + active_per_disjunction_[disjunction_active_delta.first] + + disjunction_active_delta.second; if (active_nodes > 1) { PropagateObjectiveValue(0); return false; } if (!lns_detected) { - const int64 penalty = routing_model_.GetDisjunctionPenalty(it->first); - if (it->second < 0) { + const int64 penalty = routing_model_.GetDisjunctionPenalty( + disjunction_active_delta.first); + if (disjunction_active_delta.second < 0) { if (penalty < 0) { PropagateObjectiveValue(0); return false; } else { new_objective_value += penalty; } - } else if (it->second > 0) { + } else if (disjunction_active_delta.second > 0) { new_objective_value -= penalty; } } @@ -126,8 +128,7 @@ class NodeDisjunctionFilter : public RoutingLocalSearchFilter { active_per_disjunction_[i] = 0; const std::vector& disjunction_nodes = routing_model_.GetDisjunctionIndices(i); - for (int j = 0; j < disjunction_nodes.size(); ++j) { - const int node = disjunction_nodes[j]; + for (const int64 node : disjunction_nodes) { if (IsVarSynced(node) && Value(node) != node) { ++active_per_disjunction_[i]; } @@ -218,11 +219,10 @@ bool BasePathFilter::Accept(const Assignment* delta, } } // Checking feasibility of touched paths. - const int touched_paths_size = touched_paths.size(); InitializeAcceptPath(); bool accept = true; - for (int i = 0; i < touched_paths_size; ++i) { - if (!AcceptPath(container, touched_paths[i])) { + for (const int touched_path : touched_paths) { + if (!AcceptPath(container, touched_path)) { accept = false; break; } @@ -258,8 +258,7 @@ void BasePathFilter::OnSynchronize() { // Marking unactive nodes (which are not on a path). node_path_starts_.assign(node_path_starts_.size(), kUnassigned); // Marking nodes on a path and storing next values. - for (int i = 0; i < path_starts.size(); ++i) { - const int64 start = path_starts[i]; + for (const int64 start : path_starts) { int node = start; node_path_starts_[node] = start; DCHECK(IsVarSynced(node)); @@ -432,8 +431,8 @@ PathCumulFilter::PathCumulFilter(const RoutingModel& routing_model, capacity_evaluator_(dimension.capacity_evaluator()), delta_max_end_cumul_(kint64min), lns_detected_(false) { - for (int i = 0; i < vehicle_span_cost_coefficients_.size(); ++i) { - if (vehicle_span_cost_coefficients_[i] != 0) { + for (const int64 coefficient : vehicle_span_cost_coefficients_) { + if (coefficient != 0) { has_nonzero_vehicle_span_cost_coefficients_ = true; break; } @@ -441,8 +440,8 @@ PathCumulFilter::PathCumulFilter(const RoutingModel& routing_model, cumul_soft_bounds_.resize(cumuls_.size()); bool has_cumul_soft_bounds = false; bool has_cumul_hard_bounds = false; - for (int i = 0; i < slacks_.size(); ++i) { - if (slacks_[i]->Min() > 0) { + for (const IntVar* const slack : slacks_) { + if (slack->Min() > 0) { has_cumul_hard_bounds = true; break; } @@ -653,9 +652,9 @@ bool PathCumulFilter::FinalizeAcceptPath() { if (ContainsKey(delta_paths_, r)) { continue; } - new_min_start = std::min(ComputePathMaxStartFromEndCumul( - current_path_transits_, r, new_max_end), - new_min_start); + new_min_start = std::min(new_min_start, + ComputePathMaxStartFromEndCumul( + current_path_transits_, r, new_max_end)); } } else if (new_min_start > current_min_start_.cumul_value) { // Delta min start is greater than the current solution one. @@ -709,8 +708,8 @@ int64 PathCumulFilter::ComputePathMaxStartFromEndCumul( RoutingLocalSearchFilter* MakePathCumulFilter( const RoutingModel& routing_model, const RoutingDimension& dimension, Callback1* objective_callback) { - return routing_model.solver()->RevAlloc(new PathCumulFilter( - routing_model, dimension, objective_callback)); + return routing_model.solver()->RevAlloc( + new PathCumulFilter(routing_model, dimension, objective_callback)); } namespace { @@ -734,9 +733,9 @@ NodePrecedenceFilter::NodePrecedenceFilter(const std::vector& nexts, : BasePathFilter(nexts, next_domain_size, nullptr), pair_firsts_(next_domain_size, kUnassigned), pair_seconds_(next_domain_size, kUnassigned) { - for (int i = 0; i < pairs.size(); ++i) { - pair_firsts_[pairs[i].first] = pairs[i].second; - pair_seconds_[pairs[i].second] = pairs[i].first; + for (const std::pair node_pair : pairs) { + pair_firsts_[node_pair.first] = node_pair.second; + pair_seconds_[node_pair.second] = node_pair.first; } } @@ -776,6 +775,9 @@ RoutingLocalSearchFilter* MakeNodePrecedenceFilter( pairs)); } +// TODO(user): Implement same-vehicle filter. Could be merged with node +// precedence filter. + // --- First solution decision builders --- // IntVarFilteredDecisionBuilder @@ -786,6 +788,7 @@ IntVarFilteredDecisionBuilder::IntVarFilteredDecisionBuilder( : vars_(vars), assignment_(solver->MakeAssignment()), delta_(solver->MakeAssignment()), + is_in_delta_(vars_.size(), false), empty_(solver->MakeAssignment()), filters_(filters) { assignment_->MutableIntVarContainer()->Resize(vars_.size()); @@ -818,6 +821,10 @@ bool IntVarFilteredDecisionBuilder::Commit() { } SynchronizeFilters(); } + // Reset is_in_delta to all false. + for (const int delta_index : delta_indices_) { + is_in_delta_[delta_index] = false; + } delta_->Clear(); delta_indices_.clear(); return accept; @@ -835,17 +842,17 @@ void IntVarFilteredDecisionBuilder::SetValuesFromDomains() { } void IntVarFilteredDecisionBuilder::SynchronizeFilters() { - for (int i = 0; i < filters_.size(); ++i) { - filters_[i]->Synchronize(assignment_); + for (LocalSearchFilter* const filter : filters_) { + filter->Synchronize(assignment_); } } bool IntVarFilteredDecisionBuilder::FilterAccept() { // All incremental filters must be called. bool ok = true; - for (int i = 0; i < filters_.size(); ++i) { - if (filters_[i]->IsIncremental() || ok) { - ok = filters_[i]->Accept(delta_, empty_) && ok; + for (LocalSearchFilter* const filter : filters_) { + if (filter->IsIncremental() || ok) { + ok = filter->Accept(delta_, empty_) && ok; } } return ok; @@ -866,8 +873,8 @@ bool RoutingFilteredDecisionBuilder::InitializeRoutes() { // 'start'. Values of starts[node] and ends[node] for other nodes is used // for intermediary computations and do not necessarily reflect actual chain // starts and ends. - std::vector starts(Size() + model()->vehicles(), -1); - std::vector ends(Size() + model()->vehicles(), -1); + std::vector starts(Size() + model()->vehicles(), -1); + std::vector ends(Size() + model()->vehicles(), -1); for (int node = 0; node < Size() + model()->vehicles(); ++node) { // Each node starts as a singleton chain. starts[node] = node; @@ -892,7 +899,7 @@ bool RoutingFilteredDecisionBuilder::InitializeRoutes() { // Set each route to be the concatenation of the chain at its starts and the // chain at its end, without nodes in between. for (int vehicle = 0; vehicle < model()->vehicles(); ++vehicle) { - const int start_chain_end = ends[model()->Start(vehicle)]; + const int64 start_chain_end = ends[model()->Start(vehicle)]; if (!model()->IsEnd(start_chain_end)) { SetValue(start_chain_end, starts[model()->End(vehicle)]); } @@ -901,12 +908,11 @@ bool RoutingFilteredDecisionBuilder::InitializeRoutes() { return Commit(); } -void RoutingFilteredDecisionBuilder::MakeDisjunctionNodesUnperformed(int node) { +void RoutingFilteredDecisionBuilder::MakeDisjunctionNodesUnperformed( + int64 node) { std::vector alternates; model()->GetDisjunctionIndicesFromIndex(node, &alternates); - for (int alternate_index = 0; alternate_index < alternates.size(); - ++alternate_index) { - const int alternate = alternates[alternate_index]; + for (const int alternate : alternates) { if (node != alternate) { SetValue(alternate, alternate); } @@ -921,34 +927,58 @@ void RoutingFilteredDecisionBuilder::MakeUnassignedNodesUnperformed() { } } -// GlobalCheapestInsertionFilteredDecisionBuilder +// CheapestInsertionFilteredDecisionBuilder -GlobalCheapestInsertionFilteredDecisionBuilder:: - GlobalCheapestInsertionFilteredDecisionBuilder( +CheapestInsertionFilteredDecisionBuilder:: + CheapestInsertionFilteredDecisionBuilder( RoutingModel* model, ResultCallback2* evaluator, const std::vector& filters) : RoutingFilteredDecisionBuilder(model, filters), evaluator_(evaluator) { evaluator_->CheckIsRepeatable(); } +void CheapestInsertionFilteredDecisionBuilder::InsertBetween(int64 node, + int64 predecessor, + int64 successor) { + SetValue(predecessor, node); + SetValue(node, successor); + MakeDisjunctionNodesUnperformed(node); +} + +namespace { +template +void SortAndExtractPairSeconds(std::vector>* pairs, + std::vector* sorted_seconds) { + CHECK(pairs != nullptr); + CHECK(sorted_seconds != nullptr); + std::sort(pairs->begin(), pairs->end()); + sorted_seconds->reserve(pairs->size()); + for (const std::pair& p : *pairs) { + sorted_seconds->push_back(p.second); + } +} +} // namespace + +// GlobalCheapestInsertionFilteredDecisionBuilder + +GlobalCheapestInsertionFilteredDecisionBuilder:: + GlobalCheapestInsertionFilteredDecisionBuilder( + RoutingModel* model, ResultCallback2* evaluator, + const std::vector& filters) + : CheapestInsertionFilteredDecisionBuilder(model, evaluator, filters) {} + bool GlobalCheapestInsertionFilteredDecisionBuilder::BuildSolution() { if (!InitializeRoutes()) { return false; } // Node insertions currently being considered. - std::vector> insertions; + std::vector> insertions; bool found = true; while (found) { found = false; ComputeEvaluatorSortedInsertions(&insertions); - for (int index = 0; index < insertions.size(); ++index) { - const int node = insertions[index].first; - const int insertion = insertions[index].second; - const int insertion_next = Value(insertion); - // Insert "node" after "insertion", and before "insertion_next". - SetValue(insertion, node); - SetValue(node, insertion_next); - MakeDisjunctionNodesUnperformed(node); + for (const std::pair insertion : insertions) { + InsertBetween(insertion.second, insertion.first, Value(insertion.first)); if (Commit()) { found = true; break; @@ -961,10 +991,10 @@ bool GlobalCheapestInsertionFilteredDecisionBuilder::BuildSolution() { void GlobalCheapestInsertionFilteredDecisionBuilder:: ComputeEvaluatorSortedInsertions( - std::vector>* sorted_insertions) { + std::vector>* sorted_insertions) { CHECK(sorted_insertions != nullptr); sorted_insertions->clear(); - std::vector>> valued_insertions; + std::vector>> valued_insertions; for (int node = 0; node < model()->Size(); ++node) { if (Contains(node)) { continue; @@ -975,17 +1005,13 @@ void GlobalCheapestInsertionFilteredDecisionBuilder:: const int64 insert_before = Value(insert_after); valued_insertions.push_back( std::make_pair(evaluator_->Run(insert_after, node) + - evaluator_->Run(node, insert_before), - std::make_pair(node, insert_after))); + evaluator_->Run(node, insert_before), + std::make_pair(insert_after, node))); insert_after = insert_before; } } } - std::sort(valued_insertions.begin(), valued_insertions.end()); - sorted_insertions->reserve(valued_insertions.size()); - for (int i = 0; i < valued_insertions.size(); ++i) { - sorted_insertions->push_back(valued_insertions[i].second); - } + SortAndExtractPairSeconds(&valued_insertions, sorted_insertions); } // LocalCheapestInsertionFilteredDecisionBuilder @@ -994,28 +1020,65 @@ LocalCheapestInsertionFilteredDecisionBuilder:: LocalCheapestInsertionFilteredDecisionBuilder( RoutingModel* model, ResultCallback2* evaluator, const std::vector& filters) - : RoutingFilteredDecisionBuilder(model, filters), evaluator_(evaluator) { - evaluator_->CheckIsRepeatable(); -} + : CheapestInsertionFilteredDecisionBuilder(model, evaluator, filters) {} bool LocalCheapestInsertionFilteredDecisionBuilder::BuildSolution() { if (!InitializeRoutes()) { return false; } - // Neighbors of the node currently being inserted. - std::vector neighbors; - for (int node = 0; node < model()->Size(); ++node) { - if (Contains(node)) { + // Marking if we've tried inserting a node. + std::vector visited(model()->Size(), false); + // Possible positions where the current node can inserted. + std::vector insertion_positions; + // Possible positions where its associated delivery node can inserted (if the + // current node has one). + std::vector delivery_insertion_positions; + // Iterating on pickup and delivery pairs + const RoutingModel::NodePairs& node_pairs = + model()->GetPickupAndDeliveryPairs(); + for (const std::pair node_pair : node_pairs) { + const int64 pickup = node_pair.first; + const int64 delivery = node_pair.second; + // If either is already in the solution, let it be inserted in the standard + // node insertion loop. + if (Contains(pickup) || Contains(delivery)) { continue; } - ComputeEvaluatorSortedNeighbors(node, &neighbors); - for (int index = 0; index < neighbors.size(); ++index) { - const int insertion = neighbors[index]; - const int insertion_next = Value(insertion); - // Insert "node" after "insertion", and before "insertion_next". - SetValue(insertion, node); - SetValue(node, insertion_next); - MakeDisjunctionNodesUnperformed(node); + visited[pickup] = true; + visited[delivery] = true; + ComputeEvaluatorSortedPositions(pickup, &insertion_positions); + for (const int64 pickup_insertion : insertion_positions) { + const int pickup_insertion_next = Value(pickup_insertion); + ComputeEvaluatorSortedPositionsOnRouteAfter( + delivery, pickup, pickup_insertion_next, + &delivery_insertion_positions); + bool found = false; + for (const int64 delivery_insertion : delivery_insertion_positions) { + InsertBetween(pickup, pickup_insertion, pickup_insertion_next); + const int64 delivery_insertion_next = + (delivery_insertion == pickup_insertion) + ? pickup + : (delivery_insertion == pickup) ? pickup_insertion_next + : Value(delivery_insertion); + InsertBetween(delivery, delivery_insertion, delivery_insertion_next); + if (Commit()) { + found = true; + break; + } + } + if (found) { + break; + } + } + } + // Iterating on remaining nodes. + for (int node = 0; node < model()->Size(); ++node) { + if (Contains(node) || visited[node]) { + continue; + } + ComputeEvaluatorSortedPositions(node, &insertion_positions); + for (const int64 insertion : insertion_positions) { + InsertBetween(node, insertion, Value(insertion)); if (Commit()) { break; } @@ -1026,30 +1089,53 @@ bool LocalCheapestInsertionFilteredDecisionBuilder::BuildSolution() { } void -LocalCheapestInsertionFilteredDecisionBuilder::ComputeEvaluatorSortedNeighbors( - int index, std::vector* sorted_neighbors) { - CHECK(sorted_neighbors != nullptr); - CHECK(!Contains(index)); - sorted_neighbors->clear(); +LocalCheapestInsertionFilteredDecisionBuilder::ComputeEvaluatorSortedPositions( + int64 node, std::vector* sorted_positions) { + CHECK(sorted_positions != nullptr); + CHECK(!Contains(node)); + sorted_positions->clear(); const int size = model()->Size(); - if (index < size) { - std::vector> valued_neighbors; + if (node < size) { + std::vector> valued_positions; for (int vehicle = 0; vehicle < model()->vehicles(); ++vehicle) { - int64 insert_after = model()->Start(vehicle); - while (!model()->IsEnd(insert_after)) { - const int64 insert_before = Value(insert_after); - valued_neighbors.push_back( - std::make_pair(evaluator_->Run(insert_after, index) + - evaluator_->Run(index, insert_before), - insert_after)); - insert_after = insert_before; - } - } - std::sort(valued_neighbors.begin(), valued_neighbors.end()); - sorted_neighbors->reserve(valued_neighbors.size()); - for (int i = 0; i < valued_neighbors.size(); ++i) { - sorted_neighbors->push_back(valued_neighbors[i].second); + const int64 start = model()->Start(vehicle); + AppendEvaluatedPositionsAfter(node, start, Value(start), + &valued_positions); } + SortAndExtractPairSeconds(&valued_positions, sorted_positions); + } +} + +void LocalCheapestInsertionFilteredDecisionBuilder:: + ComputeEvaluatorSortedPositionsOnRouteAfter( + int64 node, int64 start, int64 next_after_start, + std::vector* sorted_positions) { + CHECK(sorted_positions != nullptr); + CHECK(!Contains(node)); + sorted_positions->clear(); + const int size = model()->Size(); + if (node < size) { + std::vector> valued_positions; + AppendEvaluatedPositionsAfter(node, start, next_after_start, + &valued_positions); + SortAndExtractPairSeconds(&valued_positions, sorted_positions); + } +} + +void +LocalCheapestInsertionFilteredDecisionBuilder::AppendEvaluatedPositionsAfter( + int64 node_to_insert, int64 start, int64 next_after_start, + std::vector>* valued_positions) { + CHECK(valued_positions != nullptr); + int64 insert_after = start; + while (!model()->IsEnd(insert_after)) { + const int64 insert_before = + (insert_after == start) ? next_after_start : Value(insert_after); + valued_positions->push_back( + std::make_pair(evaluator_->Run(insert_after, node_to_insert) + + evaluator_->Run(node_to_insert, insert_before), + insert_after)); + insert_after = insert_before; } } @@ -1072,12 +1158,10 @@ bool CheapestAdditionFilteredDecisionBuilder::BuildSolution() { sorted_vehicles[vehicle] = vehicle; } std::sort(sorted_vehicles.begin(), sorted_vehicles.end(), - PartialRoutesAndLargeVehicleIndicesFirst(*this)); + PartialRoutesAndLargeVehicleIndicesFirst(*this)); // Neighbors of the node currently being extended. - std::vector neighbors; - for (int vehicle_index = 0; vehicle_index < sorted_vehicles.size(); - ++vehicle_index) { - const int vehicle = sorted_vehicles[vehicle_index]; + std::vector neighbors; + for (const int vehicle : sorted_vehicles) { int64 index = GetStartChainEnd(vehicle); const int64 end = model()->End(vehicle); bool found = true; @@ -1085,8 +1169,7 @@ bool CheapestAdditionFilteredDecisionBuilder::BuildSolution() { while (found && !model()->IsEnd(index)) { found = false; SortPossibleNexts(index, &neighbors); - for (int next_index = 0; next_index < neighbors.size(); ++next_index) { - const int next = neighbors[next_index]; + for (const int64 next : neighbors) { if (model()->IsEnd(next) && next != end) { continue; } @@ -1135,17 +1218,17 @@ EvaluatorCheapestAdditionFilteredDecisionBuilder:: } void EvaluatorCheapestAdditionFilteredDecisionBuilder::SortPossibleNexts( - int from, std::vector* sorted_nexts) { + int64 from, std::vector* sorted_nexts) { CHECK(sorted_nexts != nullptr); const std::vector& nexts = model()->Nexts(); sorted_nexts->clear(); const int size = model()->Size(); if (from < size) { - std::vector> valued_neighbors; + std::vector> valued_neighbors; IntVar* const next = nexts[from]; std::unique_ptr it(next->MakeDomainIterator(false)); for (it->Init(); it->Ok(); it->Next()) { - const int value = it->Value(); + const int64 value = it->Value(); if (value != from && (value >= size || !Contains(value))) { // Tie-breaking on largest node index to mimic the behavior of // CheapestValueSelector (search.cc). @@ -1155,8 +1238,8 @@ void EvaluatorCheapestAdditionFilteredDecisionBuilder::SortPossibleNexts( } std::sort(valued_neighbors.begin(), valued_neighbors.end()); sorted_nexts->reserve(valued_neighbors.size()); - for (int i = 0; i < valued_neighbors.size(); ++i) { - sorted_nexts->push_back(-valued_neighbors[i].second); + for (const std::pair neighbor : valued_neighbors) { + sorted_nexts->push_back(-neighbor.second); } } } @@ -1190,7 +1273,7 @@ class ArcComparator { } // namespace void ComparatorCheapestAdditionFilteredDecisionBuilder::SortPossibleNexts( - int from, std::vector* sorted_nexts) { + int64 from, std::vector* sorted_nexts) { CHECK(sorted_nexts != nullptr); const std::vector& nexts = model()->Nexts(); sorted_nexts->clear(); diff --git a/src/constraint_solver/sched_constraints.cc b/src/constraint_solver/sched_constraints.cc index 205a5a7c89..9bf7764090 100644 --- a/src/constraint_solver/sched_constraints.cc +++ b/src/constraint_solver/sched_constraints.cc @@ -63,13 +63,13 @@ class TreeArrayConstraint : public Constraint { root_node_ = &tree_[0][0]; } - string DebugStringInternal(const string& name) const { + std::string DebugStringInternal(const std::string& name) const { return StringPrintf("Cover(%s) == %s", JoinDebugStringPtr(vars_, ", ").c_str(), target_var_->DebugString().c_str()); } - void AcceptInternal(const string& name, ModelVisitor* const visitor) const { + void AcceptInternal(const std::string& name, ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(name, this); visitor->VisitIntervalArrayArgument(ModelVisitor::kIntervalsArgument, vars_); @@ -476,7 +476,7 @@ class CoverConstraint : public TreeArrayConstraint { PropagateRoot(); } - string DebugString() const { + std::string DebugString() const { return DebugStringInternal(ModelVisitor::kCover); } @@ -567,7 +567,7 @@ class IntervalEquality : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Equality(%s, %s)", var1_->DebugString().c_str(), var2_->DebugString().c_str()); } diff --git a/src/constraint_solver/sched_expr.cc b/src/constraint_solver/sched_expr.cc index a47e7f1b86..895d7c505c 100644 --- a/src/constraint_solver/sched_expr.cc +++ b/src/constraint_solver/sched_expr.cc @@ -50,7 +50,7 @@ class IntervalVarStartExpr : public BaseIntExpr { virtual void WhenRange(Demon* d) { interval_->WhenStartRange(d); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("start(%s)", interval_->DebugString().c_str()); } @@ -89,7 +89,7 @@ class IntervalVarEndExpr : public BaseIntExpr { virtual void WhenRange(Demon* d) { interval_->WhenEndRange(d); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("end(%s)", interval_->DebugString().c_str()); } @@ -128,7 +128,7 @@ class IntervalVarDurationExpr : public BaseIntExpr { virtual void WhenRange(Demon* d) { interval_->WhenDurationRange(d); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("duration(%s)", interval_->DebugString().c_str()); } diff --git a/src/constraint_solver/sched_search.cc b/src/constraint_solver/sched_search.cc index 80fb7b87ec..6697bf4f5f 100644 --- a/src/constraint_solver/sched_search.cc +++ b/src/constraint_solver/sched_search.cc @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include +#include #include #include @@ -36,7 +36,7 @@ int64 IndexToValue(int64 index) { return index + 1; } // that ranked_first, ranked_last, and unperformed are truly disjoint. SequenceVar::SequenceVar(Solver* const s, const std::vector& intervals, - const std::vector& nexts, const string& name) + const std::vector& nexts, const std::string& name) : PropagationBaseObject(s), intervals_(intervals), nexts_(nexts), @@ -52,7 +52,7 @@ IntervalVar* SequenceVar::Interval(int index) const { IntVar* SequenceVar::Next(int index) const { return nexts_[index]; } -string SequenceVar::DebugString() const { +std::string SequenceVar::DebugString() const { int64 hmin, hmax, dmin, dmax; HorizonRange(&hmin, &hmax); DurationRange(&dmin, &dmax); @@ -403,7 +403,7 @@ class ScheduleOrPostpone : public Decision { visitor->VisitScheduleOrPostpone(var_, est_.Value()); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("ScheduleOrPostpone(%s at %" GG_LL_FORMAT "d)", var_->DebugString().c_str(), est_.Value()); } @@ -453,7 +453,7 @@ class SetTimesForward : public DecisionBuilder { vars_[support], vars_[support]->StartMin(), &markers_[support])); } - virtual string DebugString() const { return "SetTimesForward()"; } + virtual std::string DebugString() const { return "SetTimesForward()"; } virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitExtension(ModelVisitor::kVariableGroupExtension); @@ -484,7 +484,7 @@ class RankFirst : public Decision { visitor->VisitRankFirstInterval(sequence_, index_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("RankFirst(%s, %d)", sequence_->DebugString().c_str(), index_); } @@ -508,7 +508,7 @@ class RankLast : public Decision { visitor->VisitRankLastInterval(sequence_, index_); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("RankLast(%s, %d)", sequence_->DebugString().c_str(), index_); } diff --git a/src/constraint_solver/search.cc b/src/constraint_solver/search.cc index 8f0d84105d..425a19425e 100644 --- a/src/constraint_solver/search.cc +++ b/src/constraint_solver/search.cc @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include #include #include "base/hash.h" #include @@ -53,7 +52,7 @@ namespace operations_research { // ---------- Search Log --------- SearchLog::SearchLog(Solver* const s, OptimizeVar* const obj, IntVar* const var, - ResultCallback* display_callback, int period) + ResultCallback* display_callback, int period) : SearchMonitor(s), period_(period), timer_(new WallTimer), @@ -77,10 +76,10 @@ SearchLog::SearchLog(Solver* const s, OptimizeVar* const obj, IntVar* const var, SearchLog::~SearchLog() {} -string SearchLog::DebugString() const { return "SearchLog"; } +std::string SearchLog::DebugString() const { return "SearchLog"; } void SearchLog::EnterSearch() { - const string buffer = + const std::string buffer = StringPrintf("Start search (%s)", MemoryUsage().c_str()); OutputLine(buffer); timer_->Restart(); @@ -93,7 +92,7 @@ void SearchLog::ExitSearch() { if (ms == 0) { ms = 1; } - const string buffer = StringPrintf( + const std::string buffer = StringPrintf( "End search (time = %" GG_LL_FORMAT "d ms, branches = %" GG_LL_FORMAT "d, failures = %" GG_LL_FORMAT "d, %s, speed = %" GG_LL_FORMAT "d branches/s)", @@ -105,7 +104,7 @@ void SearchLog::ExitSearch() { bool SearchLog::AtSolution() { Maintain(); const int depth = solver()->SearchDepth(); - string obj_str = ""; + std::string obj_str = ""; int64 current = 0; bool objective_updated = false; if (obj_ != nullptr) { @@ -131,7 +130,7 @@ bool SearchLog::AtSolution() { objective_max_ = current; } } - string log; + std::string log; StringAppendF(&log, "Solution #%d (%stime = %" GG_LL_FORMAT "d ms, branches = %" GG_LL_FORMAT "d," @@ -162,7 +161,7 @@ bool SearchLog::AtSolution() { void SearchLog::BeginFail() { Maintain(); } void SearchLog::NoMoreSolutions() { - string buffer = StringPrintf("Finished search tree (time = %" GG_LL_FORMAT + std::string buffer = StringPrintf("Finished search tree (time = %" GG_LL_FORMAT "d ms, branches = %" GG_LL_FORMAT "d," " failures = %" GG_LL_FORMAT "d", @@ -194,7 +193,7 @@ void SearchLog::RefuteDecision(Decision* const d) { } void SearchLog::OutputDecision() { - string buffer = StringPrintf("%" GG_LL_FORMAT "d branches, %" GG_LL_FORMAT + std::string buffer = StringPrintf("%" GG_LL_FORMAT "d branches, %" GG_LL_FORMAT "d ms, %" GG_LL_FORMAT "d failures", solver()->branches(), timer_->GetInMs(), solver()->failures()); @@ -231,14 +230,14 @@ void SearchLog::BeginInitialPropagation() { tick_ = timer_->GetInMs(); } void SearchLog::EndInitialPropagation() { const int64 delta = std::max(timer_->GetInMs() - tick_, 0LL); - const string buffer = + const std::string buffer = StringPrintf("Root node processed (time = %" GG_LL_FORMAT "d ms, constraints = %d, %s)", delta, solver()->constraints(), MemoryUsage().c_str()); OutputLine(buffer); } -void SearchLog::OutputLine(const string& line) { +void SearchLog::OutputLine(const std::string& line) { if (FLAGS_cp_log_to_vlog) { VLOG(1) << line; } else { @@ -246,7 +245,7 @@ void SearchLog::OutputLine(const string& line) { } } -string SearchLog::MemoryUsage() { +std::string SearchLog::MemoryUsage() { static const int64 kDisplayThreshold = 2; static const int64 kKiloByte = 1024; static const int64 kMegaByte = kKiloByte * kKiloByte; @@ -275,13 +274,13 @@ SearchMonitor* Solver::MakeSearchLog(int period, IntVar* const var) { } SearchMonitor* Solver::MakeSearchLog(int period, - ResultCallback* display_callback) { + ResultCallback* display_callback) { return RevAlloc( new SearchLog(this, nullptr, nullptr, display_callback, period)); } SearchMonitor* Solver::MakeSearchLog(int period, IntVar* const var, - ResultCallback* display_callback) { + ResultCallback* display_callback) { return RevAlloc(new SearchLog(this, nullptr, var, display_callback, period)); } @@ -290,7 +289,7 @@ SearchMonitor* Solver::MakeSearchLog(int period, OptimizeVar* const obj) { } SearchMonitor* Solver::MakeSearchLog(int period, OptimizeVar* const obj, - ResultCallback* display_callback) { + ResultCallback* display_callback) { return RevAlloc(new SearchLog(this, obj, nullptr, display_callback, period)); } @@ -299,7 +298,7 @@ SearchMonitor* Solver::MakeSearchLog(int period, OptimizeVar* const obj, namespace { class SearchTrace : public SearchMonitor { public: - SearchTrace(Solver* const s, const string& prefix) + SearchTrace(Solver* const s, const std::string& prefix) : SearchMonitor(s), prefix_(prefix) {} virtual ~SearchTrace() {} @@ -355,14 +354,14 @@ class SearchTrace : public SearchMonitor { LOG(INFO) << prefix_ << " NoMoreSolutions()"; } - virtual string DebugString() const { return "SearchTrace"; } + virtual std::string DebugString() const { return "SearchTrace"; } private: - const string prefix_; + const std::string prefix_; }; } // namespace -SearchMonitor* Solver::MakeSearchTrace(const string& prefix) { +SearchMonitor* Solver::MakeSearchTrace(const std::string& prefix) { return RevAlloc(new SearchTrace(this, prefix)); } @@ -423,7 +422,7 @@ class ComposeDecisionBuilder : public CompositeDecisionBuilder { explicit ComposeDecisionBuilder(const std::vector& dbs); ~ComposeDecisionBuilder(); virtual Decision* Next(Solver* const s); - virtual string DebugString() const; + virtual std::string DebugString() const; private: int start_index_; @@ -450,7 +449,7 @@ Decision* ComposeDecisionBuilder::Next(Solver* const s) { return nullptr; } -string ComposeDecisionBuilder::DebugString() const { +std::string ComposeDecisionBuilder::DebugString() const { return StringPrintf("ComposeDecisionBuilder(%s)", JoinDebugStringPtr(builders_, ", ").c_str()); } @@ -505,7 +504,7 @@ class TryDecision : public Decision { virtual ~TryDecision(); virtual void Apply(Solver* const solver); virtual void Refute(Solver* const solver); - virtual string DebugString() const { return "TryDecision"; } + virtual std::string DebugString() const { return "TryDecision"; } private: TryDecisionBuilder* const try_builder_; @@ -517,7 +516,7 @@ class TryDecisionBuilder : public CompositeDecisionBuilder { explicit TryDecisionBuilder(const std::vector& dbs); virtual ~TryDecisionBuilder(); virtual Decision* Next(Solver* const s); - virtual string DebugString() const; + virtual std::string DebugString() const; void AdvanceToNextBuilder(Solver* const solver); private: @@ -564,7 +563,7 @@ Decision* TryDecisionBuilder::Next(Solver* const solver) { } } -string TryDecisionBuilder::DebugString() const { +std::string TryDecisionBuilder::DebugString() const { return StringPrintf( "TryDecisionBuilder(%s)", JoinDebugStringPtr(builders_, ", ").c_str()); } @@ -634,7 +633,7 @@ class VariableSelector : public BaseObject { explicit VariableSelector(const std::vector& vars) : vars_(vars) {} virtual ~VariableSelector() {} virtual IntVar* Select(Solver* const s, int64* id) = 0; - string VarDebugString() const { + std::string VarDebugString() const { return StringPrintf("(%s)", JoinDebugStringPtr(vars_, ", ").c_str()); } void Accept(ModelVisitor* const visitor) const { @@ -656,7 +655,7 @@ class FirstUnboundSelector : public VariableSelector { : VariableSelector(vars), first_(0) {} virtual ~FirstUnboundSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "ChooseFirstUnbound"; } + virtual std::string DebugString() const { return "ChooseFirstUnbound"; } private: int first_; @@ -684,7 +683,7 @@ class MinSizeLowestMinSelector : public VariableSelector { : VariableSelector(vars) {} virtual ~MinSizeLowestMinSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "MinSizeLowestMinSelector"; } + virtual std::string DebugString() const { return "MinSizeLowestMinSelector"; } }; IntVar* MinSizeLowestMinSelector::Select(Solver* const s, int64* id) { @@ -721,7 +720,7 @@ class MinSizeHighestMinSelector : public VariableSelector { : VariableSelector(vars) {} virtual ~MinSizeHighestMinSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "MinSizeHighestMinSelector"; } + virtual std::string DebugString() const { return "MinSizeHighestMinSelector"; } }; IntVar* MinSizeHighestMinSelector::Select(Solver* const s, int64* id) { @@ -758,7 +757,7 @@ class MinSizeLowestMaxSelector : public VariableSelector { : VariableSelector(vars) {} virtual ~MinSizeLowestMaxSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "MinSizeLowestMaxSelector"; } + virtual std::string DebugString() const { return "MinSizeLowestMaxSelector"; } }; IntVar* MinSizeLowestMaxSelector::Select(Solver* const s, int64* id) { @@ -795,7 +794,7 @@ class MinSizeHighestMaxSelector : public VariableSelector { : VariableSelector(vars) {} virtual ~MinSizeHighestMaxSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "MinSizeHighestMaxSelector"; } + virtual std::string DebugString() const { return "MinSizeHighestMaxSelector"; } }; IntVar* MinSizeHighestMaxSelector::Select(Solver* const s, int64* id) { @@ -832,7 +831,7 @@ class LowestMinSelector : public VariableSelector { : VariableSelector(vars) {} virtual ~LowestMinSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "LowestMinSelector"; } + virtual std::string DebugString() const { return "LowestMinSelector"; } }; IntVar* LowestMinSelector::Select(Solver* const s, int64* id) { @@ -866,7 +865,7 @@ class HighestMaxSelector : public VariableSelector { : VariableSelector(vars) {} virtual ~HighestMaxSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "HighestMaxSelector"; } + virtual std::string DebugString() const { return "HighestMaxSelector"; } }; IntVar* HighestMaxSelector::Select(Solver* const s, int64* id) { @@ -900,7 +899,7 @@ class LowestSizeSelector : public VariableSelector { : VariableSelector(vars) {} virtual ~LowestSizeSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "MinSizeSelector"; } + virtual std::string DebugString() const { return "MinSizeSelector"; } }; IntVar* LowestSizeSelector::Select(Solver* const s, int64* id) { @@ -935,7 +934,7 @@ class HighestSizeSelector : public VariableSelector { : VariableSelector(vars) {} virtual ~HighestSizeSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "MaxSizeSelector"; } + virtual std::string DebugString() const { return "MaxSizeSelector"; } }; IntVar* HighestSizeSelector::Select(Solver* const s, int64* id) { @@ -974,7 +973,7 @@ class HighestRegretSelectorOnMin : public VariableSelector { } virtual ~HighestRegretSelectorOnMin() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "MaxRegretSelector"; } + virtual std::string DebugString() const { return "MaxRegretSelector"; } int64 ComputeRegret(int index) const { DCHECK(!vars_[index]->Bound()); @@ -1021,7 +1020,7 @@ class RandomSelector : public VariableSelector { : VariableSelector(vars) {} virtual ~RandomSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "RandomSelector"; } + virtual std::string DebugString() const { return "RandomSelector"; } }; IntVar* RandomSelector::Select(Solver* const s, int64* id) { @@ -1047,7 +1046,7 @@ class CheapestVarSelector : public VariableSelector { : VariableSelector(vars), var_evaluator_(var_eval) {} virtual ~CheapestVarSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "CheapestVarSelector"; } + virtual std::string DebugString() const { return "CheapestVarSelector"; } private: std::unique_ptr > var_evaluator_; @@ -1086,7 +1085,7 @@ class PathSelector : public VariableSelector { : VariableSelector(vars), first_(kint64max) {} virtual ~PathSelector() {} virtual IntVar* Select(Solver* const s, int64* id); - virtual string DebugString() const { return "ChooseNextOnPath"; } + virtual std::string DebugString() const { return "ChooseNextOnPath"; } private: bool UpdateIndex(int64* index) const; @@ -1184,7 +1183,7 @@ class MinValueSelector : public ValueSelector { MinValueSelector() {} virtual ~MinValueSelector() {} virtual int64 Select(const IntVar* const v, int64 id) { return v->Min(); } - string DebugString() const { return "AssignMin"; } + std::string DebugString() const { return "AssignMin"; } }; // ----- Select max ----- @@ -1194,7 +1193,7 @@ class MaxValueSelector : public ValueSelector { MaxValueSelector() {} virtual ~MaxValueSelector() {} virtual int64 Select(const IntVar* const v, int64 id) { return v->Max(); } - string DebugString() const { return "AssignMax"; } + std::string DebugString() const { return "AssignMax"; } }; // ----- Select random ----- @@ -1204,7 +1203,7 @@ class RandomValueSelector : public ValueSelector { RandomValueSelector() {} virtual ~RandomValueSelector() {} virtual int64 Select(const IntVar* const v, int64 id); - string DebugString() const { return "AssignRandom"; } + std::string DebugString() const { return "AssignRandom"; } }; int64 RandomValueSelector::Select(const IntVar* const v, int64 id) { @@ -1255,7 +1254,7 @@ class CenterValueSelector : public ValueSelector { CenterValueSelector() {} virtual ~CenterValueSelector() {} virtual int64 Select(const IntVar* const v, int64 id); - string DebugString() const { return "AssignCenter"; } + std::string DebugString() const { return "AssignCenter"; } }; int64 CenterValueSelector::Select(const IntVar* const v, int64 id) { @@ -1285,13 +1284,13 @@ int64 CenterValueSelector::Select(const IntVar* const v, int64 id) { class SplitValueSelector : public ValueSelector { public: - explicit SplitValueSelector(const string& name) : name_(name) {} + explicit SplitValueSelector(const std::string& name) : name_(name) {} virtual ~SplitValueSelector() {} virtual int64 Select(const IntVar* const v, int64 id); - string DebugString() const { return name_; } + std::string DebugString() const { return name_; } private: - const string name_; + const std::string name_; }; int64 SplitValueSelector::Select(const IntVar* const v, int64 id) { @@ -1311,7 +1310,7 @@ class CheapestValueSelector : public ValueSelector { : eval_(eval), tie_breaker_(tie_breaker) {} virtual ~CheapestValueSelector() {} virtual int64 Select(const IntVar* const v, int64 id); - string DebugString() const { return "CheapestValue"; } + std::string DebugString() const { return "CheapestValue"; } private: std::unique_ptr > eval_; @@ -1359,7 +1358,7 @@ class BestValueByComparisonSelector : public ValueSelector { : comparator_(comparator) {} virtual ~BestValueByComparisonSelector() {} virtual int64 Select(const IntVar* const v, int64 id); - string DebugString() const { return "BestValueByComparisonSelector"; } + std::string DebugString() const { return "BestValueByComparisonSelector"; } private: std::unique_ptr > comparator_; @@ -1393,7 +1392,7 @@ class VariableAssignmentSelector : public BaseVariableAssignmentSelector { virtual IntVar* SelectVariable(Solver* const s, int64* id) { return var_selector_->Select(s, id); } - string DebugString() const; + std::string DebugString() const; virtual void Accept(ModelVisitor* const visitor) const { var_selector_->Accept(visitor); @@ -1404,7 +1403,7 @@ class VariableAssignmentSelector : public BaseVariableAssignmentSelector { ValueSelector* const value_selector_; }; -string VariableAssignmentSelector::DebugString() const { +std::string VariableAssignmentSelector::DebugString() const { return var_selector_->DebugString() + "_" + value_selector_->DebugString() + var_selector_->VarDebugString(); } @@ -1432,7 +1431,7 @@ class BaseEvaluatorSelector : public BaseVariableAssignmentSelector { int64 value; }; - string DebugStringInternal(const string& name) const { + std::string DebugStringInternal(const std::string& name) const { return StringPrintf("%s(%s)", name.c_str(), JoinDebugStringPtr(vars_, ", ").c_str()); } @@ -1456,7 +1455,7 @@ class DynamicEvaluatorSelector : public BaseEvaluatorSelector { virtual ~DynamicEvaluatorSelector() {} virtual int64 SelectValue(const IntVar* const var, int64 id); virtual IntVar* SelectVariable(Solver* const s, int64* id); - virtual string DebugString() const; + virtual std::string DebugString() const; private: int first_; @@ -1511,7 +1510,7 @@ IntVar* DynamicEvaluatorSelector::SelectVariable(Solver* const s, int64* id) { } } -string DynamicEvaluatorSelector::DebugString() const { +std::string DynamicEvaluatorSelector::DebugString() const { return DebugStringInternal("AssignVariablesOnDynamicEvaluator"); } @@ -1524,7 +1523,7 @@ class StaticEvaluatorSelector : public BaseEvaluatorSelector { virtual ~StaticEvaluatorSelector() {} virtual int64 SelectValue(const IntVar* const var, int64 id); virtual IntVar* SelectVariable(Solver* const s, int64* id); - virtual string DebugString() const; + virtual std::string DebugString() const; private: class Compare { @@ -1599,7 +1598,7 @@ IntVar* StaticEvaluatorSelector::SelectVariable(Solver* const s, int64* id) { return nullptr; } -string StaticEvaluatorSelector::DebugString() const { +std::string StaticEvaluatorSelector::DebugString() const { return DebugStringInternal("AssignVariablesOnStaticEvaluator"); } @@ -1611,7 +1610,7 @@ class AssignOneVariableValue : public Decision { virtual ~AssignOneVariableValue() {} virtual void Apply(Solver* const s); virtual void Refute(Solver* const s); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual void Accept(DecisionVisitor* const visitor) const { visitor->VisitSetVariableValue(var_, value_); } @@ -1624,7 +1623,7 @@ class AssignOneVariableValue : public Decision { AssignOneVariableValue::AssignOneVariableValue(IntVar* const v, int64 val) : var_(v), value_(val) {} -string AssignOneVariableValue::DebugString() const { +std::string AssignOneVariableValue::DebugString() const { return StringPrintf("[%s == %" GG_LL_FORMAT "d]", var_->DebugString().c_str(), value_); } @@ -1649,7 +1648,7 @@ class AssignOneVariableValueOrFail : public Decision { virtual ~AssignOneVariableValueOrFail() {} virtual void Apply(Solver* const s); virtual void Refute(Solver* const s); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual void Accept(DecisionVisitor* const visitor) const { visitor->VisitSetVariableValue(var_, value_); } @@ -1663,7 +1662,7 @@ AssignOneVariableValueOrFail::AssignOneVariableValueOrFail(IntVar* const v, int64 value) : var_(v), value_(value) {} -string AssignOneVariableValueOrFail::DebugString() const { +std::string AssignOneVariableValueOrFail::DebugString() const { return StringPrintf("[%s == %" GG_LL_FORMAT "d]", var_->DebugString().c_str(), value_); } @@ -1688,7 +1687,7 @@ class SplitOneVariable : public Decision { virtual ~SplitOneVariable() {} virtual void Apply(Solver* const s); virtual void Refute(Solver* const s); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual void Accept(DecisionVisitor* const visitor) const { visitor->VisitSplitVariableDomain(var_, value_, start_with_lower_half_); } @@ -1703,7 +1702,7 @@ SplitOneVariable::SplitOneVariable(IntVar* const v, int64 val, bool start_with_lower_half) : var_(v), value_(val), start_with_lower_half_(start_with_lower_half) {} -string SplitOneVariable::DebugString() const { +std::string SplitOneVariable::DebugString() const { if (start_with_lower_half_) { return StringPrintf("[%s <= %" GG_LL_FORMAT "d]", var_->DebugString().c_str(), value_); @@ -1754,7 +1753,7 @@ class AssignVariablesValues : public Decision { virtual ~AssignVariablesValues() {} virtual void Apply(Solver* const s); virtual void Refute(Solver* const s); - virtual string DebugString() const; + virtual std::string DebugString() const; virtual void Accept(DecisionVisitor* const visitor) const { for (int i = 0; i < vars_.size(); ++i) { visitor->VisitSetVariableValue(vars_[i], values_[i]); @@ -1777,8 +1776,8 @@ AssignVariablesValues::AssignVariablesValues(const std::vector& vars, const std::vector& values) : vars_(vars), values_(values) {} -string AssignVariablesValues::DebugString() const { - string out; +std::string AssignVariablesValues::DebugString() const { + std::string out; for (int i = 0; i < vars_.size(); ++i) { StringAppendF(&out, "[%s == %" GG_LL_FORMAT "d]", vars_[i]->DebugString().c_str(), values_[i]); @@ -1825,7 +1824,7 @@ class BaseAssignVariables : public DecisionBuilder { : selector_(selector), mode_(mode) {} virtual ~BaseAssignVariables(); virtual Decision* Next(Solver* const s); - virtual string DebugString() const; + virtual std::string DebugString() const; static BaseAssignVariables* MakePhase(Solver* const s, const std::vector& vars, VariableSelector* const var_selector, @@ -1940,7 +1939,7 @@ Decision* BaseAssignVariables::Next(Solver* const s) { return nullptr; } -string BaseAssignVariables::DebugString() const { +std::string BaseAssignVariables::DebugString() const { return selector_->DebugString(); } @@ -2356,7 +2355,7 @@ class FirstSolutionCollector : public SolutionCollector { virtual ~FirstSolutionCollector(); virtual void EnterSearch(); virtual bool AtSolution(); - virtual string DebugString() const; + virtual std::string DebugString() const; private: bool done_; @@ -2384,7 +2383,7 @@ bool FirstSolutionCollector::AtSolution() { return false; } -string FirstSolutionCollector::DebugString() const { +std::string FirstSolutionCollector::DebugString() const { if (prototype_.get() == nullptr) { return "FirstSolutionCollector()"; } else { @@ -2412,7 +2411,7 @@ class LastSolutionCollector : public SolutionCollector { explicit LastSolutionCollector(Solver* const s); virtual ~LastSolutionCollector(); virtual bool AtSolution(); - virtual string DebugString() const; + virtual std::string DebugString() const; }; LastSolutionCollector::LastSolutionCollector(Solver* const s, @@ -2430,7 +2429,7 @@ bool LastSolutionCollector::AtSolution() { return true; } -string LastSolutionCollector::DebugString() const { +std::string LastSolutionCollector::DebugString() const { if (prototype_.get() == nullptr) { return "LastSolutionCollector()"; } else { @@ -2459,7 +2458,7 @@ class BestValueSolutionCollector : public SolutionCollector { virtual ~BestValueSolutionCollector() {} virtual void EnterSearch(); virtual bool AtSolution(); - virtual string DebugString() const; + virtual std::string DebugString() const; public: const bool maximize_; @@ -2501,7 +2500,7 @@ bool BestValueSolutionCollector::AtSolution() { return true; } -string BestValueSolutionCollector::DebugString() const { +std::string BestValueSolutionCollector::DebugString() const { if (prototype_.get() == nullptr) { return "BestValueSolutionCollector()"; } else { @@ -2529,7 +2528,7 @@ class AllSolutionCollector : public SolutionCollector { explicit AllSolutionCollector(Solver* const s); virtual ~AllSolutionCollector(); virtual bool AtSolution(); - virtual string DebugString() const; + virtual std::string DebugString() const; }; AllSolutionCollector::AllSolutionCollector(Solver* const s, @@ -2546,7 +2545,7 @@ bool AllSolutionCollector::AtSolution() { return true; } -string AllSolutionCollector::DebugString() const { +std::string AllSolutionCollector::DebugString() const { if (prototype_.get() == nullptr) { return "AllSolutionCollector()"; } else { @@ -2630,12 +2629,12 @@ bool OptimizeVar::AtSolution() { return true; } -string OptimizeVar::Print() const { +std::string OptimizeVar::Print() const { return StringPrintf("objective value = %" GG_LL_FORMAT "d, ", var_->Value()); } -string OptimizeVar::DebugString() const { - string out; +std::string OptimizeVar::DebugString() const { + std::string out; if (maximize_) { out = "MaximizeVar("; } else { @@ -2682,7 +2681,7 @@ class WeightedOptimizeVar : public OptimizeVar { } virtual ~WeightedOptimizeVar() {} - virtual string Print() const; + virtual std::string Print() const; private: const std::vector sub_objectives_; @@ -2691,8 +2690,8 @@ class WeightedOptimizeVar : public OptimizeVar { DISALLOW_COPY_AND_ASSIGN(WeightedOptimizeVar); }; -string WeightedOptimizeVar::Print() const { - string result(OptimizeVar::Print()); +std::string WeightedOptimizeVar::Print() const { + std::string result(OptimizeVar::Print()); StringAppendF(&result, "\nWeighted Objective:\n"); for (int i = 0; i < sub_objectives_.size(); ++i) { StringAppendF(&result, "Variable %s,\tvalue %lld,\tweight %lld\n", @@ -2818,7 +2817,7 @@ class TabuSearch : public Metaheuristic { virtual bool AtSolution(); virtual bool LocalOptimum(); virtual void AcceptNeighbor(); - virtual string DebugString() const { return "Tabu Search"; } + virtual std::string DebugString() const { return "Tabu Search"; } private: struct VarValue { @@ -3004,7 +3003,7 @@ class SimulatedAnnealing : public Metaheuristic { virtual bool AtSolution(); virtual bool LocalOptimum(); virtual void AcceptNeighbor(); - virtual string DebugString() const { return "Simulated Annealing"; } + virtual std::string DebugString() const { return "Simulated Annealing"; } private: float Temperature() const; @@ -3213,7 +3212,7 @@ class GuidedLocalSearch : public Metaheuristic { int64 index, int* container_index, int64* penalty) = 0; virtual IntExpr* MakeElementPenalty(int index) = 0; - virtual string DebugString() const { return "Guided Local Search"; } + virtual std::string DebugString() const { return "Guided Local Search"; } protected: struct Comparator { @@ -3372,11 +3371,11 @@ bool GuidedLocalSearch::AcceptDelta(Assignment* delta, Assignment* deltadelta) { if (maximize_) { delta->SetObjectiveMin( std::max(std::min(current_ + step_ - penalty, best_ + step_), - delta->ObjectiveMin())); + delta->ObjectiveMin())); } else { delta->SetObjectiveMax( std::min(std::max(current_ - step_ - penalty, best_ - step_), - delta->ObjectiveMax())); + delta->ObjectiveMax())); } } } @@ -3694,7 +3693,7 @@ class RegularLimit : public SearchLimit { int64 solutions); int64 wall_time() { return wall_time_; } virtual int ProgressPercent(); - virtual string DebugString() const; + virtual std::string DebugString() const; void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitExtension(ModelVisitor::kSearchLimitExtension); @@ -3791,9 +3790,9 @@ int RegularLimit::ProgressPercent() { Solver* const s = solver(); int64 progress = GetPercent(s->branches(), branches_offset_, branches_); progress = std::max(progress, - GetPercent(s->failures(), failures_offset_, failures_)); - progress = std::max( - progress, GetPercent(s->solutions(), solutions_offset_, solutions_)); + GetPercent(s->failures(), failures_offset_, failures_)); + progress = std::max(progress, + GetPercent(s->solutions(), solutions_offset_, solutions_)); if (wall_time_ < kint64max) { progress = std::max(progress, (100 * TimeDelta()) / wall_time_); } @@ -3830,7 +3829,7 @@ void RegularLimit::UpdateLimits(int64 time, int64 branches, int64 failures, solutions_ = solutions; } -string RegularLimit::DebugString() const { +std::string RegularLimit::DebugString() const { return StringPrintf("RegularLimit(crossed = %i, wall_time = %" GG_LL_FORMAT "d, " "branches = %" GG_LL_FORMAT "d, failures = %" GG_LL_FORMAT @@ -3951,7 +3950,7 @@ class ORLimit : public SearchLimit { limit_1_->RefuteDecision(d); limit_2_->RefuteDecision(d); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StrCat("OR limit (", limit_1_->DebugString(), " OR ", limit_2_->DebugString(), ")"); } @@ -4048,7 +4047,7 @@ class SolveOnce : public DecisionBuilder { return nullptr; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("SolveOnce(%s)", db_->DebugString().c_str()); } @@ -4162,7 +4161,7 @@ class NestedOptimize : public DecisionBuilder { return nullptr; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("NestedOptimize(db = %s, maximize = %d, step = %lld)", db_->DebugString().c_str(), maximize_, step_); } @@ -4280,7 +4279,7 @@ class LubyRestart : public SearchMonitor { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("LubyRestart(%i)", scale_factor_); } @@ -4315,7 +4314,7 @@ class ConstantRestart : public SearchMonitor { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("ConstantRestart(%i)", frequency_); } @@ -4426,7 +4425,7 @@ class SymmetryManager : public SearchMonitor { clauses_[visitor->index_in_symmetry_manager()].Push(solver(), term); } - string DebugString() const { return "SymmetryManager"; } + std::string DebugString() const { return "SymmetryManager"; } private: const std::vector visitors_; diff --git a/src/constraint_solver/softgcc.cc b/src/constraint_solver/softgcc.cc index e174921955..017f31d023 100644 --- a/src/constraint_solver/softgcc.cc +++ b/src/constraint_solver/softgcc.cc @@ -872,7 +872,7 @@ class SoftGCC : public Constraint{ } } - virtual string DebugString() const { + virtual std::string DebugString() const { return "SoftGCC"; } diff --git a/src/constraint_solver/table.cc b/src/constraint_solver/table.cc index 111c7e818a..3b43acbfaa 100644 --- a/src/constraint_solver/table.cc +++ b/src/constraint_solver/table.cc @@ -13,7 +13,6 @@ // // This file implements the table constraints. -#include #include #include "base/hash.h" #include "base/unique_ptr.h" @@ -73,7 +72,7 @@ struct AffineTransformation { // y == a*x + b. b = 0; } - string DebugString() const { + std::string DebugString() const { return StringPrintf("(%" GG_LL_FORMAT "d * x + %" GG_LL_FORMAT "d)", a, b); } }; @@ -85,7 +84,7 @@ class VarLinearizer : public ModelParser { virtual ~VarLinearizer() {} virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { if (operation == ModelVisitor::kSumOperation) { AddConstant(value); @@ -122,7 +121,7 @@ class VarLinearizer : public ModelParser { CHECK(multipliers_.empty()); } - virtual string DebugString() const { return "VarLinearizer"; } + virtual std::string DebugString() const { return "VarLinearizer"; } private: void AddConstant(int64 constant) { @@ -194,7 +193,7 @@ class BasePositiveTableConstraint : public Constraint { virtual ~BasePositiveTableConstraint() {} - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("AllowedAssignments(arity = %d, tuple_count = %d)", arity_, tuple_count_); } @@ -376,7 +375,7 @@ class PositiveTableConstraint : public BasePositiveTableConstraint { return false; } - virtual string DebugString() const { return "PositiveTableConstraint"; } + virtual std::string DebugString() const { return "PositiveTableConstraint"; } protected: void InitializeMask(int tuple_index) { @@ -1281,7 +1280,7 @@ class TransitionConstraint : public Constraint { visitor->EndVisitConstraint(ModelVisitor::kTransition, this); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf( "TransitionConstraint([%s], %d transitions, initial = %" GG_LL_FORMAT "d, final = [%s])", diff --git a/src/constraint_solver/timetabling.cc b/src/constraint_solver/timetabling.cc index ebc18797d6..3294c4c5b0 100644 --- a/src/constraint_solver/timetabling.cc +++ b/src/constraint_solver/timetabling.cc @@ -45,7 +45,7 @@ class IntervalUnaryRelation : public Constraint { virtual void InitialPropagate(); - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s %s %" GG_LL_FORMAT "d)", t_->DebugString().c_str(), kUnaryNames[rel_], d_); } @@ -130,7 +130,7 @@ class IntervalBinaryRelation : public Constraint { virtual void InitialPropagate(); - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("(%s %s %s)", t1_->DebugString().c_str(), kBinaryNames[rel_], t2_->DebugString().c_str()); } @@ -262,7 +262,7 @@ class TemporalDisjunction : public Constraint { virtual void Post(); virtual void InitialPropagate(); - virtual string DebugString() const; + virtual std::string DebugString() const; void RangeDemon1(); void RangeDemon2(); @@ -313,8 +313,8 @@ void TemporalDisjunction::InitialPropagate() { } } -string TemporalDisjunction::DebugString() const { - string out; +std::string TemporalDisjunction::DebugString() const { + std::string out; SStringPrintf(&out, "TemporalDisjunction(%s, %s", t1_->DebugString().c_str(), t2_->DebugString().c_str()); if (alt_ != nullptr) { diff --git a/src/constraint_solver/trace.cc b/src/constraint_solver/trace.cc index 85733fbeb6..1c38660151 100644 --- a/src/constraint_solver/trace.cc +++ b/src/constraint_solver/trace.cc @@ -11,9 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include -#include #include +#include #include "base/hash.h" #include #include @@ -150,7 +149,7 @@ class TraceIntVar : public IntVar { } } - virtual string DebugString() const { return inner_->DebugString(); } + virtual std::string DebugString() const { return inner_->DebugString(); } virtual IntVar* IsEqual(int64 constant) { return inner_->IsEqual(constant); } @@ -223,7 +222,7 @@ class TraceIntExpr : public IntExpr { visitor->EndVisitIntegerExpression(ModelVisitor::kTrace, this); } - virtual string DebugString() const { return inner_->DebugString(); } + virtual std::string DebugString() const { return inner_->DebugString(); } private: IntExpr* const inner_; @@ -381,7 +380,7 @@ class TraceIntervalVar : public IntervalVar { inner_->Accept(visitor); } - virtual string DebugString() const { return inner_->DebugString(); } + virtual std::string DebugString() const { return inner_->DebugString(); } private: IntervalVar* const inner_; @@ -392,8 +391,8 @@ class TraceIntervalVar : public IntervalVar { class PrintTrace : public PropagationMonitor { public: struct Info { - explicit Info(const string& m) : message(m), displayed(false) {} - string message; + explicit Info(const std::string& m) : message(m), displayed(false) {} + std::string message; bool displayed; }; @@ -578,7 +577,7 @@ class PrintTrace : public PropagationMonitor { PopDelayedInfo(); } - virtual void PushContext(const string& context) { PushDelayedInfo(context); } + virtual void PushContext(const std::string& context) { PushDelayedInfo(context); } virtual void PopContext() { PopDelayedInfo(); } @@ -741,10 +740,10 @@ class PrintTrace : public PropagationMonitor { } } - virtual string DebugString() const { return "PrintTrace"; } + virtual std::string DebugString() const { return "PrintTrace"; } private: - void PushDelayedInfo(const string& delayed) { + void PushDelayedInfo(const std::string& delayed) { if (FLAGS_cp_full_trace) { LOG(INFO) << Indent() << delayed << " {"; IncreaseIndent(); @@ -784,7 +783,7 @@ class PrintTrace : public PropagationMonitor { } } - void DisplayModification(const string& to_print) { + void DisplayModification(const std::string& to_print) { if (FLAGS_cp_full_trace) { LOG(INFO) << Indent() << to_print; } else { @@ -812,7 +811,7 @@ class PrintTrace : public PropagationMonitor { } } - void DisplaySearch(const string& to_print) { + void DisplaySearch(const std::string& to_print) { const int solve_depth = solver()->SolveDepth(); if (solve_depth <= 1) { LOG(INFO) << Indent() << "######## Top Level Search: " << to_print; @@ -822,9 +821,9 @@ class PrintTrace : public PropagationMonitor { } } - string Indent() { + std::string Indent() { CHECK_GE(contexes_.top().indent, 0); - string output = " @ "; + std::string output = " @ "; for (int i = 0; i < contexes_.top().indent; ++i) { output.append(" "); } diff --git a/src/constraint_solver/tree_monitor.cc b/src/constraint_solver/tree_monitor.cc index 5c40e21a74..1d32aeb3c7 100644 --- a/src/constraint_solver/tree_monitor.cc +++ b/src/constraint_solver/tree_monitor.cc @@ -11,13 +11,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include #include #include "base/hash.h" #include #include -#include #include "base/unique_ptr.h" +#include #include #include @@ -39,7 +38,7 @@ namespace operations_research { // String comparator that compares strings naturally, even those // including integer numbers. struct NaturalLess { - bool operator()(const string& s1, const string& s2) const { + bool operator()(const std::string& s1, const std::string& s2) const { int start = 0; int length = std::min(s1.length(), s2.length()); @@ -50,7 +49,7 @@ struct NaturalLess { ++start; } - // If one string is the substring of another, then the shorter string is + // If one std::string is the substring of another, then the shorter std::string is // smaller. if (start == length) { return s1.length() < s2.length(); @@ -73,7 +72,7 @@ struct NaturalLess { // Do a numerical comparison only if there are two numbers. if (number_s1 && number_s2) { // If we have similar numbers followed by other characters, we have to - // check the rest of the string. + // check the rest of the std::string. if (number_s1 != number_s2) { return number_s1 < number_s2; } @@ -86,7 +85,7 @@ struct NaturalLess { } }; -bool CompareStringsUsingNaturalLess(const string& s1, const string& s2) { +bool CompareStringsUsingNaturalLess(const std::string& s1, const std::string& s2) { return NaturalLess()(s1, s2); } @@ -148,7 +147,7 @@ class TreeDecisionVisitor : public DecisionVisitor { bool valid() { return valid_; } // Returns the name of the current variable. - const string& name() { + const std::string& name() { CHECK(valid_); return name_; } @@ -159,10 +158,10 @@ class TreeDecisionVisitor : public DecisionVisitor { return value_; } - virtual string DebugString() const { return "TreeDecisionVisitor"; } + virtual std::string DebugString() const { return "TreeDecisionVisitor"; } private: - string name_; + std::string name_; int64 value_; bool valid_; }; @@ -180,21 +179,21 @@ class TreeDecisionVisitor : public DecisionVisitor { // not support this. class TreeMonitor : public SearchMonitor { public: - typedef hash_map IntVarMap; + typedef hash_map IntVarMap; TreeMonitor(Solver* const solver, const IntVar* const* vars, int size, - const string& filename_tree, const string& filename_visualizer); + const std::string& filename_tree, const std::string& filename_visualizer); TreeMonitor(Solver* const solver, const IntVar* const* vars, int size, - string* const tree_xml, string* const visualization_xml); + std::string* const tree_xml, std::string* const visualization_xml); TreeMonitor(Solver* const solver, const IntVar* const* vars, int size, - const string& filename_config, const string& filename_tree, - const string& filename_visualizer); + const std::string& filename_config, const std::string& filename_tree, + const std::string& filename_visualizer); TreeMonitor(Solver* const solver, const IntVar* const* vars, int size, - string* const config_xml, string* const tree_xml, - string* const visualization_xml); + std::string* const config_xml, std::string* const tree_xml, + std::string* const visualization_xml); ~TreeMonitor(); @@ -209,13 +208,13 @@ class TreeMonitor : public SearchMonitor { virtual void ExitSearch(); // Returns the XML of the current tree. - virtual string DebugString() const; + virtual std::string DebugString() const; // Generates and returns the Tree XML file for CPVIZ. - string GenerateTreeXML() const; + std::string GenerateTreeXML() const; // Generates and returns the Visualization XML file for CPVIZ. - string GenerateVisualizationXML() const; + std::string GenerateVisualizationXML() const; // Callback called to indicate that the solver goes up one level in the // search tree. This is also used to restart the search at a parent node @@ -223,35 +222,35 @@ class TreeMonitor : public SearchMonitor { virtual void RefuteDecision(Decision* const decision); // Strips characters that cause problems with CPViz from attributes - static string StripSpecialCharacters(string attribute); + static std::string StripSpecialCharacters(std::string attribute); private: // Registers vars and sets Min and Max accordingly. void Init(const IntVar* const* vars, int size); - string* const config_xml_; + std::string* const config_xml_; TreeNode* current_node_; - const string filename_config_; - const string filename_tree_; - const string filename_visualizer_; + const std::string filename_config_; + const std::string filename_tree_; + const std::string filename_visualizer_; int id_counter_; - string last_decision_; - hash_map last_value_; - string last_variable_; + std::string last_decision_; + hash_map last_value_; + std::string last_variable_; int64 min_; int64 max_; std::unique_ptr root_node_; int search_level_; - string* const tree_xml_; + std::string* const tree_xml_; IntVarMap vars_; - string* const visualization_xml_; + std::string* const visualization_xml_; }; // Represents a node in the decision phase. Can either be the root node, a // successful attempt, a failure or a solution. class TreeNode { public: - typedef std::map, NaturalLess> DomainMap; + typedef std::map, NaturalLess> DomainMap; enum TreeNodeType { ROOT, TRY, @@ -295,10 +294,10 @@ class TreeNode { int id() const { return id_; } // Returns the name of the variable of the current decision. - const string& name() const { return name_; } + const std::string& name() const { return name_; } // Sets the name of the variable for the current decision. - void set_name(const string& name) { name_ = name; } + void set_name(const std::string& name) { name_ = name; } // Gets the node type. TreeNodeType node_type() const { return node_type_; } @@ -313,8 +312,8 @@ class TreeNode { void AddCycle() { cycles_++; } // Adds a new child, initializes it and returns the corresponding pointer. - bool AddChild(int id, const string& name, - hash_map const& last_value, bool is_final_node, + bool AddChild(int id, const std::string& name, + hash_map const& last_value, bool is_final_node, TreeMonitor::IntVarMap const& vars, TreeNode** child) { CHECK(child != nullptr); @@ -374,7 +373,7 @@ class TreeNode { current[0], current.back())); } else { // Use list of integers - string domain; + std::string domain; for (int j = 0; j < current.size(); ++j) { StringAppendF(&domain, " %" GG_LL_FORMAT "d", current[j]); @@ -468,14 +467,14 @@ class TreeNode { int cycles_; DomainMap domain_; const int id_; - string name_; + std::string name_; TreeNodeType node_type_; TreeNode* const parent_; }; TreeMonitor::TreeMonitor(Solver* const solver, const IntVar* const* vars, - int size, const string& filename_tree, - const string& filename_visualizer) + int size, const std::string& filename_tree, + const std::string& filename_visualizer) : SearchMonitor(solver), config_xml_(nullptr), current_node_(nullptr), @@ -492,8 +491,8 @@ TreeMonitor::TreeMonitor(Solver* const solver, const IntVar* const* vars, } TreeMonitor::TreeMonitor(Solver* const solver, const IntVar* const* vars, - int size, string* const tree_xml, - string* const visualization_xml) + int size, std::string* const tree_xml, + std::string* const visualization_xml) : SearchMonitor(solver), config_xml_(nullptr), current_node_(nullptr), @@ -512,9 +511,9 @@ TreeMonitor::TreeMonitor(Solver* const solver, const IntVar* const* vars, } TreeMonitor::TreeMonitor(Solver* const solver, const IntVar* const* vars, - int size, const string& filename_config, - const string& filename_tree, - const string& filename_visualizer) + int size, const std::string& filename_config, + const std::string& filename_tree, + const std::string& filename_visualizer) : SearchMonitor(solver), config_xml_(nullptr), current_node_(nullptr), @@ -531,9 +530,9 @@ TreeMonitor::TreeMonitor(Solver* const solver, const IntVar* const* vars, } TreeMonitor::TreeMonitor(Solver* const solver, const IntVar* const* vars, - int size, string* const config_xml, - string* const tree_xml, - string* const visualization_xml) + int size, std::string* const config_xml, + std::string* const tree_xml, + std::string* const visualization_xml) : SearchMonitor(solver), config_xml_(config_xml), current_node_(nullptr), @@ -563,7 +562,7 @@ void TreeMonitor::Init(const IntVar* const* vars, int size) { min_ = std::min(min_, vars[i]->Min()); max_ = std::max(max_, vars[i]->Max()); - string name = vars[i]->name(); + std::string name = vars[i]->name(); if (name.empty()) { name = StringPrintf("%d", i); @@ -644,7 +643,7 @@ void TreeMonitor::RefuteDecision(Decision* const decision) { current_node_ = current_node_->Parent(); } -string TreeMonitor::GenerateTreeXML() const { +std::string TreeMonitor::GenerateTreeXML() const { XmlHelper xml_writer; xml_writer.StartDocument(); @@ -662,7 +661,7 @@ string TreeMonitor::GenerateTreeXML() const { return xml_writer.GetContent(); } -string TreeMonitor::GenerateVisualizationXML() const { +std::string TreeMonitor::GenerateVisualizationXML() const { XmlHelper xml_writer; xml_writer.StartDocument(); @@ -691,7 +690,7 @@ string TreeMonitor::GenerateVisualizationXML() const { return xml_writer.GetContent(); } -string TreeMonitor::DebugString() const { +std::string TreeMonitor::DebugString() const { return StringPrintf("TreeMonitor:\n%s", GenerateTreeXML().c_str()); } @@ -747,7 +746,7 @@ void TreeMonitor::ExitSearch() { } } -string TreeMonitor::StripSpecialCharacters(string attribute) { +std::string TreeMonitor::StripSpecialCharacters(std::string attribute) { // Numbers, characters, dashes, underscored, brackets, colons, slashes, // periods, question marks, and parentheses are allowed const char* kAllowedCharacters = "0123456789abcdefghijklmnopqrstuvwxyz" @@ -774,38 +773,38 @@ string TreeMonitor::StripSpecialCharacters(string attribute) { // For tests // Strips characters that cause problems with CPViz from attributes -string TreeMonitorStripSpecialCharacters(string attribute) { +std::string TreeMonitorStripSpecialCharacters(std::string attribute) { return TreeMonitor::StripSpecialCharacters(attribute); } // ----- API ---- SearchMonitor* Solver::MakeTreeMonitor(const std::vector& vars, - const string& file_tree, - const string& file_visualization) { + const std::string& file_tree, + const std::string& file_visualization) { return RevAlloc(new TreeMonitor(this, vars.data(), vars.size(), file_tree, file_visualization)); } SearchMonitor* Solver::MakeTreeMonitor(const std::vector& vars, - const string& file_config, - const string& file_tree, - const string& file_visualization) { + const std::string& file_config, + const std::string& file_tree, + const std::string& file_visualization) { return RevAlloc(new TreeMonitor(this, vars.data(), vars.size(), file_config, file_tree, file_visualization)); } SearchMonitor* Solver::MakeTreeMonitor(const std::vector& vars, - string* const tree_xml, - string* const visualization_xml) { + std::string* const tree_xml, + std::string* const visualization_xml) { return RevAlloc(new TreeMonitor(this, vars.data(), vars.size(), tree_xml, visualization_xml)); } SearchMonitor* Solver::MakeTreeMonitor(const std::vector& vars, - string* const config_xml, - string* const tree_xml, - string* const visualization_xml) { + std::string* const config_xml, + std::string* const tree_xml, + std::string* const visualization_xml) { return RevAlloc(new TreeMonitor(this, vars.data(), vars.size(), config_xml, tree_xml, visualization_xml)); } diff --git a/src/constraint_solver/utilities.cc b/src/constraint_solver/utilities.cc index 5a9622c798..2892228d20 100644 --- a/src/constraint_solver/utilities.cc +++ b/src/constraint_solver/utilities.cc @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include #include "base/hash.h" #include "base/hash.h" #include @@ -227,45 +226,45 @@ class PrintModelVisitor : public ModelVisitor { virtual ~PrintModelVisitor() {} // Header/footers. - virtual void BeginVisitModel(const string& solver_name) { + virtual void BeginVisitModel(const std::string& solver_name) { LOG(INFO) << "Model " << solver_name << " {"; Increase(); } - virtual void EndVisitModel(const string& solver_name) { + virtual void EndVisitModel(const std::string& solver_name) { LOG(INFO) << "}"; Decrease(); CHECK_EQ(0, indent_); } - virtual void BeginVisitConstraint(const string& type_name, + virtual void BeginVisitConstraint(const std::string& type_name, const Constraint* const constraint) { LOG(INFO) << Spaces() << type_name; Increase(); } - virtual void EndVisitConstraint(const string& type_name, + virtual void EndVisitConstraint(const std::string& type_name, const Constraint* const constraint) { Decrease(); } - virtual void BeginVisitIntegerExpression(const string& type_name, + virtual void BeginVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) { LOG(INFO) << Spaces() << type_name; Increase(); } - virtual void EndVisitIntegerExpression(const string& type_name, + virtual void EndVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) { Decrease(); } - virtual void BeginVisitExtension(const string& type_name) { + virtual void BeginVisitExtension(const std::string& type_name) { LOG(INFO) << Spaces() << type_name; Increase(); } - virtual void EndVisitExtension(const string& type_name) { Decrease(); } + virtual void EndVisitExtension(const std::string& type_name) { Decrease(); } virtual void VisitIntegerVariable(const IntVar* const variable, IntExpr* const delegate) { @@ -281,7 +280,7 @@ class PrintModelVisitor : public ModelVisitor { } virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { LOG(INFO) << Spaces() << "IntVar"; Increase(); @@ -292,7 +291,7 @@ class PrintModelVisitor : public ModelVisitor { } virtual void VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate) { if (delegate != nullptr) { LOG(INFO) << Spaces() << operation << " <" << value << ", "; @@ -310,21 +309,21 @@ class PrintModelVisitor : public ModelVisitor { } // Variables. - virtual void VisitIntegerArgument(const string& arg_name, int64 value) { + virtual void VisitIntegerArgument(const std::string& arg_name, int64 value) { LOG(INFO) << Spaces() << arg_name << ": " << value; } - virtual void VisitIntegerArrayArgument(const string& arg_name, + virtual void VisitIntegerArrayArgument(const std::string& arg_name, const std::vector& values) { LOG(INFO) << Spaces() << arg_name << ": [" << IntVectorToString(values, ", ") << "]"; } - virtual void VisitIntegerMatrixArgument(const string& arg_name, + virtual void VisitIntegerMatrixArgument(const std::string& arg_name, const IntTupleSet& values) { const int rows = values.NumTuples(); const int columns = values.Arity(); - string array = "["; + std::string array = "["; for (int i = 0; i < rows; ++i) { if (i != 0) { array.append(", "); @@ -342,7 +341,7 @@ class PrintModelVisitor : public ModelVisitor { LOG(INFO) << Spaces() << arg_name << ": " << array; } - virtual void VisitIntegerExpressionArgument(const string& arg_name, + virtual void VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument) { set_prefix(StringPrintf("%s: ", arg_name.c_str())); Increase(); @@ -351,7 +350,7 @@ class PrintModelVisitor : public ModelVisitor { } virtual void VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { LOG(INFO) << Spaces() << arg_name << ": ["; Increase(); for (int i = 0; i < arguments.size(); ++i) { @@ -362,7 +361,7 @@ class PrintModelVisitor : public ModelVisitor { } // Visit interval argument. - virtual void VisitIntervalArgument(const string& arg_name, + virtual void VisitIntervalArgument(const std::string& arg_name, IntervalVar* const argument) { set_prefix(StringPrintf("%s: ", arg_name.c_str())); Increase(); @@ -371,7 +370,7 @@ class PrintModelVisitor : public ModelVisitor { } virtual void VisitIntervalArgumentArray( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { LOG(INFO) << Spaces() << arg_name << ": ["; Increase(); for (int i = 0; i < arguments.size(); ++i) { @@ -382,7 +381,7 @@ class PrintModelVisitor : public ModelVisitor { } // Visit sequence argument. - virtual void VisitSequenceArgument(const string& arg_name, + virtual void VisitSequenceArgument(const std::string& arg_name, SequenceVar* const argument) { set_prefix(StringPrintf("%s: ", arg_name.c_str())); Increase(); @@ -391,7 +390,7 @@ class PrintModelVisitor : public ModelVisitor { } virtual void VisitSequenceArgumentArray( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { LOG(INFO) << Spaces() << arg_name << ": ["; Increase(); for (int i = 0; i < arguments.size(); ++i) { @@ -401,15 +400,15 @@ class PrintModelVisitor : public ModelVisitor { LOG(INFO) << Spaces() << "]"; } - virtual string DebugString() const { return "PrintModelVisitor"; } + virtual std::string DebugString() const { return "PrintModelVisitor"; } private: void Increase() { indent_ += 2; } void Decrease() { indent_ -= 2; } - string Spaces() { - string result; + std::string Spaces() { + std::string result; for (int i = 0; i < indent_ - 2 * (!prefix_.empty()); ++i) { result.append(" "); } @@ -420,10 +419,10 @@ class PrintModelVisitor : public ModelVisitor { return result; } - void set_prefix(const string& prefix) { prefix_ = prefix; } + void set_prefix(const std::string& prefix) { prefix_ = prefix; } int indent_; - string prefix_; + std::string prefix_; }; // ---------- ModelStatisticsVisitor ----------- @@ -442,7 +441,7 @@ class ModelStatisticsVisitor : public ModelVisitor { virtual ~ModelStatisticsVisitor() {} // Begin/End visit element. - virtual void BeginVisitModel(const string& solver_name) { + virtual void BeginVisitModel(const std::string& solver_name) { // Reset statistics. num_constraints_ = 0; num_variables_ = 0; @@ -457,17 +456,17 @@ class ModelStatisticsVisitor : public ModelVisitor { extension_types_.clear(); } - virtual void EndVisitModel(const string& solver_name) { + virtual void EndVisitModel(const std::string& solver_name) { // Display statistics. LOG(INFO) << "Model has:"; LOG(INFO) << " - " << num_constraints_ << " constraints."; - for (ConstIter > it(constraint_types_); !it.at_end(); + for (ConstIter > it(constraint_types_); !it.at_end(); ++it) { LOG(INFO) << " * " << it->second << " " << it->first; } LOG(INFO) << " - " << num_variables_ << " integer variables."; LOG(INFO) << " - " << num_expressions_ << " integer expressions."; - for (ConstIter > it(expression_types_); !it.at_end(); + for (ConstIter > it(expression_types_); !it.at_end(); ++it) { LOG(INFO) << " * " << it->second << " " << it->first; } @@ -475,25 +474,25 @@ class ModelStatisticsVisitor : public ModelVisitor { LOG(INFO) << " - " << num_intervals_ << " interval variables."; LOG(INFO) << " - " << num_sequences_ << " sequence variables."; LOG(INFO) << " - " << num_extensions_ << " model extensions."; - for (ConstIter > it(extension_types_); !it.at_end(); + for (ConstIter > it(extension_types_); !it.at_end(); ++it) { LOG(INFO) << " * " << it->second << " " << it->first; } } - virtual void BeginVisitConstraint(const string& type_name, + virtual void BeginVisitConstraint(const std::string& type_name, const Constraint* const constraint) { num_constraints_++; AddConstraintType(type_name); } - virtual void BeginVisitIntegerExpression(const string& type_name, + virtual void BeginVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) { AddExpressionType(type_name); num_expressions_++; } - virtual void BeginVisitExtension(const string& type_name) { + virtual void BeginVisitExtension(const std::string& type_name) { AddExtensionType(type_name); num_extensions_++; } @@ -509,7 +508,7 @@ class ModelStatisticsVisitor : public ModelVisitor { } virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { num_variables_++; Register(variable); @@ -518,7 +517,7 @@ class ModelStatisticsVisitor : public ModelVisitor { } virtual void VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate) { num_intervals_++; if (delegate) { @@ -534,45 +533,45 @@ class ModelStatisticsVisitor : public ModelVisitor { } // Visit integer expression argument. - virtual void VisitIntegerExpressionArgument(const string& arg_name, + virtual void VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument) { VisitSubArgument(argument); } virtual void VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { VisitSubArgument(arguments[i]); } } // Visit interval argument. - virtual void VisitIntervalArgument(const string& arg_name, + virtual void VisitIntervalArgument(const std::string& arg_name, IntervalVar* const argument) { VisitSubArgument(argument); } virtual void VisitIntervalArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { VisitSubArgument(arguments[i]); } } // Visit sequence argument. - virtual void VisitSequenceArgument(const string& arg_name, + virtual void VisitSequenceArgument(const std::string& arg_name, SequenceVar* const argument) { VisitSubArgument(argument); } virtual void VisitSequenceArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { VisitSubArgument(arguments[i]); } } - virtual string DebugString() const { return "ModelStatisticsVisitor"; } + virtual std::string DebugString() const { return "ModelStatisticsVisitor"; } private: void Register(const BaseObject* const object) { @@ -592,21 +591,21 @@ class ModelStatisticsVisitor : public ModelVisitor { } } - void AddConstraintType(const string& constraint_type) { + void AddConstraintType(const std::string& constraint_type) { constraint_types_[constraint_type]++; } - void AddExpressionType(const string& expression_type) { + void AddExpressionType(const std::string& expression_type) { expression_types_[expression_type]++; } - void AddExtensionType(const string& extension_type) { + void AddExtensionType(const std::string& extension_type) { extension_types_[extension_type]++; } - hash_map constraint_types_; - hash_map expression_types_; - hash_map extension_types_; + hash_map constraint_types_; + hash_map expression_types_; + hash_map extension_types_; int num_constraints_; int num_variables_; int num_expressions_; @@ -638,7 +637,7 @@ class VariableDegreeVisitor : public ModelVisitor { } virtual void VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { IntVar* const var = const_cast(variable); if (ContainsKey(*map_, var)) { @@ -648,7 +647,7 @@ class VariableDegreeVisitor : public ModelVisitor { } virtual void VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate) { if (delegate) { VisitSubArgument(delegate); @@ -662,45 +661,45 @@ class VariableDegreeVisitor : public ModelVisitor { } // Visit integer expression argument. - virtual void VisitIntegerExpressionArgument(const string& arg_name, + virtual void VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument) { VisitSubArgument(argument); } virtual void VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { VisitSubArgument(arguments[i]); } } // Visit interval argument. - virtual void VisitIntervalArgument(const string& arg_name, + virtual void VisitIntervalArgument(const std::string& arg_name, IntervalVar* const argument) { VisitSubArgument(argument); } virtual void VisitIntervalArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { VisitSubArgument(arguments[i]); } } // Visit sequence argument. - virtual void VisitSequenceArgument(const string& arg_name, + virtual void VisitSequenceArgument(const std::string& arg_name, SequenceVar* const argument) { VisitSubArgument(argument); } virtual void VisitSequenceArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { for (int i = 0; i < arguments.size(); ++i) { VisitSubArgument(arguments[i]); } } - virtual string DebugString() const { return "VariableDegreeVisitor"; } + virtual std::string DebugString() const { return "VariableDegreeVisitor"; } private: // T should derive from BaseObject diff --git a/src/constraint_solver/visitor.cc b/src/constraint_solver/visitor.cc index 2084217840..695d6dc4a9 100644 --- a/src/constraint_solver/visitor.cc +++ b/src/constraint_solver/visitor.cc @@ -11,8 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include -#include +#include #include "base/hash.h" #include "base/hash.h" #include @@ -31,93 +30,93 @@ namespace operations_research { // ---------- ArgumentHolder ---------- -const string& ArgumentHolder::TypeName() const { return type_name_; } +const std::string& ArgumentHolder::TypeName() const { return type_name_; } -void ArgumentHolder::SetTypeName(const string& type_name) { +void ArgumentHolder::SetTypeName(const std::string& type_name) { type_name_ = type_name; } -void ArgumentHolder::SetIntegerArgument(const string& arg_name, int64 value) { +void ArgumentHolder::SetIntegerArgument(const std::string& arg_name, int64 value) { integer_argument_[arg_name] = value; } -void ArgumentHolder::SetIntegerArrayArgument(const string& arg_name, +void ArgumentHolder::SetIntegerArrayArgument(const std::string& arg_name, const std::vector& values) { integer_array_argument_[arg_name] = values; } -void ArgumentHolder::SetIntegerMatrixArgument(const string& arg_name, +void ArgumentHolder::SetIntegerMatrixArgument(const std::string& arg_name, const IntTupleSet& values) { - std::pair to_insert = std::make_pair(arg_name, values); + std::pair to_insert = std::make_pair(arg_name, values); matrix_argument_.insert(to_insert); } -void ArgumentHolder::SetIntegerExpressionArgument(const string& arg_name, +void ArgumentHolder::SetIntegerExpressionArgument(const std::string& arg_name, IntExpr* const expr) { integer_expression_argument_[arg_name] = expr; } void ArgumentHolder::SetIntegerVariableArrayArgument( - const string& arg_name, const std::vector& vars) { + const std::string& arg_name, const std::vector& vars) { integer_variable_array_argument_[arg_name] = vars; } -void ArgumentHolder::SetIntervalArgument(const string& arg_name, +void ArgumentHolder::SetIntervalArgument(const std::string& arg_name, IntervalVar* const var) { interval_argument_[arg_name] = var; } void ArgumentHolder::SetIntervalArrayArgument( - const string& arg_name, const std::vector& vars) { + const std::string& arg_name, const std::vector& vars) { interval_array_argument_[arg_name] = vars; } -void ArgumentHolder::SetSequenceArgument(const string& arg_name, +void ArgumentHolder::SetSequenceArgument(const std::string& arg_name, SequenceVar* const var) { sequence_argument_[arg_name] = var; } void ArgumentHolder::SetSequenceArrayArgument( - const string& arg_name, const std::vector& vars) { + const std::string& arg_name, const std::vector& vars) { sequence_array_argument_[arg_name] = vars; } bool ArgumentHolder::HasIntegerExpressionArgument( - const string& arg_name) const { + const std::string& arg_name) const { return ContainsKey(integer_expression_argument_, arg_name); } bool ArgumentHolder::HasIntegerVariableArrayArgument( - const string& arg_name) const { + const std::string& arg_name) const { return ContainsKey(integer_variable_array_argument_, arg_name); } -int64 ArgumentHolder::FindIntegerArgumentWithDefault(const string& arg_name, +int64 ArgumentHolder::FindIntegerArgumentWithDefault(const std::string& arg_name, int64 def) const { return FindWithDefault(integer_argument_, arg_name, def); } -int64 ArgumentHolder::FindIntegerArgumentOrDie(const string& arg_name) const { +int64 ArgumentHolder::FindIntegerArgumentOrDie(const std::string& arg_name) const { return FindOrDie(integer_argument_, arg_name); } const std::vector& ArgumentHolder::FindIntegerArrayArgumentOrDie( - const string& arg_name) const { + const std::string& arg_name) const { return FindOrDie(integer_array_argument_, arg_name); } IntExpr* ArgumentHolder::FindIntegerExpressionArgumentOrDie( - const string& arg_name) const { + const std::string& arg_name) const { return FindOrDie(integer_expression_argument_, arg_name); } const std::vector& ArgumentHolder::FindIntegerVariableArrayArgumentOrDie( - const string& arg_name) const { + const std::string& arg_name) const { return FindOrDie(integer_variable_array_argument_, arg_name); } const IntTupleSet& ArgumentHolder::FindIntegerMatrixArgumentOrDie( - const string& arg_name) const { + const std::string& arg_name) const { return FindOrDie(matrix_argument_, arg_name); } @@ -127,31 +126,31 @@ ModelParser::ModelParser() {} ModelParser::~ModelParser() { CHECK(holders_.empty()); } -void ModelParser::BeginVisitModel(const string& solver_name) { +void ModelParser::BeginVisitModel(const std::string& solver_name) { PushArgumentHolder(); } -void ModelParser::EndVisitModel(const string& solver_name) { +void ModelParser::EndVisitModel(const std::string& solver_name) { PopArgumentHolder(); } -void ModelParser::BeginVisitConstraint(const string& type_name, +void ModelParser::BeginVisitConstraint(const std::string& type_name, const Constraint* const constraint) { PushArgumentHolder(); } -void ModelParser::EndVisitConstraint(const string& type_name, +void ModelParser::EndVisitConstraint(const std::string& type_name, const Constraint* const constraint) { // Constraint parsing is usually done here. PopArgumentHolder(); } -void ModelParser::BeginVisitIntegerExpression(const string& type_name, +void ModelParser::BeginVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) { PushArgumentHolder(); } -void ModelParser::EndVisitIntegerExpression(const string& type_name, +void ModelParser::EndVisitIntegerExpression(const std::string& type_name, const IntExpr* const expr) { // Expression parsing is usually done here. PopArgumentHolder(); @@ -163,14 +162,14 @@ void ModelParser::VisitIntegerVariable(const IntVar* const variable, } void ModelParser::VisitIntegerVariable(const IntVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntVar* const delegate) { delegate->Accept(this); // Usual place for parsing. } void ModelParser::VisitIntervalVariable(const IntervalVar* const variable, - const string& operation, int64 value, + const std::string& operation, int64 value, IntervalVar* const delegate) { if (delegate != nullptr) { delegate->Accept(this); @@ -183,29 +182,29 @@ void ModelParser::VisitSequenceVariable(const SequenceVar* const variable) { } // Integer arguments -void ModelParser::VisitIntegerArgument(const string& arg_name, int64 value) { +void ModelParser::VisitIntegerArgument(const std::string& arg_name, int64 value) { Top()->SetIntegerArgument(arg_name, value); } -void ModelParser::VisitIntegerArrayArgument(const string& arg_name, +void ModelParser::VisitIntegerArrayArgument(const std::string& arg_name, const std::vector& values) { Top()->SetIntegerArrayArgument(arg_name, values); } -void ModelParser::VisitIntegerMatrixArgument(const string& arg_name, +void ModelParser::VisitIntegerMatrixArgument(const std::string& arg_name, const IntTupleSet& values) { Top()->SetIntegerMatrixArgument(arg_name, values); } // Variables. -void ModelParser::VisitIntegerExpressionArgument(const string& arg_name, +void ModelParser::VisitIntegerExpressionArgument(const std::string& arg_name, IntExpr* const argument) { Top()->SetIntegerExpressionArgument(arg_name, argument); argument->Accept(this); } void ModelParser::VisitIntegerVariableArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { Top()->SetIntegerVariableArrayArgument(arg_name, arguments); for (int i = 0; i < arguments.size(); ++i) { arguments[i]->Accept(this); @@ -213,14 +212,14 @@ void ModelParser::VisitIntegerVariableArrayArgument( } // Visit interval argument. -void ModelParser::VisitIntervalArgument(const string& arg_name, +void ModelParser::VisitIntervalArgument(const std::string& arg_name, IntervalVar* const argument) { Top()->SetIntervalArgument(arg_name, argument); argument->Accept(this); } void ModelParser::VisitIntervalArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { Top()->SetIntervalArrayArgument(arg_name, arguments); for (int i = 0; i < arguments.size(); ++i) { arguments[i]->Accept(this); @@ -228,14 +227,14 @@ void ModelParser::VisitIntervalArrayArgument( } // Visit sequence argument. -void ModelParser::VisitSequenceArgument(const string& arg_name, +void ModelParser::VisitSequenceArgument(const std::string& arg_name, SequenceVar* const argument) { Top()->SetSequenceArgument(arg_name, argument); argument->Accept(this); } void ModelParser::VisitSequenceArrayArgument( - const string& arg_name, const std::vector& arguments) { + const std::string& arg_name, const std::vector& arguments) { Top()->SetSequenceArrayArgument(arg_name, arguments); for (int i = 0; i < arguments.size(); ++i) { arguments[i]->Accept(this); diff --git a/src/flatzinc/booleans.cc b/src/flatzinc/booleans.cc index a063c596d0..f758272cce 100644 --- a/src/flatzinc/booleans.cc +++ b/src/flatzinc/booleans.cc @@ -55,7 +55,7 @@ inline Boolean MakeBoolean(bool x) { return Boolean(!x); } inline Boolean Xor(Boolean a, bool b) { return Boolean((uint8)(a.value() ^ (uint8) b)); } -inline string ToString(Boolean b) { +inline std::string ToString(Boolean b) { switch (b.value()) { case 0: return "true"; @@ -524,7 +524,7 @@ class SatPropagator : public Constraint { return result; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("SatConstraint(%d variables, %d clauses)", sat_.NumVariables(), sat_.NumClauses()); } diff --git a/src/flatzinc/flatzinc.cc b/src/flatzinc/flatzinc.cc index 57f6225548..b211fe6873 100644 --- a/src/flatzinc/flatzinc.cc +++ b/src/flatzinc/flatzinc.cc @@ -78,7 +78,7 @@ void FlatZincModel::InitSolver() { } } -void FlatZincModel::NewIntVar(const string& name, IntVarSpec* const vs, +void FlatZincModel::NewIntVar(const std::string& name, IntVarSpec* const vs, bool active) { IntVar* var = nullptr; if (vs->alias) { @@ -113,7 +113,7 @@ void FlatZincModel::NewIntVar(const string& name, IntVarSpec* const vs, void FlatZincModel::SkipIntVar() { integer_variables_[int_var_count++] = nullptr; } -void FlatZincModel::NewBoolVar(const string& name, BoolVarSpec* const vs) { +void FlatZincModel::NewBoolVar(const std::string& name, BoolVarSpec* const vs) { IntVar* var = nullptr; if (vs->alias) { var = boolean_variables_[vs->i]->Var(); @@ -138,7 +138,7 @@ void FlatZincModel::SkipBoolVar() { boolean_variables_[bool_var_count++] = nullptr; } -void FlatZincModel::NewSetVar(const string& name, SetVarSpec* vs) { +void FlatZincModel::NewSetVar(const std::string& name, SetVarSpec* vs) { // if (vs->alias) { // set_variables_[set_var_count++] = set_variables_[vs->i]; // } else { @@ -229,8 +229,8 @@ void FlatZincModel::CollectOutputVariables(AstNode* const node) { } } -string FlatZincModel::DebugString(AstNode* const ai) const { - string output; +std::string FlatZincModel::DebugString(AstNode* const ai) const { + std::string output; int k; if (ai->isArray()) { AstArray* aia = ai->getArray(); @@ -269,7 +269,7 @@ string FlatZincModel::DebugString(AstNode* const ai) const { } } } else if (ai->isString()) { - string s = ai->getString(); + std::string s = ai->getString(); for (unsigned int i = 0; i < s.size(); i++) { if (s[i] == '\\' && i < s.size() - 1) { switch (s[i + 1]) { diff --git a/src/flatzinc/flatzinc.h b/src/flatzinc/flatzinc.h index b87677531c..73cc28b103 100644 --- a/src/flatzinc/flatzinc.h +++ b/src/flatzinc/flatzinc.h @@ -116,12 +116,12 @@ class FzParallelSupport { FzParallelSupport() : num_solutions_found_(0) {} virtual ~FzParallelSupport() {} - virtual void Init(int worker_id, const string& init_string) = 0; + virtual void Init(int worker_id, const std::string& init_string) = 0; virtual void StartSearch(int worker_id, Type type) = 0; - virtual void SatSolution(int worker_id, const string& solution_string) = 0; + virtual void SatSolution(int worker_id, const std::string& solution_string) = 0; virtual void OptimizeSolution(int worker_id, int64 value, - const string& solution_string) = 0; - virtual void FinalOutput(int worker_id, const string& final_output) = 0; + const std::string& solution_string) = 0; + virtual void FinalOutput(int worker_id, const std::string& final_output) = 0; virtual bool ShouldFinish() const = 0; virtual void EndSearch(int worker_id, bool interrupted) = 0; virtual int64 BestSolution() const = 0; @@ -129,7 +129,7 @@ class FzParallelSupport { IntVar* const var, int64 step, int worker_id) = 0; virtual SearchLimit* Limit(Solver* const s, int worker_id) = 0; - virtual void Log(int worker_id, const string& message) = 0; + virtual void Log(int worker_id, const std::string& message) = 0; virtual bool Interrupted() const = 0; void IncrementSolutions() { num_solutions_found_++; } @@ -169,15 +169,15 @@ class FlatZincModel { void InitOutput(AstArray* const output); // Creates a new integer variable from specification. - void NewIntVar(const string& name, IntVarSpec* const vs, bool active); + void NewIntVar(const std::string& name, IntVarSpec* const vs, bool active); // Skips the creation of the variable. void SkipIntVar(); // Creates a new boolean variable from specification. - void NewBoolVar(const string& name, BoolVarSpec* const vs); + void NewBoolVar(const std::string& name, BoolVarSpec* const vs); // Skips the creation of the variable. void SkipBoolVar(); // Creates a new set variable from specification. - void NewSetVar(const string& name, SetVarSpec* const vs); + void NewSetVar(const std::string& name, SetVarSpec* const vs); // Adds a constraint to the model. void AddConstraint(CtSpec* const spec, Constraint* const ct); @@ -231,7 +231,7 @@ class FlatZincModel { FzParallelSupport* const parallel_support); // \brief Parse FlatZinc file \a fileName into \a fzs and return it. - bool Parse(const string& fileName); + bool Parse(const std::string& fileName); // \brief Parse FlatZinc from \a is into \a fzs and return it. bool Parse(std::istream& is); // NOLINT @@ -263,7 +263,7 @@ class FlatZincModel { Meth ProblemType() const { return method_; } private: - string DebugString(AstNode* const ai) const; + std::string DebugString(AstNode* const ai) const; void CollectOutputVariables(AstNode* const node); @@ -297,8 +297,8 @@ class FlatZincModel { std::vector introduced_variables_; std::vector output_variables_; bool parsed_ok_; - string search_name_; - string filename_; + std::string search_name_; + std::string filename_; SatPropagator* sat_; std::vector postponed_constraints_; std::vector integer_occurrences_; @@ -308,12 +308,12 @@ class FlatZincModel { // %Exception class for %FlatZinc errors class FzError { private: - const string msg; + const std::string msg; public: - FzError(const string& where, const string& what) + FzError(const std::string& where, const std::string& what) : msg(where + ": " + what) {} - const string& DebugString(void) const { return msg; } + const std::string& DebugString(void) const { return msg; } }; } // namespace operations_research diff --git a/src/flatzinc/flatzinc.yy b/src/flatzinc/flatzinc.yy index c2202cae4a..d18375b70d 100644 --- a/src/flatzinc/flatzinc.yy +++ b/src/flatzinc/flatzinc.yy @@ -272,7 +272,7 @@ FZ_VAR int_ti_expr_tail ':' var_par_id annotations non_array_expr_opt bool introduced = $5->hasAtom("var_is_introduced"); pp->int_var_map_[$4] = pp->int_variables_.size(); if (print) { - pp->output(string($4), new AstIntVar(pp->int_variables_.size())); + pp->output(std::string($4), new AstIntVar(pp->int_variables_.size())); } if ($6.defined()) { AstNode* arg = $6.value(); @@ -299,7 +299,7 @@ FZ_VAR int_ti_expr_tail ':' var_par_id annotations non_array_expr_opt bool introduced = $5->hasAtom("var_is_introduced"); pp->bool_var_map_[$4] = pp->bool_variables_.size(); if (print) { - pp->output(string($4), new AstBoolVar(pp->bool_variables_.size())); + pp->output(std::string($4), new AstBoolVar(pp->bool_variables_.size())); } if ($6.defined()) { AstNode* arg = $6.value(); @@ -333,7 +333,7 @@ FZ_VAR int_ti_expr_tail ':' var_par_id annotations non_array_expr_opt bool introduced = $7->hasAtom("var_is_introduced"); pp->set_var_map_[$6] = pp->set_variables_.size(); if (print) { - pp->output(string($6), new AstSetVar(pp->set_variables_.size())); + pp->output(std::string($6), new AstSetVar(pp->set_variables_.size())); } if ($8.defined()) { AstNode* arg = $8.value(); @@ -413,7 +413,7 @@ var_par_id annotations vardecl_int_var_array_init if ($5 > 0) { for (int i = 0; i < $5 - 1; i++) { vars[i] = pp->int_variables_.size(); - const string var_name = StringPrintf("%s[%d]", $11, i + 1); + const std::string var_name = StringPrintf("%s[%d]", $11, i + 1); if ($9.defined()) { Option copy = Option::some($9.value()->Copy()); @@ -425,7 +425,7 @@ var_par_id annotations vardecl_int_var_array_init } } vars[$5 - 1] = pp->int_variables_.size(); - const string var_name = + const std::string var_name = StringPrintf("%s[%" GG_LL_FORMAT "d]", $11, $5); pp->int_variables_.push_back( new IntVarSpec(var_name, $9, false, true)); @@ -440,7 +440,7 @@ var_par_id annotations vardecl_int_var_array_init output->a.push_back(new AstIntVar(vars[i])); a->a.push_back(output); a->a.push_back(new AstString(")")); - pp->output(string($11), a); + pp->output(std::string($11), a); } pp->int_var_array_map_[$11] = vars; } @@ -465,7 +465,7 @@ var_par_id annotations vardecl_bool_var_array_init vars[i] = bvsv->i; else { vars[i] = pp->bool_variables_.size(); - const string var_name = StringPrintf("%s[%d]", $11, i + 1); + const std::string var_name = StringPrintf("%s[%d]", $11, i + 1); (*vsv)[i]->SetName(var_name); pp->bool_variables_.push_back((*vsv)[i]); } @@ -479,7 +479,7 @@ var_par_id annotations vardecl_bool_var_array_init } else { for (int i = 0; i < $5; i++) { vars[i] = pp->bool_variables_.size(); - const string var_name = StringPrintf("%s[%d]", $11, i + 1); + const std::string var_name = StringPrintf("%s[%d]", $11, i + 1); pp->bool_variables_.push_back( new BoolVarSpec(var_name, $9, !print, (i == $5 - 1))); } @@ -492,7 +492,7 @@ var_par_id annotations vardecl_bool_var_array_init output->a.push_back(new AstBoolVar(vars[i])); a->a.push_back(output); a->a.push_back(new AstString(")")); - pp->output(string($11), a); + pp->output(std::string($11), a); } pp->bool_var_array_map_[$11] = vars; } @@ -536,7 +536,7 @@ var_par_id annotations vardecl_set_var_array_init delete vsv; } else { if ($5>0) { - string arrayname = "["; arrayname += $13; + std::string arrayname = "["; arrayname += $13; for (int i=0; i<$5-1; i++) { vars[i] = pp->set_variables_.size(); pp->set_variables_.push_back( @@ -554,7 +554,7 @@ var_par_id annotations vardecl_set_var_array_init output->a.push_back(new AstSetVar(vars[i])); a->a.push_back(output); a->a.push_back(new AstString(")")); - pp->output(string($13), a); + pp->output(std::string($13), a); } pp->set_var_array_map_[$13] = vars; } diff --git a/src/flatzinc/flatzinc_constraints.cc b/src/flatzinc/flatzinc_constraints.cc index 02a60a8235..f169585875 100644 --- a/src/flatzinc/flatzinc_constraints.cc +++ b/src/flatzinc/flatzinc_constraints.cc @@ -103,7 +103,7 @@ class BooleanSumOdd : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("BooleanSumOdd([%s])", JoinDebugStringPtr(vars_, ", ").c_str()); } @@ -158,7 +158,7 @@ class VariableParity : public Constraint { var_->SetRange(new_vmin, new_vmax); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("VarParity(%s, %d)", var_->DebugString().c_str(), odd_); } @@ -263,7 +263,7 @@ class IsBooleanSumInRange : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Sum([%s]) in [%" GG_LL_FORMAT "d..%" GG_LL_FORMAT "d] == %s", JoinDebugStringPtr(vars_, ", ").c_str(), range_min_, @@ -382,7 +382,7 @@ class BooleanSumInRange : public Constraint { Check(); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Sum([%s]) in [%" GG_LL_FORMAT "d..%" GG_LL_FORMAT "d]", JoinDebugStringPtr(vars_, ", ").c_str(), range_min_, range_max_); @@ -478,7 +478,7 @@ class Lex : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf( "Lex([%s], [%s]%s)", JoinDebugStringPtr(left_, ", ").c_str(), JoinDebugStringPtr(right_, ", ").c_str(), strict_ ? ", strict" : ""); @@ -569,7 +569,7 @@ class Inverse : public Constraint { } } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Inverse([%s], [%s])", JoinDebugStringPtr(left_, ", ").c_str(), JoinDebugStringPtr(right_, ", ").c_str()); @@ -646,7 +646,7 @@ class VariableCumulativeTask : public BaseObject { int64 StartMin() const { return start_->Min(); } int64 StartMax() const { return start_->Max(); } int64 EndMin() const { return start_->Min() + duration_->Min(); } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("Task{ start: %s, duration: %s, demand: %s }", start_->DebugString().c_str(), duration_->DebugString().c_str(), @@ -709,7 +709,7 @@ class VariableCumulativeTimeTable : public Constraint { LOG(FATAL) << "Should not be visited"; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("VariableCumulativeTimeTable([%s], capacity = %s)", JoinDebugStringPtr(by_start_min_, ", ").c_str(), capacity_->DebugString().c_str()); diff --git a/src/flatzinc/fz.cc b/src/flatzinc/fz.cc index aefca41ff6..66cc663ad3 100644 --- a/src/flatzinc/fz.cc +++ b/src/flatzinc/fz.cc @@ -63,12 +63,10 @@ DEFINE_bool(verbose_mt, false, "Verbose Multi-Thread"); DECLARE_bool(log_prefix); DECLARE_bool(logging); -using std::string; -using operations_research::scoped_ptr; using operations_research::ThreadPool; namespace operations_research { -int Run(const string& file, const FlatZincSearchParameters& parameters, +int Run(const std::string& file, const FlatZincSearchParameters& parameters, FzParallelSupport* const parallel_support) { FlatZincModel fz_model; if (file == "-") { @@ -217,7 +215,6 @@ int main(int argc, char** argv) { LOG(ERROR) << "Usage: " << argv[0] << " "; exit(EXIT_FAILURE); } - // Fix the number of solutions. if (FLAGS_num_solutions == 0) { // not specified FLAGS_num_solutions = FLAGS_all ? kint32max : 1; diff --git a/src/flatzinc/fz_search.cc b/src/flatzinc/fz_search.cc index 934096c0bd..35afbb204f 100644 --- a/src/flatzinc/fz_search.cc +++ b/src/flatzinc/fz_search.cc @@ -27,7 +27,6 @@ DECLARE_bool(logging); -using std::string; namespace operations_research { namespace { class FzLog : public SearchLog { @@ -37,7 +36,7 @@ class FzLog : public SearchLog { virtual ~FzLog() {} protected: - virtual void OutputLine(const string& line) { + virtual void OutputLine(const std::string& line) { std::cout << "%% " << line << std::endl; } }; @@ -109,7 +108,7 @@ class SequentialSupport : public FzParallelSupport { virtual ~SequentialSupport() {} - virtual void Init(int worker_id, const string& init_string) { + virtual void Init(int worker_id, const std::string& init_string) { std::cout << init_string << std::endl; } @@ -122,7 +121,7 @@ class SequentialSupport : public FzParallelSupport { } } - virtual void SatSolution(int worker_id, const string& solution_string) { + virtual void SatSolution(int worker_id, const std::string& solution_string) { if (NumSolutions() < num_solutions_ || print_all_) { std::cout << solution_string << std::endl; } @@ -130,7 +129,7 @@ class SequentialSupport : public FzParallelSupport { } virtual void OptimizeSolution(int worker_id, int64 value, - const string& solution_string) { + const std::string& solution_string) { best_solution_ = value; if (print_all_ || num_solutions_ > 1) { std::cout << solution_string << std::endl; @@ -140,7 +139,7 @@ class SequentialSupport : public FzParallelSupport { IncrementSolutions(); } - virtual void FinalOutput(int worker_id, const string& final_output) { + virtual void FinalOutput(int worker_id, const std::string& final_output) { std::cout << final_output << std::endl; } @@ -162,7 +161,7 @@ class SequentialSupport : public FzParallelSupport { virtual SearchLimit* Limit(Solver* const s, int worker_id) { return nullptr; } - virtual void Log(int worker_id, const string& message) { + virtual void Log(int worker_id, const std::string& message) { std::cout << "%% worker " << worker_id << ": " << message << std::endl; } @@ -173,7 +172,7 @@ class SequentialSupport : public FzParallelSupport { const bool verbose_; const int num_solutions_; Type type_; - string last_solution_; + std::string last_solution_; int64 best_solution_; bool interrupted_; }; @@ -192,7 +191,7 @@ class MtSupport : public FzParallelSupport { virtual ~MtSupport() {} - virtual void Init(int worker_id, const string& init_string) { + virtual void Init(int worker_id, const std::string& init_string) { MutexLock lock(&mutex_); if (worker_id == 0) { std::cout << init_string << std::endl; @@ -212,7 +211,7 @@ class MtSupport : public FzParallelSupport { } } - virtual void SatSolution(int worker_id, const string& solution_string) { + virtual void SatSolution(int worker_id, const std::string& solution_string) { MutexLock lock(&mutex_); if (NumSolutions() < num_solutions_ || print_all_) { LogNoLock(worker_id, "solution found"); @@ -223,7 +222,7 @@ class MtSupport : public FzParallelSupport { } virtual void OptimizeSolution(int worker_id, int64 value, - const string& solution_string) { + const std::string& solution_string) { MutexLock lock(&mutex_); if (!should_finish_) { switch (type_) { @@ -267,7 +266,7 @@ class MtSupport : public FzParallelSupport { } } - virtual void FinalOutput(int worker_id, const string& final_output) { + virtual void FinalOutput(int worker_id, const std::string& final_output) { MutexLock lock(&mutex_); std::cout << final_output << std::endl; } @@ -301,7 +300,7 @@ class MtSupport : public FzParallelSupport { return s->RevAlloc(new MtCustomLimit(s, this, worker_id)); } - virtual void Log(int worker_id, const string& message) { + virtual void Log(int worker_id, const std::string& message) { if (verbose_) { MutexLock lock(&mutex_); std::cout << "%% worker " << worker_id << ": " << message << std::endl; @@ -310,7 +309,7 @@ class MtSupport : public FzParallelSupport { virtual bool Interrupted() const { return interrupted_; } - void LogNoLock(int worker_id, const string& message) { + void LogNoLock(int worker_id, const std::string& message) { if (verbose_) { std::cout << "%% worker " << worker_id << ": " << message << std::endl; } @@ -322,7 +321,7 @@ class MtSupport : public FzParallelSupport { const bool verbose_; Mutex mutex_; Type type_; - string last_solution_; + std::string last_solution_; int last_worker_; int64 best_solution_; bool should_finish_; @@ -381,7 +380,7 @@ void SortVariableByDegree(const std::vector& occurrences, } // Report memory usage in a nice way. -string FlatZincMemoryUsage() { +std::string FlatZincMemoryUsage() { static const int64 kDisplayThreshold = 2; static const int64 kKiloByte = 1024; static const int64 kMegaByte = kKiloByte * kKiloByte; @@ -803,7 +802,7 @@ void FlatZincModel::Solve(FlatZincSearchParameters p, } bool breaked = false; - string solution_string; + std::string solution_string; const int64 build_time = solver_->wall_time(); solver_->NewSearch(db, monitors); while (solver_->NextSolution()) { @@ -847,7 +846,7 @@ void FlatZincModel::Solve(FlatZincSearchParameters p, const int num_solutions = parallel_support->NumSolutions(); bool proven = false; bool timeout = false; - string final_output; + std::string final_output; if (p.worker_id <= 0) { if (p.worker_id == 0) { // Recompute the breaked variable. @@ -906,12 +905,12 @@ void FlatZincModel::Solve(FlatZincSearchParameters p, } } const bool no_solutions = num_solutions == 0; - const string status_string = + const std::string status_string = (no_solutions ? (timeout ? "**timeout**" : "**unsat**") : (objective_ == nullptr ? "**sat**" : (timeout ? "**feasible**" : "**proven**"))); - const string obj_string = (objective_ != nullptr && !no_solutions + const std::string obj_string = (objective_ != nullptr && !no_solutions ? StringPrintf("%" GG_LL_FORMAT "d", best) : ""); final_output.append("%% name, status, obj, solns, s_time, b_time, br, " diff --git a/src/flatzinc/parser.cc b/src/flatzinc/parser.cc index 83c5a65a84..bbe79f892e 100644 --- a/src/flatzinc/parser.cc +++ b/src/flatzinc/parser.cc @@ -84,16 +84,16 @@ int ParserState::FillBuffer(char* lexBuf, unsigned int lexBufSize) { return num; } -void ParserState::output(string x, AstNode* n) { - output_.push_back(std::pair(x, n)); +void ParserState::output(std::string x, AstNode* n) { + output_.push_back(std::pair(x, n)); } // Strict weak ordering for output items class OutputOrder { public: // Return if \a x is less than \a y, based on first component - bool operator()(const std::pair& x, - const std::pair& y) { + bool operator()(const std::pair& x, + const std::pair& y) { return x.first < y.first; } }; @@ -151,7 +151,7 @@ void ParserState::CollectRequired(AstArray* const args, void ParserState::ComputeViableTarget(CtSpec* const spec, NodeSet* const candidates) const { - const string& id = spec->Id(); + const std::string& id = spec->Id(); if (id == "bool2int" || id == "int_plus" || id == "int_minus" || (id == "array_var_int_element" && !IsBound(spec->Arg(2))) || id == "array_int_element" || id == "int_abs" || @@ -235,7 +235,7 @@ void ParserState::MarkAllVariables(AstNode* const node, void ParserState::MarkComputedVariables(CtSpec* const spec, NodeSet* const computed) { - const string& id = spec->Id(); + const std::string& id = spec->Id(); if (id == "global_cardinality") { VLOG(2) << " - marking " << spec->DebugString(); MarkAllVariables(spec->Arg(2), computed); @@ -328,7 +328,7 @@ void ParserState::CollectIgnored(NodeSet* const ignored) { } for (int i = 0; i < constraints_.size(); ++i) { CtSpec* const spec = constraints_[i]; - const string& id = spec->Id(); + const std::string& id = spec->Id(); if (id == "array_bool_and" || id == "array_bool_or" || id == "bool_eq_reif" || id == "bool_ne_reif" || id == "bool_le_reif" || id == "bool_ge_reif") { @@ -348,7 +348,7 @@ void ParserState::ReuseIgnored(NodeSet* const ignored) { } for (int i = 0; i < constraints_.size(); ++i) { CtSpec* const spec = constraints_[i]; - const string& id = spec->Id(); + const std::string& id = spec->Id(); AstNode* const bool_define = FindTarget(spec->annotations()); AstNode* const last_arg = Copy(spec->LastArg()); if (bool_define == nullptr && last_arg != nullptr && @@ -497,7 +497,7 @@ void ParserState::Presolve() { FZLOG << "Model statistics" << std::endl; BuildStatistics(); - for (ConstIter>> it(constraints_per_id_); + for (ConstIter>> it(constraints_per_id_); !it.at_end(); ++it) { FZLOG << " - " << it->first << ": " << it->second.size() << std::endl; } @@ -731,7 +731,7 @@ void ParserState::BuildModel(const NodeSet& candidates, for (unsigned int i = 0; i < int_variables_.size(); i++) { VLOG(2) << "xi(" << i << ") -> " << int_variables_[i]->DebugString(); if (!hadError) { - const string& name = int_variables_[i]->Name(); + const std::string& name = int_variables_[i]->Name(); AstNode* const var = IntCopy(i); if (!ContainsKey(candidates, var) && !ContainsKey(int_aliases_, i)) { const bool active = @@ -760,8 +760,8 @@ void ParserState::BuildModel(const NodeSet& candidates, VLOG(2) << var->DebugString() << " -> " << bool_variables_[i]->DebugString(); if (!hadError) { - const string& raw_name = bool_variables_[i]->Name(); - string name; + const std::string& raw_name = bool_variables_[i]->Name(); + std::string name; if (raw_name[0] == '[') { name = StringPrintf("%s[%d]", raw_name.c_str() + 1, ++array_index); } else { @@ -788,8 +788,8 @@ void ParserState::BuildModel(const NodeSet& candidates, array_index = 0; for (unsigned int i = 0; i < set_variables_.size(); i++) { if (!hadError) { - const string& raw_name = set_variables_[i]->Name(); - string name; + const std::string& raw_name = set_variables_[i]->Name(); + std::string name; if (raw_name[0] == '[') { name = StringPrintf("%s[%d]", raw_name.c_str() + 1, ++array_index); } else { @@ -874,7 +874,7 @@ void ParserState::AnalyseAndCreateModel() { BuildModel(candidates, computed_variables); } -AstNode* ParserState::ArrayElement(string id, unsigned int offset) { +AstNode* ParserState::ArrayElement(std::string id, unsigned int offset) { if (offset > 0) { std::vector tmp; if (Get(int_var_array_map_, id, tmp) && offset <= tmp.size()) @@ -899,7 +899,7 @@ AstNode* ParserState::ArrayElement(string id, unsigned int offset) { return new AstIntVar(0); // keep things consistent } -AstNode* ParserState::VarRefArg(string id, bool annotation) { +AstNode* ParserState::VarRefArg(std::string id, bool annotation) { int64 tmp; if (Get(int_var_map_, id, tmp)) return new AstIntVar(tmp); if (Get(bool_var_map_, id, tmp)) return new AstBoolVar(tmp); @@ -1047,7 +1047,7 @@ bool ParserState::MergeIntDomain(IntVarSpec* const source, } bool ParserState::DiscoverAliases(CtSpec* const spec) { - const string& id = spec->Id(); + const std::string& id = spec->Id(); if (id == "int_eq") { if (spec->Arg(0)->isIntVar() && spec->Arg(1)->isIntVar() && !ContainsKey(stored_constraints_, spec)) { @@ -1106,7 +1106,7 @@ bool ParserState::DiscoverAliases(CtSpec* const spec) { } bool ParserState::PresolveOneConstraint(CtSpec* const spec) { - const string& id = spec->Id(); + const std::string& id = spec->Id(); if (id == "int_le") { if (spec->Arg(0)->isIntVar() && IsBound(spec->Arg(1))) { IntVarSpec* const var_spec = IntSpec(spec->Arg(0)); @@ -1293,13 +1293,13 @@ bool ParserState::PresolveOneConstraint(CtSpec* const spec) { spec->Nullify(); return true; } - if (id.find("_reif") != string::npos && IsBound(spec->LastArg()) && + if (id.find("_reif") != std::string::npos && IsBound(spec->LastArg()) && GetBound(spec->LastArg()) == 1) { VLOG(2) << " - presolve: unreify " << spec->DebugString(); spec->Unreify(); return true; } - if (id.find("_reif") != string::npos && IsBound(spec->LastArg()) && + if (id.find("_reif") != std::string::npos && IsBound(spec->LastArg()) && GetBound(spec->LastArg()) == 0) { VLOG(2) << " - presolve: unreify and inverse " << spec->DebugString(); spec->Unreify(); @@ -1750,7 +1750,7 @@ bool ParserState::PresolveOneConstraint(CtSpec* const spec) { return false; } -void ParserState::RegroupAux(const string& ct_id, int start_index, +void ParserState::RegroupAux(const std::string& ct_id, int start_index, int end_index, int output_var_index, const std::vector& indices) { if (indices.size() == 1) { @@ -1787,7 +1787,7 @@ void ParserState::RegroupAux(const string& ct_id, int start_index, } } -void ParserState::Regroup(const string& ct_id, const std::vector& ct_indices) { +void ParserState::Regroup(const std::string& ct_id, const std::vector& ct_indices) { int start_index = -1; int end_index = -1; std::vector variables; @@ -1848,7 +1848,7 @@ void ParserState::ReplaceAliases(CtSpec* const spec) { } } -void ParserState::AddConstraint(const string& id, AstArray* const args, +void ParserState::AddConstraint(const std::string& id, AstArray* const args, AstNode* const annotations) { constraints_.push_back( new CtSpec(constraints_.size(), id, args, annotations)); @@ -1875,11 +1875,11 @@ void ParserState::InitOutput(operations_research::FlatZincModel* const m) { m->InitOutput(Output()); } -bool FlatZincModel::Parse(const string& filename) { +bool FlatZincModel::Parse(const std::string& filename) { filename_ = filename; filename_.resize(filename_.size() - 4); size_t found = filename_.find_last_of("/\\"); - if (found != string::npos) { + if (found != std::string::npos) { filename_ = filename_.substr(found + 1); } #ifdef HAVE_MMAP @@ -1910,7 +1910,7 @@ bool FlatZincModel::Parse(const string& filename) { LOG(ERROR) << "Cannot open file " << filename; return false; } - string s = string(std::istreambuf_iterator(file), + std::string s = std::string(std::istreambuf_iterator(file), std::istreambuf_iterator()); ParserState pp(s, this); #endif @@ -1927,7 +1927,7 @@ bool FlatZincModel::Parse(const string& filename) { bool FlatZincModel::Parse(std::istream& is) { // NOLINT filename_ = "stdin"; - string s = string(std::istreambuf_iterator(is), + std::string s = std::string(std::istreambuf_iterator(is), std::istreambuf_iterator()); ParserState pp(s, this); @@ -1951,7 +1951,7 @@ AstNode* ArrayOutput(AstCall* ann) { a = new AstArray(ann->args); } - string out; + std::string out; out = StringPrintf("array%lud(", a->a.size()); for (unsigned int i = 0; i < a->a.size(); i++) { diff --git a/src/flatzinc/parser.h b/src/flatzinc/parser.h index f52624ce3e..9494376d73 100644 --- a/src/flatzinc/parser.h +++ b/src/flatzinc/parser.h @@ -65,8 +65,6 @@ extern "C" int isatty(int t); #include "base/map_util.h" #include "base/hash.h" -using std::string; - namespace operations_research { // ---------- Abstract syntax tree ---------- class AstCall; @@ -77,12 +75,12 @@ class AstSetLit; // %Exception signaling type error class AstTypeError { private: - string _what; + std::string _what; public: AstTypeError() : _what("") {} - explicit AstTypeError(string what) : _what(what) {} - string what() const { return _what; } + explicit AstTypeError(std::string what) : _what(what) {} + std::string what() const { return _what; } }; /* @@ -97,17 +95,17 @@ class AstNode { void append(AstNode* n); // Test if node has atom with \a id - bool hasAtom(const string& id); + bool hasAtom(const std::string& id); // Test if node is int, if yes set \a i to the value bool isInt(int& i); // NOLINT // Test if node is function call with \a id - bool isCall(const string& id); + bool isCall(const std::string& id); // Return function call AstCall* getCall(); // Test if node is function call or array containing function call \a id - bool hasCall(const string& id); + bool hasCall(const std::string& id); // Return function call \a id - AstCall* getCall(const string& id); + AstCall* getCall(const std::string& id); // Cast this node to an array node AstArray* getArray(); // Cast this node to an Atom node @@ -130,8 +128,8 @@ class AstNode { // Cast this node to a set literal node AstSetLit* getSet(); - // Cast this node to a string node - string getString(); + // Cast this node to a std::string node + std::string getString(); // Test if node is an integer variable node bool isIntVar(); @@ -143,7 +141,7 @@ class AstNode { bool isInt(); // Test if node is a Boolean node bool isBool(); - // Test if node is a string node + // Test if node is a std::string node bool isString(); // Test if node is an array node bool isArray(); @@ -152,8 +150,8 @@ class AstNode { // Test if node is an atom node bool isAtom(); - // Output string representation - virtual string DebugString() const = 0; + // Output std::string representation + virtual std::string DebugString() const = 0; }; // Boolean literal node @@ -161,7 +159,7 @@ class AstBoolLit : public AstNode { public: bool b; explicit AstBoolLit(bool b0) : b(b0) {} - virtual string DebugString() const { return b ? "b(true)" : "b(false)"; } + virtual std::string DebugString() const { return b ? "b(true)" : "b(false)"; } }; // Integer literal node @@ -169,7 +167,7 @@ class AstIntLit : public AstNode { public: int64 i; explicit AstIntLit(int64 i0) : i(i0) {} - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("i(%" GG_LL_FORMAT "d)", i); } }; @@ -178,7 +176,7 @@ class AstFloatLit : public AstNode { public: double d; explicit AstFloatLit(double d0) : d(d0) {} - virtual string DebugString() const { return StringPrintf("f(%f)", d); } + virtual std::string DebugString() const { return StringPrintf("f(%f)", d); } }; // %Set literal node class AstSetLit : public AstNode { @@ -200,11 +198,11 @@ class AstSetLit : public AstNode { return new AstSetLit(s); } } - virtual string DebugString() const { + virtual std::string DebugString() const { if (interval) { return StringPrintf("%" GG_LL_FORMAT "d..%" GG_LL_FORMAT "d", imin, imax); } else { - string output = "s({"; + std::string output = "s({"; for (unsigned int i = 0; i < s.size(); i++) { output += StringPrintf("%" GG_LL_FORMAT "d%s", s[i], (i < s.size() - 1 ? ", " : "})")); @@ -225,25 +223,25 @@ class AstVar : public AstNode { class AstBoolVar : public AstVar { public: explicit AstBoolVar(int i0) : AstVar(i0) {} - virtual string DebugString() const { return StringPrintf("xb(%d)", i); } + virtual std::string DebugString() const { return StringPrintf("xb(%d)", i); } }; // Integer variable node class AstIntVar : public AstVar { public: explicit AstIntVar(int i0) : AstVar(i0) {} - virtual string DebugString() const { return StringPrintf("xi(%d)", i); } + virtual std::string DebugString() const { return StringPrintf("xi(%d)", i); } }; // Float variable node class AstFloatVar : public AstVar { public: explicit AstFloatVar(int i0) : AstVar(i0) {} - virtual string DebugString() const { return StringPrintf("xf(%d)", i); } + virtual std::string DebugString() const { return StringPrintf("xf(%d)", i); } }; // %Set variable node class AstSetVar : public AstVar { public: explicit AstSetVar(int i0) : AstVar(i0) {} - virtual string DebugString() const { return StringPrintf("xs(%d)", i); } + virtual std::string DebugString() const { return StringPrintf("xs(%d)", i); } }; // %Array node @@ -253,8 +251,8 @@ class AstArray : public AstNode { explicit AstArray(AstNode* const n) : a(1) { a[0] = n; } explicit AstArray(int n) : a(n) {} AstArray() : a(0) {} - virtual string DebugString() const { - string output = "["; + virtual std::string DebugString() const { + std::string output = "["; for (unsigned int i = 0; i < a.size(); i++) { output += a[i]->DebugString(); if (i < a.size() - 1) output += ", "; @@ -272,11 +270,11 @@ class AstArray : public AstNode { // %Node representing a function call class AstCall : public AstNode { public: - const string id; + const std::string id; AstNode* const args; - AstCall(const string& id0, AstNode* args0) : id(id0), args(args0) {} + AstCall(const std::string& id0, AstNode* args0) : id(id0), args(args0) {} virtual ~AstCall() { delete args; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("%s(%s)", id.c_str(), args->DebugString().c_str()); } AstArray* getArgs(unsigned int n) { @@ -296,7 +294,7 @@ class AstArrayAccess : public AstNode { delete a; delete idx; } - virtual string DebugString() const { + virtual std::string DebugString() const { return StringPrintf("%s[%s]", a->DebugString().c_str(), idx->DebugString().c_str()); } @@ -305,19 +303,19 @@ class AstArrayAccess : public AstNode { // %Node representing an atom class AstAtom : public AstNode { public: - explicit AstAtom(const string& id0) : id(id0) {} - virtual string DebugString() const { return id; } - string id; + explicit AstAtom(const std::string& id0) : id(id0) {} + virtual std::string DebugString() const { return id; } + std::string id; }; // %String node class AstString : public AstNode { public: - explicit AstString(const string& s0) : s(s0) {} - virtual string DebugString() const { + explicit AstString(const std::string& s0) : s(s0) {} + virtual std::string DebugString() const { return StringPrintf("s(\"%s\")", s.c_str()); } - string s; + std::string s; }; inline void AstNode::append(AstNode* newNode) { @@ -326,7 +324,7 @@ inline void AstNode::append(AstNode* newNode) { a->a.push_back(newNode); } -inline bool AstNode::hasAtom(const string& id) { +inline bool AstNode::hasAtom(const std::string& id) { if (AstArray* a = dynamic_cast(this)) { for (int i = a->a.size(); i--;) if (AstAtom* at = dynamic_cast(a->a[i])) @@ -337,7 +335,7 @@ inline bool AstNode::hasAtom(const string& id) { return false; } -inline bool AstNode::isCall(const string& id) { +inline bool AstNode::isCall(const std::string& id) { if (AstCall* a = dynamic_cast(this)) { if (a->id == id) return true; } @@ -349,7 +347,7 @@ inline AstCall* AstNode::getCall() { throw AstTypeError("call expected"); } -inline bool AstNode::hasCall(const string& id) { +inline bool AstNode::hasCall(const std::string& id) { if (AstArray* a = dynamic_cast(this)) { for (int i = a->a.size(); i--;) if (AstCall* at = dynamic_cast(a->a[i])) @@ -370,7 +368,7 @@ inline bool AstNode::isInt(int& i) { // NOLINT return false; } -inline AstCall* AstNode::getCall(const string& id) { +inline AstCall* AstNode::getCall(const std::string& id) { if (AstArray* a = dynamic_cast(this)) { for (int i = a->a.size(); i--;) if (AstCall* at = dynamic_cast(a->a[i])) @@ -425,9 +423,9 @@ inline AstSetLit* AstNode::getSet() { if (AstSetLit* a = dynamic_cast(this)) return a; throw AstTypeError("set literal expected"); } -inline string AstNode::getString() { +inline std::string AstNode::getString() { if (AstString* a = dynamic_cast(this)) return a->s; - throw AstTypeError("string literal expected"); + throw AstTypeError("std::string literal expected"); } inline bool AstNode::isIntVar() { return (dynamic_cast(this) != nullptr); @@ -514,15 +512,15 @@ struct Option { class VarSpec { public: // Constructor - VarSpec(const string& name0, bool introduced0, bool alias0, bool assigned0) + VarSpec(const std::string& name0, bool introduced0, bool alias0, bool assigned0) : introduced(introduced0), alias(alias0), assigned(assigned0), name(name0) {} - // Debug string. - virtual string DebugString() const { return "VarSpec"; } - void SetName(const string& n) { name = n; } - const string& Name() const { return name; } + // Debug std::string. + virtual std::string DebugString() const { return "VarSpec"; } + void SetName(const std::string& n) { name = n; } + const std::string& Name() const { return name; } // Whether the variable was introduced in the mzn2fzn translation const bool introduced; @@ -535,27 +533,27 @@ class VarSpec { // Whether the variable is assigned bool assigned; // name - string name; + std::string name; }; // Specification for integer variables class IntVarSpec : public VarSpec { public: - IntVarSpec(const string& name, const Option& d, bool introduced, + IntVarSpec(const std::string& name, const Option& d, bool introduced, bool own_domain) : VarSpec(name, introduced, false, false), own_domain_(own_domain) { i = -1; domain_ = d; } - IntVarSpec(const string& name, int64 i0, bool introduced) + IntVarSpec(const std::string& name, int64 i0, bool introduced) : VarSpec(name, introduced, false, true), domain_(Option::none()), own_domain_(false) { i = i0; } - IntVarSpec(const string& name, const Alias& eq, bool introduced) + IntVarSpec(const std::string& name, const Alias& eq, bool introduced) : VarSpec(name, introduced, true, false), domain_(Option::none()), own_domain_(false) { @@ -673,7 +671,7 @@ class IntVarSpec : public VarSpec { domain_.value()->imax <= 1); } - virtual string DebugString() const { + virtual std::string DebugString() const { if (alias) { return StringPrintf( "IntVarSpec(name = %s, alias to = %" GG_LL_FORMAT "d)", name.c_str(), @@ -706,19 +704,19 @@ class IntVarSpec : public VarSpec { // Specification for Boolean variables class BoolVarSpec : public VarSpec { public: - BoolVarSpec(const string& name, const Option& d, bool introduced, + BoolVarSpec(const std::string& name, const Option& d, bool introduced, bool own_domain) : VarSpec(name, introduced, false, false), own_domain_(own_domain) { i = -1; domain_ = d; } - BoolVarSpec(const string& name, bool b, bool introduced) + BoolVarSpec(const std::string& name, bool b, bool introduced) : VarSpec(name, introduced, false, true), own_domain_(false) { i = b; } - BoolVarSpec(const string& name, const Alias& eq, bool introduced) + BoolVarSpec(const std::string& name, const Alias& eq, bool introduced) : VarSpec(name, introduced, true, false), own_domain_(false) { i = eq.v; } @@ -744,7 +742,7 @@ class BoolVarSpec : public VarSpec { return IsTrue(); } - virtual string DebugString() const { + virtual std::string DebugString() const { if (alias) { return StringPrintf( "BoolVarSpec(name = %s, alias to = %" GG_LL_FORMAT "d)", name.c_str(), @@ -770,18 +768,18 @@ class BoolVarSpec : public VarSpec { // Specification for floating point variables class FloatVarSpec : public VarSpec { public: - FloatVarSpec(const string& name, const Option*>& d, + FloatVarSpec(const std::string& name, const Option*>& d, bool introduced) : VarSpec(name, introduced, false, false) { domain = d; } - FloatVarSpec(const string& name, bool b, bool introduced) + FloatVarSpec(const std::string& name, bool b, bool introduced) : VarSpec(name, introduced, false, true) { i = b; } - FloatVarSpec(const string& name, const Alias& eq, bool introduced) + FloatVarSpec(const std::string& name, const Alias& eq, bool introduced) : VarSpec(name, introduced, true, false) { i = eq.v; } @@ -796,23 +794,23 @@ class FloatVarSpec : public VarSpec { // Specification for set variables class SetVarSpec : public VarSpec { public: - SetVarSpec(const string& name, bool introduced) + SetVarSpec(const std::string& name, bool introduced) : VarSpec(name, introduced, false, false), own_domain_(false) { domain_ = Option::none(); } - SetVarSpec(const string& name, const Option& v, bool introduced, + SetVarSpec(const std::string& name, const Option& v, bool introduced, bool own_domain) : VarSpec(name, introduced, false, false), own_domain_(own_domain) { domain_ = v; } - SetVarSpec(const string& name, AstSetLit* v, bool introduced) + SetVarSpec(const std::string& name, AstSetLit* v, bool introduced) : VarSpec(name, introduced, false, true), own_domain_(false) { domain_ = Option::some(v); } - SetVarSpec(const string& name, const Alias& eq, bool introduced) + SetVarSpec(const std::string& name, const Alias& eq, bool introduced) : VarSpec(name, introduced, true, false), own_domain_(false) { i = eq.v; } @@ -821,7 +819,7 @@ class SetVarSpec : public VarSpec { if (!alias && domain_.defined() && own_domain_) delete domain_.value(); } - virtual string DebugString() const { + virtual std::string DebugString() const { if (alias) { return StringPrintf( "SetVarSpec(name = %s, alias to = %" GG_LL_FORMAT "d)", name.c_str(), @@ -847,7 +845,7 @@ class SetVarSpec : public VarSpec { class CtSpec { public: - CtSpec(int index, const string& id, AstArray* const args, + CtSpec(int index, const std::string& id, AstArray* const args, AstNode* const annotations) : index_(index), id_(id), @@ -862,9 +860,9 @@ class CtSpec { delete annotations_; } - const string& Id() const { return id_; } + const std::string& Id() const { return id_; } - void SetId(const string& id) { id_ = id; } + void SetId(const std::string& id) { id_ = id; } int Index() const { return index_; } @@ -901,8 +899,8 @@ class CtSpec { AstNode* annotations() const { return annotations_; } - string DebugString() const { - string output = StringPrintf("CtSpec(no = %d, id = %s, args = %s", index_, + std::string DebugString() const { + std::string output = StringPrintf("CtSpec(no = %d, id = %s, args = %s", index_, id_.c_str(), args_->DebugString().c_str()); if (annotations_ != nullptr) { output += StringPrintf(", annotations = %s", @@ -997,7 +995,7 @@ class CtSpec { private: const int index_; - string id_; + std::string id_; AstArray* const args_; AstNode* annotations_; std::vector uses_; @@ -1007,9 +1005,9 @@ class CtSpec { bool ignored_; }; -template bool Get(const hash_map& map, const string& key, +template bool Get(const hash_map& map, const std::string& key, T& val) { // NOLINT - typename hash_map::const_iterator i = map.find(key); + typename hash_map::const_iterator i = map.find(key); if (i == map.end()) return false; val = i->second; return true; @@ -1018,7 +1016,7 @@ template bool Get(const hash_map& map, const string& key, // %State of the %FlatZinc parser class ParserState { public: - ParserState(const string& b, + ParserState(const std::string& b, operations_research::FlatZincModel* const model0) : buf(b.c_str()), pos(0), @@ -1036,20 +1034,20 @@ class ParserState { const char* buf; unsigned int pos, length; - hash_map int_var_map_; - hash_map bool_var_map_; - hash_map float_var_map_; - hash_map set_var_map_; - hash_map > int_var_array_map_; - hash_map > bool_var_array_map_; - hash_map > float_var_array_map_; - hash_map > set_var_array_map_; - hash_map > int_value_array_map_; - hash_map > bool_value_array_map_; - hash_map int_map_; - hash_map bool_map_; - hash_map set_map_; - hash_map > set_value_array_map_; + hash_map int_var_map_; + hash_map bool_var_map_; + hash_map float_var_map_; + hash_map set_var_map_; + hash_map > int_var_array_map_; + hash_map > bool_var_array_map_; + hash_map > float_var_array_map_; + hash_map > set_var_array_map_; + hash_map > int_value_array_map_; + hash_map > bool_value_array_map_; + hash_map int_map_; + hash_map bool_map_; + hash_map set_map_; + hash_map > set_value_array_map_; std::vector int_variables_; std::vector bool_variables_; @@ -1062,15 +1060,15 @@ class ParserState { bool hadError; int FillBuffer(char* lexBuf, unsigned int lexBufSize); - void output(string x, AstNode* n); + void output(std::string x, AstNode* n); AstArray* Output(); void AnalyseAndCreateModel(); - AstNode* ArrayElement(string id, unsigned int offset); - AstNode* VarRefArg(string id, bool annotation); + AstNode* ArrayElement(std::string id, unsigned int offset); + AstNode* VarRefArg(std::string id, bool annotation); void AddIntVarDomainConstraint(int var_id, AstSetLit* const dom); void AddBoolVarDomainConstraint(int var_id, AstSetLit* const dom); void AddSetVarDomainConstraint(int var_id, AstSetLit* const dom); - void AddConstraint(const string& id, AstArray* const args, + void AddConstraint(const std::string& id, AstArray* const args, AstNode* const annotations); void InitModel(); void InitOutput(operations_research::FlatZincModel* const m); @@ -1120,8 +1118,8 @@ class ParserState { void ComputeViableTarget(CtSpec* const spec, NodeSet* const candidates) const; void Sanitize(CtSpec* const spec); void BuildStatistics(); - void Regroup(const string& ct_id, const std::vector& ct_list); - void RegroupAux(const string& ct_id, int start_index, int end_index, + void Regroup(const std::string& ct_id, const std::vector& ct_list); + void RegroupAux(const std::string& ct_id, int start_index, int end_index, int output_var_index, const std::vector& indices); bool IsAlias(AstNode* const node) const; bool IsIntroduced(AstNode* const node) const; @@ -1129,13 +1127,13 @@ class ParserState { IntVarSpec* IntSpec(AstNode* const node) const; operations_research::FlatZincModel* model_; - std::vector > output_; + std::vector > output_; NodeSet orphans_; NodeSet targets_; hash_set bool2int_vars_; ConstraintSet stored_constraints_; std::vector > all_differents_; - hash_map > constraints_per_id_; + hash_map > constraints_per_id_; std::vector > constraints_per_int_variables_; std::vector > constraints_per_bool_variables_; hash_map abs_map_; diff --git a/src/flatzinc/registry.cc b/src/flatzinc/registry.cc index 543792035c..e1ad9b1b03 100644 --- a/src/flatzinc/registry.cc +++ b/src/flatzinc/registry.cc @@ -88,30 +88,30 @@ class ModelBuilder { // Type of constraint posting function typedef void (*Builder)(FlatZincModel* const model, CtSpec* const spec); // Add posting function \a p with identifier \a id - void Register(const string& id, Builder p); + void Register(const std::string& id, Builder p); // Post constraint specified by \a ce void Post(FlatZincModel* const model, CtSpec* const spec); private: // The actual builders. - std::map r; + std::map r; }; static ModelBuilder global_model_builder; void ModelBuilder::Post(FlatZincModel* const model, CtSpec* const spec) { if (!spec->Nullified()) { - const string& id = spec->Id(); - std::map::iterator i = r.find(id); + const std::string& id = spec->Id(); + std::map::iterator i = r.find(id); if (i == r.end()) { throw FzError("ModelBuilder", - string("Constraint ") + spec->Id() + " not found"); + std::string("Constraint ") + spec->Id() + " not found"); } i->second(model, spec); } } -void ModelBuilder::Register(const string& id, Builder p) { r[id] = p; } +void ModelBuilder::Register(const std::string& id, Builder p) { r[id] = p; } void p_int_eq(FlatZincModel* const model, CtSpec* const spec) { Solver* const solver = model->solver(); @@ -411,7 +411,7 @@ void p_int_lin_eq(FlatZincModel* const model, CtSpec* const spec) { } else { throw FzError( "ModelBuilder", - string("Constraint ") + spec->Id() + + std::string("Constraint ") + spec->Id() + " cannot define an integer variable with a coefficient" " different from -1"); } @@ -437,7 +437,7 @@ void p_int_lin_eq(FlatZincModel* const model, CtSpec* const spec) { if (array_coefficients->a[i]->getInt() != -1) { throw FzError( "ModelBuilder", - string("Constraint ") + spec->Id() + + std::string("Constraint ") + spec->Id() + " cannot define an integer variable with a coefficient" " different from -1"); } @@ -3482,7 +3482,7 @@ void p_set_in(FlatZincModel* const model, CtSpec* const spec) { model->AddConstraint(spec, ct); } } else { - throw FzError("ModelBuilder", string("Constraint ") + spec->Id() + + throw FzError("ModelBuilder", std::string("Constraint ") + spec->Id() + " does not support variable sets"); } } @@ -3503,7 +3503,7 @@ void p_set_in_reif(FlatZincModel* const model, CtSpec* const spec) { model->AddConstraint(spec, ct); } } else { - throw FzError("ModelBuilder", string("Constraint ") + spec->Id() + + throw FzError("ModelBuilder", std::string("Constraint ") + spec->Id() + " does not support variable sets"); } } diff --git a/src/graph/assignment.cc b/src/graph/assignment.cc index f6d55c7e5c..ee7df045ff 100644 --- a/src/graph/assignment.cc +++ b/src/graph/assignment.cc @@ -13,8 +13,8 @@ #include "graph/assignment.h" #include "base/commandlineflags.h" -#include "graph/linear_assignment.h" #include "graph/ebert_graph.h" +#include "graph/linear_assignment.h" namespace operations_research { @@ -55,6 +55,15 @@ SimpleLinearSumAssignment::Status SimpleLinearSumAssignment::Solve() { optimal_cost_ = 0; assignment_arcs_.clear(); if (NumNodes() == 0) return OPTIMAL; + // HACK(user): Detect overflows early. In ./linear_assignment.h, the cost of + // each arc is internally multiplied by cost_scaling_factor_ (which is equal + // to (num_nodes + 1)) without overflow checking. + const CostValue max_supported_arc_cost = + std::numeric_limits::max() / (NumNodes() + 1); + for (const CostValue unscaled_arc_cost : arc_cost_) { + if (unscaled_arc_cost > max_supported_arc_cost) return POSSIBLE_OVERFLOW; + } + const ArcIndex num_arcs = arc_cost_.size(); ForwardStarGraph graph(2 * num_nodes_, num_arcs); LinearSumAssignment assignment(graph, num_nodes_); diff --git a/src/graph/cliques.cc b/src/graph/cliques.cc index 704c709059..b7dc601718 100644 --- a/src/graph/cliques.cc +++ b/src/graph/cliques.cc @@ -143,7 +143,7 @@ class FindAndEliminate { bool GraphCallback(int node1, int node2) { if (visited_.find( std::make_pair(std::min(node1, node2), - std::max(node1, node2))) != visited_.end()) { + std::max(node1, node2))) != visited_.end()) { return false; } return graph_->Run(node1, node2); @@ -155,7 +155,7 @@ class FindAndEliminate { for (int i = 0; i < size - 1; ++i) { for (int j = i + 1; j < size; ++j) { visited_.insert(std::make_pair(std::min(solution[i], solution[j]), - std::max(solution[i], solution[j]))); + std::max(solution[i], solution[j]))); } } callback_->Run(solution); diff --git a/src/graph/ebert_graph.h b/src/graph/ebert_graph.h index c8cda33c54..baf0c7176d 100644 --- a/src/graph/ebert_graph.h +++ b/src/graph/ebert_graph.h @@ -182,7 +182,6 @@ #include "util/permutation.h" #include "util/zvector.h" -using std::string; namespace operations_research { @@ -307,7 +306,7 @@ template (head_)); + PermutationIndexComparisonByArcHead( + head_)); begin = end; } } else { @@ -746,7 +745,7 @@ class ForwardStaticGraph ArcIndexType end_index = (end > 0 ? end - 1 : end); ArcIndexType end_offset = (end > 0 ? 1 : 0); std::sort(&head_[begin_index] + begin_offset, - &head_[end_index] + end_offset); + &head_[end_index] + end_offset); begin = end; } } @@ -813,10 +812,10 @@ class ForwardStaticGraph } } - // Returns a debug string containing all the information contained in the + // Returns a debug std::string containing all the information contained in the // data structure in raw form. - string DebugString() const { - string result = "Arcs:(node) :\n"; + std::string DebugString() const { + std::string result = "Arcs:(node) :\n"; for (ArcIndexType arc = kFirstArc; arc < num_arcs_; ++arc) { result += " " + ArcDebugString(arc) + ":(" + NodeDebugString(head_[arc]) + ")\n"; @@ -1033,7 +1032,7 @@ class EbertGraphBase return kNilArc; } if (tail + 1 > num_nodes_) { - num_nodes_ = tail + 1; // std::max does not work on int16. + num_nodes_ = tail + 1; // max does not work on int16. } if (head + 1 > num_nodes_) { num_nodes_ = head + 1; @@ -1060,8 +1059,8 @@ class EbertGraphBase arc_permutation[i] = i; } std::sort(&arc_permutation[kFirstArc], - &arc_permutation[end_arc_index()], - compare); + &arc_permutation[end_arc_index()], + compare); // Now we actually permute the head_ array and the // scaled_arc_cost_ array according to the sorting permutation. @@ -1484,11 +1483,11 @@ template class EbertGraph representation_clean_ = true; } - // Returns a debug string containing all the information contained in the + // Returns a debug std::string containing all the information contained in the // data structure in raw form. - string DebugString() const { + std::string DebugString() const { DCHECK(representation_clean_); - string result = "Arcs:(node, next arc) :\n"; + std::string result = "Arcs:(node, next arc) :\n"; for (ArcIndexType arc = -num_arcs_; arc < num_arcs_; ++arc) { result += " " + ArcDebugString(arc) + ":(" + NodeDebugString(head_[arc]) + "," + ArcDebugString(next_adjacent_arc_[arc]) + ")\n"; @@ -1724,11 +1723,11 @@ class ForwardEbertGraph return true; } - // Returns a debug string containing all the information contained in the + // Returns a debug std::string containing all the information contained in the // data structure in raw form. - string DebugString() const { + std::string DebugString() const { DCHECK(representation_clean_); - string result = "Arcs:(node, next arc) :\n"; + std::string result = "Arcs:(node, next arc) :\n"; for (ArcIndexType arc = kFirstArc; arc < num_arcs_; ++arc) { result += " " + ArcDebugString(arc) + ":(" + NodeDebugString(head_[arc]) diff --git a/src/graph/hamiltonian_path.h b/src/graph/hamiltonian_path.h index 09da98e4b5..83a1294869 100644 --- a/src/graph/hamiltonian_path.h +++ b/src/graph/hamiltonian_path.h @@ -41,7 +41,7 @@ // Let us pick 0 as the starting node. // Let d(i,j) denote the distance (or cost) from i to j. // f(S,j) where S is a set of nodes and j is a node is defined as follows: -// f(S,j) = min(i in S, f(S\{i}, i) + d(i,j)) +// f(S,j) = std::min(i in S, f(S\{i}, i) + d(i,j)) // // The set S can be represented by an integer where bit i corresponds to // element i in the set. In the following S denotes the integer corresponding diff --git a/src/graph/linear_assignment.h b/src/graph/linear_assignment.h index e3e9e83260..7dbf602e79 100644 --- a/src/graph/linear_assignment.h +++ b/src/graph/linear_assignment.h @@ -188,7 +188,6 @@ #include "graph/ebert_graph.h" #include "util/permutation.h" -using std::string; #ifndef SWIG DECLARE_int64(assignment_alpha); @@ -334,7 +333,7 @@ template class LinearSumAssignment { return Head(matching_arc); } - string StatsString() const { + std::string StatsString() const { return total_stats_.StatsString(); } @@ -380,7 +379,7 @@ template class LinearSumAssignment { relabelings_ += that.relabelings_; refinements_ += that.refinements_; } - string StatsString() const { + std::string StatsString() const { return StringPrintf("%lld refinements; %lld relabelings; " "%lld double pushes; %lld pushes", refinements_, @@ -1016,9 +1015,9 @@ void LinearSumAssignment::SetArcCost(ArcIndex arc, CostValue cost) { DCHECK_LE(num_left_nodes_, head); } cost *= cost_scaling_factor_; - const CostValue cost_magnitude = std::abs(cost); + const CostValue cost_magnitude = abs(cost); largest_scaled_cost_magnitude_ = std::max(largest_scaled_cost_magnitude_, - cost_magnitude); + cost_magnitude); scaled_arc_cost_.Set(arc, cost); } @@ -1391,7 +1390,7 @@ bool LinearSumAssignment::FinalizeSetup() { // where the largest arc cost is zero, we still do a Refine() // iteration. epsilon_ = std::max(largest_scaled_cost_magnitude_, - kMinEpsilon + 1); + kMinEpsilon + 1); VLOG(2) << "Largest given cost magnitude: " << largest_scaled_cost_magnitude_ / cost_scaling_factor_; // Initialize left-side node-indexed arrays and check incidence diff --git a/src/graph/max_flow.cc b/src/graph/max_flow.cc index 4e26605040..63816997c9 100644 --- a/src/graph/max_flow.cc +++ b/src/graph/max_flow.cc @@ -281,8 +281,8 @@ bool GenericMaxFlow::CheckRelabelPrecondition(NodeIndex node) const { } template -string GenericMaxFlow::DebugString( - const string& context, ArcIndex arc) const { +std::string GenericMaxFlow::DebugString( + const std::string& context, ArcIndex arc) const { const NodeIndex tail = Tail(arc); const NodeIndex head = Head(arc); return StringPrintf("%s Arc %d, from %d to %d, " diff --git a/src/graph/max_flow.h b/src/graph/max_flow.h index 7352a57bd3..f0feae67e6 100644 --- a/src/graph/max_flow.h +++ b/src/graph/max_flow.h @@ -127,7 +127,6 @@ #include "util/stats.h" #include "util/zvector.h" -using std::string; namespace operations_research { @@ -417,7 +416,7 @@ template class GenericMaxFlow : public MaxFlowStatusClass { // Returns context concatenated with information about arc // in a human-friendly way. - string DebugString(const string& context, ArcIndex arc) const; + std::string DebugString(const std::string& context, ArcIndex arc) const; // Initializes the container active_nodes_. virtual void InitializeActiveNodeContainer(); diff --git a/src/graph/min_cost_flow.cc b/src/graph/min_cost_flow.cc index ddfaf6c2db..d85fd4ca56 100644 --- a/src/graph/min_cost_flow.cc +++ b/src/graph/min_cost_flow.cc @@ -13,8 +13,8 @@ #include "graph/min_cost_flow.h" -#include #include +#include #include #include "base/commandlineflags.h" @@ -259,8 +259,8 @@ bool GenericMinCostFlow< } template -string GenericMinCostFlow::DebugString( - const string& context, ArcIndex arc) const { +std::string GenericMinCostFlow::DebugString( + const std::string& context, ArcIndex arc) const { const NodeIndex tail = Tail(arc); const NodeIndex head = Head(arc); // Reduced cost is computed directly without calling ReducedCost to avoid @@ -739,7 +739,7 @@ void GenericMinCostFlow::UpdatePrices() { if (node_in_queue[node]) continue; max_potential_diff = std::max(max_potential_diff, - min_non_admissible_potential[node] - node_potential_[node]); + min_non_admissible_potential[node] - node_potential_[node]); if (max_potential_diff == potential_delta) break; } DCHECK_LE(max_potential_diff, potential_delta); @@ -822,7 +822,7 @@ void GenericMinCostFlow::Discharge( const bool head_active_before_push = IsActive(head); const FlowQuantity delta = std::min(node_excess_[node], - static_cast(residual_arc_capacity_[arc])); + static_cast(residual_arc_capacity_[arc])); FastPushFlow(delta, arc, node); if (IsActive(head) && !head_active_before_push) { active_nodes_.push(head); diff --git a/src/graph/min_cost_flow.h b/src/graph/min_cost_flow.h index fee7582c04..9dc6d673aa 100644 --- a/src/graph/min_cost_flow.h +++ b/src/graph/min_cost_flow.h @@ -181,7 +181,6 @@ #include "util/stats.h" #include "util/zvector.h" -using std::string; namespace operations_research { @@ -427,7 +426,7 @@ class GenericMinCostFlow : public MinCostFlowBase { // Returns context concatenated with information about a given arc // in a human-friendly way. - string DebugString(const string& context, ArcIndex arc) const; + std::string DebugString(const std::string& context, ArcIndex arc) const; // Resets the first_admissible_arc_ array to the first incident arc of each // node. diff --git a/src/linear_solver/cbc_interface.cc b/src/linear_solver/cbc_interface.cc index 6f25167951..fa59613798 100644 --- a/src/linear_solver/cbc_interface.cc +++ b/src/linear_solver/cbc_interface.cc @@ -126,7 +126,7 @@ class CBCInterface : public MPSolverInterface { virtual void ExtractNewConstraints() {} virtual void ExtractObjective() {} - virtual string SolverVersion() const { + virtual std::string SolverVersion() const { return "Cbc " CBC_VERSION; } diff --git a/src/linear_solver/clp_interface.cc b/src/linear_solver/clp_interface.cc index 1e5bbeb6ab..7abcd99f32 100644 --- a/src/linear_solver/clp_interface.cc +++ b/src/linear_solver/clp_interface.cc @@ -108,7 +108,7 @@ class CLPInterface : public MPSolverInterface { virtual void ExtractNewConstraints(); virtual void ExtractObjective(); - virtual string SolverVersion() const { + virtual std::string SolverVersion() const { return "Clp " CLP_VERSION; } @@ -274,10 +274,11 @@ void CLPInterface::AddVariable(MPVariable* const var) { void CLPInterface::CreateDummyVariableForEmptyConstraints() { clp_->setColumnBounds(kDummyVariableIndex, 0.0, 0.0); clp_->setObjectiveCoefficient(kDummyVariableIndex, 0.0); - // Workaround for peculiar signature of setColumnName. - std::string dummy_name = "dummy"; - int var_index = kDummyVariableIndex; - clp_->setColumnName(var_index, dummy_name); + // Workaround for peculiar signature of setColumnName. Note that we do need + // std::string here, and not 'std::string', which aren't the same as of 2013-12 + // (this will change later). + std::string dummy = "dummy"; // We do need to create this temporary variable. + clp_->setColumnName(kDummyVariableIndex, dummy); } // Define new variables and add them to existing constraints. @@ -294,8 +295,8 @@ void CLPInterface::ExtractNewVariables() { int var_index = i + 1; // offset by 1 because of dummy variable. var->set_index(var_index); if (!var->name().empty()) { - std::string std_name = var->name(); - clp_->setColumnName(var_index, std_name); + std::string name = var->name(); + clp_->setColumnName(var_index, name); } clp_->setColumnBounds(var_index, var->lb(), var->ub()); } @@ -314,8 +315,8 @@ void CLPInterface::ExtractNewVariables() { double tmp_obj_coef = 0.0; clp_->addColumn(0, NULL, NULL, var->lb(), var->ub(), tmp_obj_coef); if (!var->name().empty()) { - std::string std_name = var->name(); - clp_->setColumnName(var_index, std_name); + std::string name = var->name(); + clp_->setColumnName(var_index, name); } } // Add new variables to existing constraints. @@ -383,8 +384,8 @@ void CLPInterface::ExtractNewConstraints() { for (int i = last_constraint_index_; i < total_num_rows; ++i) { MPConstraint* const ct = solver_->constraints_[i]; if (!ct->name().empty()) { - std::string std_name = ct->name(); - clp_->setRowName(ct->index(), std_name); + std::string name = ct->name(); + clp_->setRowName(ct->index(), name); } } } diff --git a/src/linear_solver/glpk_interface.cc b/src/linear_solver/glpk_interface.cc index a07c07d5c5..513ccfcb7f 100644 --- a/src/linear_solver/glpk_interface.cc +++ b/src/linear_solver/glpk_interface.cc @@ -12,8 +12,8 @@ // limitations under the License. // -#include -#include +#include +#include #include "base/hash.h" #include #include "base/unique_ptr.h" @@ -158,7 +158,7 @@ class GLPKInterface : public MPSolverInterface { virtual void ExtractNewConstraints(); virtual void ExtractObjective(); - virtual string SolverVersion() const { + virtual std::string SolverVersion() const { return StringPrintf("GLPK %s", glp_version()); } diff --git a/src/linear_solver/gurobi_interface.cc b/src/linear_solver/gurobi_interface.cc index 75a802d8ab..9ac17c5716 100644 --- a/src/linear_solver/gurobi_interface.cc +++ b/src/linear_solver/gurobi_interface.cc @@ -10,8 +10,8 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -#include -#include +#include +#include #include "base/hash.h" #include #include "base/unique_ptr.h" @@ -103,7 +103,7 @@ class GurobiInterface : public MPSolverInterface { virtual void ExtractNewConstraints(); virtual void ExtractObjective(); - virtual string SolverVersion() const { + virtual std::string SolverVersion() const { int major, minor, technical; GRBversion(&major, &minor, &technical); return StringPrintf("Gurobi library version %d.%d.%d\n", @@ -152,8 +152,8 @@ class GurobiInterface : public MPSolverInterface { virtual void SetScalingMode(int value); virtual void SetLpAlgorithm(int value); - virtual bool ReadParameterFile(const string& filename); - virtual string ValidFileExtensionForParameterFile() const; + virtual bool ReadParameterFile(const std::string& filename); + virtual std::string ValidFileExtensionForParameterFile() const; MPSolver::BasisStatus TransformGRBVarBasisStatus(int gurobi_basis_status) const; @@ -804,12 +804,12 @@ MPSolver::ResultStatus GurobiInterface::Solve(const MPSolverParameters& param) { return result_status_; } -bool GurobiInterface::ReadParameterFile(const string& filename) { +bool GurobiInterface::ReadParameterFile(const std::string& filename) { // A non-zero return value indicates that a problem occurred. return GRBreadparams(GRBgetenv(model_), filename.c_str()) == 0; } -string GurobiInterface::ValidFileExtensionForParameterFile() const { +std::string GurobiInterface::ValidFileExtensionForParameterFile() const { return ".prm"; } diff --git a/src/linear_solver/linear_solver.cc b/src/linear_solver/linear_solver.cc index 21edc58e9e..248c8d0c4c 100644 --- a/src/linear_solver/linear_solver.cc +++ b/src/linear_solver/linear_solver.cc @@ -304,7 +304,7 @@ bool MPSolver::Minimization() const { // ----- Version ----- -string MPSolver::SolverVersion() const { +std::string MPSolver::SolverVersion() const { return interface_->SolverVersion(); } @@ -316,7 +316,7 @@ void* MPSolver::underlying_solver() { // ---- Solver-specific parameters ---- -bool MPSolver::SetSolverSpecificParametersAsString(const string& parameters) { +bool MPSolver::SetSolverSpecificParametersAsString(const std::string& parameters) { if (parameters.empty()) return true; solver_specific_parameter_string_ = parameters; @@ -324,8 +324,8 @@ bool MPSolver::SetSolverSpecificParametersAsString(const string& parameters) { // immediately, so we also perform the actual parameter parsing right away. // Some implementations will keep them forever and won't need to re-parse // them; some (eg. SCIP, Gurobi) need to re-parse the parameters every time - // they do Solve(). We just store the parameters string anyway. - string extension = interface_->ValidFileExtensionForParameterFile(); + // they do Solve(). We just store the parameters std::string anyway. + std::string extension = interface_->ValidFileExtensionForParameterFile(); #if defined(__linux) int32 tid = static_cast(pthread_self()); #else // defined(__linux__) @@ -337,7 +337,7 @@ bool MPSolver::SetSolverSpecificParametersAsString(const string& parameters) { int32 pid = 456; #endif // _MSC_VER int64 now = WallTimer::GetTimeInMicroSeconds(); - string filename = StringPrintf("/tmp/parameters-tempfile-%x-%d-%llx%s", + std::string filename = StringPrintf("/tmp/parameters-tempfile-%x-%d-%llx%s", tid, pid, now, extension.c_str()); bool no_error_so_far = true; if (no_error_so_far) { @@ -431,7 +431,7 @@ MPSolverInterface* BuildSolverInterface(MPSolver* const solver) { namespace { int NumDigits(int n) { // Number of digits needed to write a non-negative integer in base 10. - // Note(user): max(1, log(0) + 1) == max(1, -inf) == 1. + // Note(user): std::max(1, log(0) + 1) == std::max(1, -inf) == 1. #if defined(_MSC_VER) return static_cast(std::max(1.0L, log(1.0L * n) / log(10.0L) + 1.0)); #else @@ -440,7 +440,7 @@ int NumDigits(int n) { } } // namespace -MPSolver::MPSolver(const string& name, OptimizationProblemType problem_type) +MPSolver::MPSolver(const std::string& name, OptimizationProblemType problem_type) : name_(name), problem_type_(problem_type), #if !defined(_MSC_VER) @@ -462,16 +462,16 @@ MPSolver::~MPSolver() { } -MPVariable* MPSolver::LookupVariableOrNull(const string& var_name) const { - hash_map::const_iterator it = +MPVariable* MPSolver::LookupVariableOrNull(const std::string& var_name) const { + hash_map::const_iterator it = variable_name_to_index_.find(var_name); if (it == variable_name_to_index_.end()) return NULL; return variables_[it->second]; } MPConstraint* MPSolver::LookupConstraintOrNull( - const string& constraint_name) const { - hash_map::const_iterator it = + const std::string& constraint_name) const { + hash_map::const_iterator it = constraint_name_to_index_.find(constraint_name); if (it == constraint_name_to_index_.end()) return NULL; return constraints_[it->second]; @@ -482,10 +482,10 @@ MPConstraint* MPSolver::LookupConstraintOrNull( MPSolver::LoadStatus MPSolver::LoadModel(const MPModelProto& input_model) { // TODO(user): clear the previous data in the solver, and re-use the // existing hash maps! - hash_map variables; + hash_map variables; for (int i = 0; i < input_model.variables_size(); ++i) { const MPVariableProto& var_proto = input_model.variables(i); - const string& id = var_proto.id(); + const std::string& id = var_proto.id(); if (!ContainsKey(variables, id)) { if (var_and_constraint_names_allow_export_) { // TODO(user): unit test this clause and the similar one below. @@ -506,7 +506,7 @@ MPSolver::LoadStatus MPSolver::LoadModel(const MPModelProto& input_model) { for (int i = 0; i < input_model.constraints_size(); ++i) { tmp_variable_set.clear(); const MPConstraintProto& ct_proto = input_model.constraints(i); - const string& ct_id = ct_proto.id(); + const std::string& ct_id = ct_proto.id(); if (var_and_constraint_names_allow_export_) { var_and_constraint_names_allow_export_ &= MPModelProtoExporter::CheckNameValidity(ct_id); @@ -516,7 +516,7 @@ MPSolver::LoadStatus MPSolver::LoadModel(const MPModelProto& input_model) { ct_id); for (int j = 0; j < ct_proto.terms_size(); ++j) { const MPTermProto& term_proto = ct_proto.terms(j); - const string& id = term_proto.variable_id(); + const std::string& id = term_proto.variable_id(); MPVariable* variable = FindPtrOrNull(variables, id); if (variable == NULL) { return MPSolver::UNKNOWN_VARIABLE_ID; @@ -535,7 +535,7 @@ MPSolver::LoadStatus MPSolver::LoadModel(const MPModelProto& input_model) { tmp_variable_set.clear(); for (int i = 0; i < input_model.objective_terms_size(); ++i) { const MPTermProto& term_proto = input_model.objective_terms(i); - const string& id = term_proto.variable_id(); + const std::string& id = term_proto.variable_id(); MPVariable* variable = FindPtrOrNull(variables, id); if (variable == NULL) { return MPSolver::UNKNOWN_VARIABLE_ID; @@ -579,16 +579,23 @@ MPSolver::LoadStatus MPSolver::LoadModelFromProto( MPConstraint* const ct = MakeRowConstraint(ct_proto.lower_bound(), ct_proto.upper_bound(), ct_proto.name()); - for (int j = 0; j < ct_proto.linear_term_size(); ++j) { - const new_proto::MPConstraintProto::UnaryTerm& term_proto = - ct_proto.linear_term(j); - if (term_proto.var_index() >= variables_.size()) { + if (ct_proto.var_index_size() != ct_proto.coefficient_size()) { + LOG(ERROR) << "In constraint #" << i << " (name: '" << ct_proto.name() + << "'):" << " var_index_size() != coefficient_size()" + << ct_proto.DebugString(); + // TODO(user): add new error type to MPSolver and return it here. + // TODO(user): add unit test of this error. + return MPSolver::UNKNOWN_VARIABLE_ID; + } + for (int j = 0; j < ct_proto.var_index_size(); ++j) { + if (ct_proto.var_index(j) >= variables_.size() || + ct_proto.var_index(j) < 0) { LOG(ERROR) << "Variable index out of bound in constraint named " - << ct_proto.name() << "."; + << ct_proto.name() << "."; return MPSolver::UNKNOWN_VARIABLE_ID; } - ct->SetCoefficient(variables_[term_proto.var_index()], - term_proto.coefficient()); + ct->SetCoefficient(variables_[ct_proto.var_index(j)], + ct_proto.coefficient(j)); } } SetOptimizationDirection(input_model.maximize()); @@ -842,16 +849,9 @@ void MPSolver::ExportModelToNewProto( // few terms. std::sort(linear_term.begin(), linear_term.end()); // Now use linear term. - for (int k = 0; k < linear_term.size(); ++k) { - const std::pair& p = linear_term[k]; - const int var_index = p.first; - const double coeff = p.second; - new_proto::MPConstraintProto_UnaryTerm* unary_term - = constraint_proto->add_linear_term(); - unary_term->set_var_index(var_index); - unary_term->set_coefficient(coeff); - constraint_proto->add_var_index(var_index); - constraint_proto->add_coefficient(coeff); + for (const std::pair var_and_coeff : linear_term) { + constraint_proto->add_var_index(var_and_coeff.first); + constraint_proto->add_coefficient(var_and_coeff.second); } } output_model->set_maximize(Objective().maximization()); @@ -937,9 +937,9 @@ void MPSolver::SuppressOutput() { } MPVariable* MPSolver::MakeVar( - double lb, double ub, bool integer, const string& name) { + double lb, double ub, bool integer, const std::string& name) { const int var_index = NumVariables(); - const string fixed_name = name.empty() + const std::string fixed_name = name.empty() ? StringPrintf("auto_v_%09d", var_index) : name; if (var_and_constraint_names_allow_export_) { var_and_constraint_names_allow_export_ &= @@ -953,16 +953,16 @@ MPVariable* MPSolver::MakeVar( } MPVariable* MPSolver::MakeNumVar( - double lb, double ub, const string& name) { + double lb, double ub, const std::string& name) { return MakeVar(lb, ub, false, name); } MPVariable* MPSolver::MakeIntVar( - double lb, double ub, const string& name) { + double lb, double ub, const std::string& name) { return MakeVar(lb, ub, true, name); } -MPVariable* MPSolver::MakeBoolVar(const string& name) { +MPVariable* MPSolver::MakeBoolVar(const std::string& name) { return MakeVar(0.0, 1.0, true, name); } @@ -970,7 +970,7 @@ void MPSolver::MakeVarArray(int nb, double lb, double ub, bool integer, - const string& name, + const std::string& name, std::vector* vars) { DCHECK_GE(nb, 0); if (nb <= 0) return; @@ -979,7 +979,7 @@ void MPSolver::MakeVarArray(int nb, if (name.empty()) { vars->push_back(MakeVar(lb, ub, integer, name)); } else { - string vname = StringPrintf("%s%0*d", name.c_str(), num_digits, i); + std::string vname = StringPrintf("%s%0*d", name.c_str(), num_digits, i); vars->push_back(MakeVar(lb, ub, integer, vname)); } } @@ -988,7 +988,7 @@ void MPSolver::MakeVarArray(int nb, void MPSolver::MakeNumVarArray(int nb, double lb, double ub, - const string& name, + const std::string& name, std::vector* vars) { MakeVarArray(nb, lb, ub, false, name, vars); } @@ -996,13 +996,13 @@ void MPSolver::MakeNumVarArray(int nb, void MPSolver::MakeIntVarArray(int nb, double lb, double ub, - const string& name, + const std::string& name, std::vector* vars) { MakeVarArray(nb, lb, ub, true, name, vars); } void MPSolver::MakeBoolVarArray(int nb, - const string& name, + const std::string& name, std::vector* vars) { MakeVarArray(nb, 0.0, 1.0, true, name, vars); } @@ -1016,9 +1016,9 @@ MPConstraint* MPSolver::MakeRowConstraint() { } MPConstraint* MPSolver::MakeRowConstraint(double lb, double ub, - const string& name) { + const std::string& name) { const int constraint_index = NumConstraints(); - const string fixed_name = name.empty() + const std::string fixed_name = name.empty() ? StringPrintf("auto_c_%09d", constraint_index) : name; if (var_and_constraint_names_allow_export_) { var_and_constraint_names_allow_export_ &= @@ -1032,7 +1032,7 @@ MPConstraint* MPSolver::MakeRowConstraint(double lb, double ub, return constraint; } -MPConstraint* MPSolver::MakeRowConstraint(const string& name) { +MPConstraint* MPSolver::MakeRowConstraint(const std::string& name) { return MakeRowConstraint(-infinity(), infinity(), name); } @@ -1095,8 +1095,8 @@ MPSolver::ResultStatus MPSolver::Solve(const MPSolverParameters ¶m) { } namespace { -string PrettyPrintVar(const MPVariable& var) { - const string prefix = "Variable '" + var.name() + "': domain = "; +std::string PrettyPrintVar(const MPVariable& var) { + const std::string prefix = "Variable '" + var.name() + "': domain = "; if (var.lb() >= MPSolver::infinity() || var.ub() <= -MPSolver::infinity() || var.lb() > var.ub()) { @@ -1123,14 +1123,14 @@ string PrettyPrintVar(const MPVariable& var) { + (var.integer() ? "Integer" : "Real") + " in " + (var.lb() <= -MPSolver::infinity() - ? string("]-∞") : StringPrintf("[%f", var.lb())) + ? std::string("]-∞") : StringPrintf("[%f", var.lb())) + ", " + (var.ub() >= MPSolver::infinity() - ? string("+∞[") : StringPrintf("%f]", var.ub())); + ? std::string("+∞[") : StringPrintf("%f]", var.ub())); } -string PrettyPrintConstraint(const MPConstraint& constraint) { - string prefix = "Constraint '" + constraint.name() + "': "; +std::string PrettyPrintConstraint(const MPConstraint& constraint) { + std::string prefix = "Constraint '" + constraint.name() + "': "; if (constraint.lb() >= MPSolver::infinity() || constraint.ub() <= -MPSolver::infinity() || constraint.lb() > constraint.ub()) { @@ -1197,7 +1197,7 @@ bool MPSolver::VerifySolution(double tolerance, bool log_errors) const { if (fabs(value - round(value)) > tolerance) { ++num_errors; max_observed_error = std::max(max_observed_error, - fabs(value - round(value))); + fabs(value - round(value))); LOG_IF(ERROR, log_errors) << "Non-integer value "<< value << " for " << PrettyPrintVar(var); } @@ -1229,7 +1229,7 @@ bool MPSolver::VerifySolution(double tolerance, bool log_errors) const { if (activity < constraint.lb() - tolerance) { ++num_errors; max_observed_error = std::max(max_observed_error, - constraint.lb() - activity); + constraint.lb() - activity); LOG_IF(ERROR, log_errors) << "Activity " << activity << " too low for " << PrettyPrintConstraint(constraint); @@ -1244,7 +1244,7 @@ bool MPSolver::VerifySolution(double tolerance, bool log_errors) const { if (activity > constraint.ub() + tolerance) { ++num_errors; max_observed_error = std::max(max_observed_error, - activity - constraint.ub()); + activity - constraint.ub()); LOG_IF(ERROR, log_errors) << "Activity " << activity << " too high for " << PrettyPrintConstraint(constraint); @@ -1321,7 +1321,7 @@ bool MPSolver::OwnsVariable(const MPVariable* var) const { } -bool MPSolver::ExportModelAsLpFormat(bool obfuscate, string* output) { +bool MPSolver::ExportModelAsLpFormat(bool obfuscate, std::string* output) { MPModelProto proto; ExportModel(&proto); MPModelProtoExporter exporter(proto); @@ -1329,7 +1329,7 @@ bool MPSolver::ExportModelAsLpFormat(bool obfuscate, string* output) { } bool MPSolver::ExportModelAsMpsFormat( - bool fixed_format, bool obfuscate, string* output) { + bool fixed_format, bool obfuscate, std::string* output) { MPModelProto proto; ExportModel(&proto); MPModelProtoExporter exporter(proto); @@ -1488,12 +1488,12 @@ void MPSolverInterface::SetIntegerParamToUnsupportedValue( << " to an unsupported value: " << value; } -bool MPSolverInterface::ReadParameterFile(const string& filename) { +bool MPSolverInterface::ReadParameterFile(const std::string& filename) { LOG(WARNING) << "ReadParameterFile() not supported by this solver."; return false; } -string MPSolverInterface::ValidFileExtensionForParameterFile() const { +std::string MPSolverInterface::ValidFileExtensionForParameterFile() const { return ".tmp"; } @@ -1712,7 +1712,7 @@ bool MPSolver::LoadSolutionFromProto(const MPSolutionResponse& response) { std::vector variable_has_solution_value(variables_.size(), false); int num_vars_out_of_bounds = 0; for (int i = 0; i < response.solution_values_size(); ++i) { - const string& var_name = response.solution_values(i).variable_id(); + const std::string& var_name = response.solution_values(i).variable_id(); const int var_index = FindWithDefault(variable_name_to_index_, var_name, -1); if (var_index < 0) { diff --git a/src/linear_solver/linear_solver.h b/src/linear_solver/linear_solver.h index 2c6ff947c5..70ce298182 100644 --- a/src/linear_solver/linear_solver.h +++ b/src/linear_solver/linear_solver.h @@ -144,7 +144,6 @@ #include "base/timer.h" -using std::string; namespace operations_research { @@ -207,11 +206,11 @@ class MPSolver { #endif }; - MPSolver(const string& name, OptimizationProblemType problem_type); + MPSolver(const std::string& name, OptimizationProblemType problem_type); virtual ~MPSolver(); - string Name() const { + std::string Name() const { return name_; // Set at construction. } @@ -231,20 +230,20 @@ class MPSolver { // (They are listed in the order in which they were created.) const std::vector& variables() const { return variables_; } // Look up a variable by name, and return NULL if it does not exist. - MPVariable* LookupVariableOrNull(const string& var_name) const; + MPVariable* LookupVariableOrNull(const std::string& var_name) const; // Creates a variable with the given bounds, integrality requirement // and name. Bounds can be finite or +/- MPSolver::infinity(). // The MPSolver owns the variable (i.e. the returned pointer is borrowed). // Variable names must be unique (it may crash otherwise). Empty variable // names are allowed, an automated variable name will then be assigned. - MPVariable* MakeVar(double lb, double ub, bool integer, const string& name); + MPVariable* MakeVar(double lb, double ub, bool integer, const std::string& name); // Creates a continuous variable. - MPVariable* MakeNumVar(double lb, double ub, const string& name); + MPVariable* MakeNumVar(double lb, double ub, const std::string& name); // Creates an integer variable. - MPVariable* MakeIntVar(double lb, double ub, const string& name); + MPVariable* MakeIntVar(double lb, double ub, const std::string& name); // Creates a boolean variable. - MPVariable* MakeBoolVar(const string& name); + MPVariable* MakeBoolVar(const std::string& name); // Creates an array of variables. All variables created have the // same bounds and integrality requirement. If nb <= 0, no variables are @@ -255,23 +254,23 @@ class MPSolver { double lb, double ub, bool integer, - const string& name_prefix, + const std::string& name_prefix, std::vector* vars); // Creates an array of continuous variables. void MakeNumVarArray(int nb, double lb, double ub, - const string& name, + const std::string& name, std::vector* vars); // Creates an array of integer variables. void MakeIntVarArray(int nb, double lb, double ub, - const string& name, + const std::string& name, std::vector* vars); // Creates an array of boolean variables. void MakeBoolVarArray(int nb, - const string& name, + const std::string& name, std::vector* vars); // ----- Constraints ----- @@ -281,7 +280,7 @@ class MPSolver { // (They are listed in the order in which they were created.) const std::vector& constraints() const { return constraints_; } // Look up a constraint by name, and return NULL if it does not exist. - MPConstraint* LookupConstraintOrNull(const string& constraint_name) const; + MPConstraint* LookupConstraintOrNull(const std::string& constraint_name) const; // Creates a linear constraint with given bounds. Bounds can be // finite or +/- MPSolver::infinity(). The MPSolver class assumes @@ -291,9 +290,9 @@ class MPSolver { // Creates a constraint with -infinity and +infinity bounds. MPConstraint* MakeRowConstraint(); // Creates a named constraint with given bounds. - MPConstraint* MakeRowConstraint(double lb, double ub, const string& name); + MPConstraint* MakeRowConstraint(double lb, double ub, const std::string& name); // Creates a named constraint with -infinity and +infinity bounds. - MPConstraint* MakeRowConstraint(const string& name); + MPConstraint* MakeRowConstraint(const std::string& name); // ----- Objective ----- // Note that the objective is owned by the solver, and is initialized to @@ -416,9 +415,9 @@ class MPSolver { // Shortcuts to the homonymous MPModelProtoExporter methods, via // exporting to a MPModelProto with ExportModelToNewProto() (see above). - bool ExportModelAsLpFormat(bool obfuscated, string* model_str); + bool ExportModelAsLpFormat(bool obfuscated, std::string* model_str); bool ExportModelAsMpsFormat( - bool fixed_format, bool obfuscated, string* model_str); + bool fixed_format, bool obfuscated, std::string* model_str); // ----- Misc ----- @@ -429,7 +428,7 @@ class MPSolver { // TODO(user): Currently SCIP will always return true even if the format is // wrong (you can check the log if you suspect an issue there). This seems to // be a bug in SCIP though. - bool SetSolverSpecificParametersAsString(const string& parameters); + bool SetSolverSpecificParametersAsString(const std::string& parameters); // Advanced usage: possible basis status values for a variable and the // slack variable of a linear constraint. @@ -492,8 +491,8 @@ class MPSolver { return var_and_constraint_names_allow_export_; } - // Returns a string describing the underlying solver and its version. - string SolverVersion() const; + // Returns a std::string describing the underlying solver and its version. + std::string SolverVersion() const; // Advanced usage: returns the underlying solver so that the user // can use solver-specific features or features that are not exposed @@ -579,7 +578,7 @@ class MPSolver { bool HasInfeasibleConstraints() const; // The name of the linear programming problem. - const string name_; + const std::string name_; // The type of the linear programming problem. const OptimizationProblemType problem_type_; @@ -590,12 +589,12 @@ class MPSolver { // The vector of variables in the problem. std::vector variables_; // A map from a variable's name to its index in variables_. - hash_map variable_name_to_index_; + hash_map variable_name_to_index_; // The vector of constraints in the problem. std::vector constraints_; // A map from a constraint's name to its index in constraints_. - hash_map constraint_name_to_index_; + hash_map constraint_name_to_index_; // The linear objective function. std::unique_ptr objective_; @@ -609,7 +608,7 @@ class MPSolver { WallTimer timer_; // Permanent storage for SetSolverSpecificParametersAsString(). - string solver_specific_parameter_string_; + std::string solver_specific_parameter_string_; DISALLOW_COPY_AND_ASSIGN(MPSolver); @@ -714,7 +713,7 @@ class MPObjective { class MPVariable { public: // Returns the name of the variable. - const string& name() const { return name_; } + const std::string& name() const { return name_; } // Sets the integrality requirement of the variable. void SetInteger(bool integer); @@ -766,7 +765,7 @@ class MPVariable { // Constructor. A variable points to a single MPSolverInterface that // is specified in the constructor. A variable cannot belong to // several models. - MPVariable(double lb, double ub, bool integer, const string& name, + MPVariable(double lb, double ub, bool integer, const std::string& name, MPSolverInterface* const interface) : lb_(lb), ub_(ub), integer_(integer), name_(name), index_(-1), solution_value_(0.0), reduced_cost_(0.0), interface_(interface) {} @@ -779,7 +778,7 @@ class MPVariable { double lb_; double ub_; bool integer_; - const string name_; + const std::string name_; int index_; double solution_value_; double reduced_cost_; @@ -792,7 +791,7 @@ class MPVariable { class MPConstraint { public: // Returns the name of the constraint. - const string& name() const { return name_; } + const std::string& name() const { return name_; } // Clears all variables and coefficients. Does not clear the bounds. void Clear(); @@ -860,7 +859,7 @@ class MPConstraint { // to several models. MPConstraint(double lb, double ub, - const string& name, + const std::string& name, MPSolverInterface* const interface) : coefficients_(1), lb_(lb), ub_(ub), name_(name), is_lazy_(false), index_(-1), dual_value_(0.0), activity_(0.0), interface_(interface) {} @@ -884,7 +883,7 @@ class MPConstraint { double ub_; // Name. - const string name_; + const std::string name_; // True if the constraint is "lazy", i.e. the constraint is added to the // underlying Linear Programming solver only if it is violated. @@ -1203,8 +1202,8 @@ class MPSolverInterface { return result_status_; } - // Returns a string describing the underlying solver and its version. - virtual string SolverVersion() const = 0; + // Returns a std::string describing the underlying solver and its version. + virtual std::string SolverVersion() const = 0; // Returns the underlying solver. virtual void* underlying_solver() = 0; @@ -1282,12 +1281,12 @@ class MPSolverInterface { // Reads a solver-specific file of parameters and set them. // Returns true if there was no errors. - virtual bool ReadParameterFile(const string& filename); + virtual bool ReadParameterFile(const std::string& filename); // Returns a file extension like ".tmp", this is needed because some solvers // require a given extension for the ReadParameterFile() filename and we need // to know it to generate a temporary parameter file. - virtual string ValidFileExtensionForParameterFile() const; + virtual std::string ValidFileExtensionForParameterFile() const; // Sets the scaling mode. virtual void SetScalingMode(int value) = 0; diff --git a/src/linear_solver/linear_solver.swig b/src/linear_solver/linear_solver.swig index 9e82d8158e..e3e1bbe69a 100644 --- a/src/linear_solver/linear_solver.swig +++ b/src/linear_solver/linear_solver.swig @@ -524,7 +524,7 @@ namespace operations_research { %ignore MPSolver::MakeNumVarArray; %ignore MPSolver::MakeIntVarArray; %ignore MPSolver::MakeBoolVarArray; -// The following 3 methods that use protocol buffers as output +// The following 6 methods that use protocol buffers as output // arguments are replaced by methods that return a protocol buffer, // see code below. %ignore MPSolver::ExportModelToNewProto; diff --git a/src/linear_solver/linear_solver_ext.h b/src/linear_solver/linear_solver_ext.h index 8d90decede..3ee1e147d9 100644 --- a/src/linear_solver/linear_solver_ext.h +++ b/src/linear_solver/linear_solver_ext.h @@ -31,14 +31,12 @@ #include "base/hash.h" #include "linear_solver/linear_solver.h" -using std::string; - #if defined(USE_SLM) extern "C" { #include "sulumc.h" } - + #endif namespace operations_research { diff --git a/src/linear_solver/model_exporter.cc b/src/linear_solver/model_exporter.cc index 9cb894dd2a..2451a4cdc2 100644 --- a/src/linear_solver/model_exporter.cc +++ b/src/linear_solver/model_exporter.cc @@ -42,7 +42,7 @@ MPModelProtoExporter::MPModelProtoExporter(const MPModelProto& proto) : } // Note(user): This method is static. It is also used by MPSolver. -bool MPModelProtoExporter::CheckNameValidity(const string& name) { +bool MPModelProtoExporter::CheckNameValidity(const std::string& name) { if (name.empty()) { LOG(WARNING) << "CheckNameValidity() should not be passed an empty name."; return false; @@ -55,16 +55,16 @@ bool MPModelProtoExporter::CheckNameValidity(const string& name) { << " Will be unable to write model to file."; return false; } - const string kForbiddenChars = " +-*/<>=:\\"; - if (name.find_first_of(kForbiddenChars) != string::npos) { + const std::string kForbiddenChars = " +-*/<>=:\\"; + if (name.find_first_of(kForbiddenChars) != std::string::npos) { LOG(WARNING) << "Invalid name " << name << " contains forbidden character: " << kForbiddenChars << " or space." << " Will be unable to write model to file."; return false; } - const string kForbiddenFirstChars = "$.0123456789"; - if (kForbiddenFirstChars.find(name[0]) != string::npos) { + const std::string kForbiddenFirstChars = "$.0123456789"; + if (kForbiddenFirstChars.find(name[0]) != std::string::npos) { LOG(WARNING) << "Invalid name " << name << ". First character is one of: " << kForbiddenFirstChars << " Will be unable to write model to file."; @@ -74,7 +74,7 @@ bool MPModelProtoExporter::CheckNameValidity(const string& name) { } -string MPModelProtoExporter::GetVariableName(int var_index) const { +std::string MPModelProtoExporter::GetVariableName(int var_index) const { const MPVariableProto& var_proto = proto_.variables(var_index); if (use_obfuscated_names_ || !var_proto.has_id()) { return StringPrintf("V%0*d", num_digits_for_variables_, var_index); @@ -83,7 +83,7 @@ string MPModelProtoExporter::GetVariableName(int var_index) const { } } -string MPModelProtoExporter::GetConstraintName(int cst_index) const { +std::string MPModelProtoExporter::GetConstraintName(int cst_index) const { const MPConstraintProto& ct_proto = proto_.constraints(cst_index); if (use_obfuscated_names_ || !ct_proto.has_id()) { return StringPrintf("C%0*d", num_digits_for_constraints_, cst_index); @@ -93,7 +93,7 @@ string MPModelProtoExporter::GetConstraintName(int cst_index) const { } void MPModelProtoExporter::AppendComments( - const string& separator, string* output) const { + const std::string& separator, std::string* output) const { const char* const sep = separator.c_str(); StringAppendF(output, "%s Generated by MPModelProtoExporter\n", sep); StringAppendF(output, "%s %-16s : %s\n", sep, "Name", @@ -113,14 +113,14 @@ void MPModelProtoExporter::AppendComments( } bool MPModelProtoExporter::AppendLpTerm(const MPTermProto& term_proto, - string* output) const { - const string& id = term_proto.variable_id(); + std::string* output) const { + const std::string& id = term_proto.variable_id(); const int var_index = FindWithDefault(var_id_to_index_map_, id, -1); if (var_index == -1) { LOG(DFATAL) << "Reference to non-existent variable with id " << id; return false; } - const string var_name = GetVariableName(var_index); + const std::string var_name = GetVariableName(var_index); const double coeff = term_proto.coefficient(); if (coeff == 0.0) return true; StringAppendF(output, "%+.16G %-s ", coeff, var_name.c_str()); @@ -137,7 +137,7 @@ bool MPModelProtoExporter::Setup() { var_id_to_index_map_.clear(); for (int var_index = 0; var_index < proto_.variables_size(); ++var_index) { const MPVariableProto& var_proto = proto_.variables(var_index); - const string& id = var_proto.id(); + const std::string& id = var_proto.id(); if (!ContainsKey(var_id_to_index_map_, id)) { const double lb = var_proto.lb(); const double ub = var_proto.ub(); @@ -175,7 +175,7 @@ bool MPModelProtoExporter::CheckAllNamesValidity() const { } bool MPModelProtoExporter::ExportModelAsLpFormat(bool obfuscated, - string* output) { + std::string* output) { // TODO(user): // - Sort constraints by category (implication, knapsack, logical or, etc...). @@ -212,7 +212,7 @@ bool MPModelProtoExporter::ExportModelAsLpFormat(bool obfuscated, StringAppendF(output, "\nSubject to\n"); for (int cst_index = 0; cst_index < proto_.constraints_size(); ++cst_index) { const MPConstraintProto& ct_proto = proto_.constraints(cst_index); - string term; + std::string term; for (int k = 0; k < ct_proto.terms_size(); ++k) { if (!AppendLpTerm(ct_proto.terms(k), &term)) { return false; @@ -220,13 +220,13 @@ bool MPModelProtoExporter::ExportModelAsLpFormat(bool obfuscated, } const double lb = ct_proto.lb(); const double ub = ct_proto.ub(); - string name = GetConstraintName(cst_index); + std::string name = GetConstraintName(cst_index); if (lb == ub) { StringAppendF(output, " %s: %s = %-.16G\n", name.c_str(), term.c_str(), ub); } else { if (ub != +std::numeric_limits::infinity()) { - string rhs_name = name; + std::string rhs_name = name; if (lb != -std::numeric_limits::infinity()) { rhs_name += "_rhs"; } @@ -234,7 +234,7 @@ bool MPModelProtoExporter::ExportModelAsLpFormat(bool obfuscated, rhs_name.c_str(), term.c_str(), ub); } if (lb != -std::numeric_limits::infinity()) { - string lhs_name = name; + std::string lhs_name = name; if (ub != +std::numeric_limits::infinity()) { lhs_name += "_lhs"; } @@ -296,11 +296,11 @@ bool MPModelProtoExporter::ExportModelAsLpFormat(bool obfuscated, } void MPModelProtoExporter::AppendMpsPair( - const string& name, double value, string* output) const { + const std::string& name, double value, std::string* output) const { const int kFixedMpsDoubleWidth = 12; if (use_fixed_mps_format_) { int precision = kFixedMpsDoubleWidth; - string value_str = StringPrintf("%.*G", precision, value); + std::string value_str = StringPrintf("%.*G", precision, value); // Use the largest precision that can fit into the field witdh. while (value_str.size() > kFixedMpsDoubleWidth) { --precision; @@ -314,21 +314,21 @@ void MPModelProtoExporter::AppendMpsPair( } void MPModelProtoExporter::AppendMpsLineHeader( - const string& id, const string& name, string* output) const { + const std::string& id, const std::string& name, std::string* output) const { StringAppendF(output, use_fixed_mps_format_ ? " %-2s %-8s" : " %-2s %-16s", id.c_str(), name.c_str()); } void MPModelProtoExporter::AppendMpsLineHeaderWithNewLine( - const string& id, const string& name, string* output) const { + const std::string& id, const std::string& name, std::string* output) const { AppendMpsLineHeader(id, name, output); *output += "\n"; } void MPModelProtoExporter::AppendMpsTermWithContext( - const string& head_name, const string& name, double value, string* output) { + const std::string& head_name, const std::string& name, double value, std::string* output) { if (current_mps_column_ == 0) { AppendMpsLineHeader("", head_name, output); } @@ -337,14 +337,14 @@ void MPModelProtoExporter::AppendMpsTermWithContext( } void MPModelProtoExporter::AppendMpsBound( - const string& bound_type, const string& name, double value, - string* output) const { + const std::string& bound_type, const std::string& name, double value, + std::string* output) const { AppendMpsLineHeader(bound_type, "BOUND", output); AppendMpsPair(name, value, output); *output += "\n"; } -void MPModelProtoExporter::AppendNewLineIfTwoColumns(string* output) { +void MPModelProtoExporter::AppendNewLineIfTwoColumns(std::string* output) { ++current_mps_column_; if (current_mps_column_ == 2) { *output += "\n"; @@ -361,14 +361,14 @@ bool MPModelProtoExporter::CanUseFixedMpsFormat() const { } for (int cst_index = 0; cst_index < proto_.constraints_size(); ++cst_index) { const MPConstraintProto& ct_proto = proto_.constraints(cst_index); - const string& ct_id = ct_proto.id(); + const std::string& ct_id = ct_proto.id(); if (ct_id.size() > kMpsFieldSize) { return false; } } for (int var_index = 0; var_index < proto_.variables_size(); ++var_index) { const MPVariableProto& var_proto = proto_.variables(var_index); - const string& var_id = var_proto.id(); + const std::string& var_id = var_proto.id(); if (var_id.size() > kMpsFieldSize) { return false; } @@ -378,7 +378,7 @@ bool MPModelProtoExporter::CanUseFixedMpsFormat() const { bool MPModelProtoExporter::ExportModelAsMpsFormat(bool fixed_format, bool obfuscated, - string* output) { + std::string* output) { if (!obfuscated && !CheckAllNamesValidity()) { return false; } @@ -404,13 +404,13 @@ bool MPModelProtoExporter::ExportModelAsMpsFormat(bool fixed_format, // ROWS section. current_mps_column_ = 0; - string rows_section; + std::string rows_section; AppendMpsLineHeaderWithNewLine("N", "COST", &rows_section); for (int cst_index = 0; cst_index < proto_.constraints_size(); ++cst_index) { const MPConstraintProto& ct_proto = proto_.constraints(cst_index); const double lb = ct_proto.lb(); const double ub = ct_proto.ub(); - const string cst_name = GetConstraintName(cst_index); + const std::string cst_name = GetConstraintName(cst_index); if (lb == ub && lb != 0.0) { AppendMpsLineHeaderWithNewLine("E", cst_name, &rows_section); } else if (lb == -std::numeric_limits::infinity()) { @@ -433,7 +433,7 @@ bool MPModelProtoExporter::ExportModelAsMpsFormat(bool fixed_format, const MPConstraintProto& ct_proto = proto_.constraints(cst_index); for (int k = 0; k < ct_proto.terms_size(); ++k) { const MPTermProto& term_proto = ct_proto.terms(k); - const string& id = term_proto.variable_id(); + const std::string& id = term_proto.variable_id(); const int var_index = FindWithDefault(var_id_to_index_map_, id, -1); if (var_index == -1) { LOG(DFATAL) << "Non-existent variable with id " << id @@ -453,7 +453,7 @@ bool MPModelProtoExporter::ExportModelAsMpsFormat(bool fixed_format, std::vector objective(proto_.variables_size(), 0.0); for (int k = 0; k < proto_.objective_terms_size(); ++k) { const MPTermProto& term_proto = proto_.objective_terms(k); - const string& id = term_proto.variable_id(); + const std::string& id = term_proto.variable_id(); const int var_index = FindWithDefault(var_id_to_index_map_, id, -1); if (var_index == -1) { LOG(DFATAL) << "Non-existent variable with id " << id @@ -465,11 +465,11 @@ bool MPModelProtoExporter::ExportModelAsMpsFormat(bool fixed_format, // COLUMNS section. current_mps_column_ = 0; - string columns_section; + std::string columns_section; const char* const kIntMarkerFormat = " %-10s%-36s%-10s\n"; for (int var_index = 0; var_index < proto_.variables_size(); ++var_index) { const MPVariableProto& var_proto = proto_.variables(var_index); - const string var_name = GetVariableName(var_index); + const std::string var_name = GetVariableName(var_index); current_mps_column_ = 0; if (var_proto.integer()) { StringAppendF(&columns_section, kIntMarkerFormat, @@ -484,7 +484,7 @@ bool MPModelProtoExporter::ExportModelAsMpsFormat(bool fixed_format, const std::pair p = transpose[var_index][k]; const int cst_index = p.first; const double coeff = p.second; - const string cst_name = GetConstraintName(cst_index); + const std::string cst_name = GetConstraintName(cst_index); AppendMpsTermWithContext( var_name, cst_name, coeff, &columns_section); } @@ -502,12 +502,12 @@ bool MPModelProtoExporter::ExportModelAsMpsFormat(bool fixed_format, // RHS (right-hand-side) section. current_mps_column_ = 0; - string rhs_section; + std::string rhs_section; for (int cst_index = 0; cst_index < proto_.constraints_size(); ++cst_index) { const MPConstraintProto& ct_proto = proto_.constraints(cst_index); const double lb = ct_proto.lb(); const double ub = ct_proto.ub(); - const string cst_name = GetConstraintName(cst_index); + const std::string cst_name = GetConstraintName(cst_index); if (lb != -std::numeric_limits::infinity()) { AppendMpsTermWithContext("RHS", cst_name, lb, &rhs_section); } else if (ub != +std::numeric_limits::infinity()) { @@ -521,12 +521,12 @@ bool MPModelProtoExporter::ExportModelAsMpsFormat(bool fixed_format, // RANGES section. current_mps_column_ = 0; - string ranges_section; + std::string ranges_section; for (int cst_index = 0; cst_index < proto_.constraints_size(); ++cst_index) { const MPConstraintProto& ct_proto = proto_.constraints(cst_index); const double range = fabs(ct_proto.ub() - ct_proto.lb()); if (range != 0.0 && range != +std::numeric_limits::infinity()) { - const string cst_name = GetConstraintName(cst_index); + const std::string cst_name = GetConstraintName(cst_index); AppendMpsTermWithContext("RANGE", cst_name, range, &ranges_section); } } @@ -537,12 +537,12 @@ bool MPModelProtoExporter::ExportModelAsMpsFormat(bool fixed_format, // BOUNDS section. current_mps_column_ = 0; - string bounds_section; + std::string bounds_section; for (int var_index = 0; var_index < proto_.variables_size(); ++var_index) { const MPVariableProto& var_proto = proto_.variables(var_index); const double lb = var_proto.lb(); const double ub = var_proto.ub(); - const string var_name = GetVariableName(var_index); + const std::string var_name = GetVariableName(var_index); if (var_proto.integer()) { if (lb == 0.0 && ub == 1.0) { AppendMpsLineHeader("BV", "BOUND", &bounds_section); diff --git a/src/linear_solver/model_exporter.h b/src/linear_solver/model_exporter.h index 60c571d531..aefa80afb2 100644 --- a/src/linear_solver/model_exporter.h +++ b/src/linear_solver/model_exporter.h @@ -18,7 +18,6 @@ #include "base/macros.h" #include "base/hash.h" -using std::string; namespace operations_research { @@ -33,7 +32,7 @@ class MPModelProtoExporter { // The argument must live as long as this class is active. explicit MPModelProtoExporter(const MPModelProto& proto); - // Outputs the current model (variables, constraints, objective) as a string + // Outputs the current model (variables, constraints, objective) as a std::string // encoded in the so-called "CPLEX LP file format" as generated by SCIP. // The LP file format is easily readable by a human. // Returns false if some error has occurred during execution. @@ -46,9 +45,9 @@ class MPModelProtoExporter { // http://lpsolve.sourceforge.net/5.5/CPLEX-format.htm // http://tinyurl.com/cplex-lp-format // http://www.gurobi.com/documentation/5.1/reference-manual/node871 - bool ExportModelAsLpFormat(bool obfuscated, string* model_str); + bool ExportModelAsLpFormat(bool obfuscated, std::string* model_str); - // Outputs the current model (variables, constraints, objective) as a string + // Outputs the current model (variables, constraints, objective) as a std::string // encoded in MPS file format, using the "fixed" MPS format if possible, // and the "free" MPS format otherwise. // Returns false if some error has occurred during execution. @@ -71,7 +70,7 @@ class MPModelProtoExporter { // http://www.gurobi.com/documentation/5.1/reference-manual/node869 bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscated, - string* model_str); + std::string* model_str); // Checks the validity of a variable or constraint name. // Used by MPSolver::CheckAllNamesValidity and @@ -83,7 +82,7 @@ class MPModelProtoExporter { // - name contains space or a character in "+-*/<>=:\". // If name is empty, a message is issued to LOG(DFATAL). For all the other // cases which return false, a message is issued to LOG(WARNING). - static bool CheckNameValidity(const string& name); + static bool CheckNameValidity(const std::string& name); private: // This scans the Model proto and sets up all the internal data structures @@ -101,13 +100,13 @@ class MPModelProtoExporter { // returns the variable name, otherwise returns a name in the form // "V00123" where "00123" corresponds to the variable number. The format // width of the number depends on the number of variables in the model. - string GetVariableName(int var_index) const; + std::string GetVariableName(int var_index) const; // If use_obfuscated_names_ is false and the constraint number cst_index has // a name, returns the constraint name, otherwise returns a name in the form // "C00123" where "00123" corresponds to the constraint number. The format // width of the number depends on the number of constraints in the model. - string GetConstraintName(int cst_index) const; + std::string GetConstraintName(int cst_index) const; // Returns true when the fixed MPS format can be used. // The fixed format is used when the variable and constraint names do not @@ -117,45 +116,45 @@ class MPModelProtoExporter { // Appends a general "Comment" section with useful metadata about the model // to "output". - void AppendComments(const string& separator, string* output) const; + void AppendComments(const std::string& separator, std::string* output) const; // Appends a term to "output", in "Lp" format. - bool AppendLpTerm(const MPTermProto& term_proto, string* output) const; + bool AppendLpTerm(const MPTermProto& term_proto, std::string* output) const; // Appends a pair name, value to "output", formatted to comply with the MPS // standard. - void AppendMpsPair(const string& name, double value, string* output) const; + void AppendMpsPair(const std::string& name, double value, std::string* output) const; // Appends the head of a line, consisting of an id and a name to output. - void AppendMpsLineHeader(const string& id, const string& name, - string* output) const; + void AppendMpsLineHeader(const std::string& id, const std::string& name, + std::string* output) const; // Same as AppendMpsLineHeader. Appends an extra new-line at the end the - // string pointed to by output. - void AppendMpsLineHeaderWithNewLine(const string& id, const string& name, - string* output) const; + // std::string pointed to by output. + void AppendMpsLineHeaderWithNewLine(const std::string& id, const std::string& name, + std::string* output) const; // Appends an MPS term in various contexts. The term consists of a head name, // a name, and a value. If the line is not empty, then only the pair // (name, value) is appended. The number of columns, limited to 2 by the MPS // format is also taken care of. - void AppendMpsTermWithContext(const string& head_name, const string& name, - double value, string* output); + void AppendMpsTermWithContext(const std::string& head_name, const std::string& name, + double value, std::string* output); // Appends a new-line if two columns are already present on the MPS line. // Used by and in complement to AppendMpsTermWithContext. - void AppendNewLineIfTwoColumns(string* output); + void AppendNewLineIfTwoColumns(std::string* output); // Appends a line describing the bound of a variablenew-line if two columns // are already present on the MPS line. // Used by and in complement to AppendMpsTermWithContext. - void AppendMpsBound(const string& bound_type, const string& name, - double value, string* output) const; + void AppendMpsBound(const std::string& bound_type, const std::string& name, + double value, std::string* output) const; const MPModelProto& proto_; // Maps a variable id to its index in the protobuf. - hash_map var_id_to_index_map_; + hash_map var_id_to_index_map_; // Number of integer variables in proto_. int num_integer_variables_; diff --git a/src/linear_solver/proto_tools.cc b/src/linear_solver/proto_tools.cc index 121fd2106f..58516090bd 100644 --- a/src/linear_solver/proto_tools.cc +++ b/src/linear_solver/proto_tools.cc @@ -41,10 +41,10 @@ bool ConvertOldMPModelProtoToNew(const MPModelProto& src_proto, } dest_proto->set_name(src_proto.name()); - hash_map var_id_to_index_map; + hash_map var_id_to_index_map; for (int var_index = 0; var_index < src_proto.variables_size(); ++var_index) { const MPVariableProto& var_proto = src_proto.variables(var_index); - const string& id = var_proto.id(); + const std::string& id = var_proto.id(); if (ContainsKey(var_id_to_index_map, id)) { LOG(DFATAL) << "Duplicate variable id found: " << id; return false; @@ -54,7 +54,7 @@ bool ConvertOldMPModelProtoToNew(const MPModelProto& src_proto, std::vector objective(src_proto.variables_size(), 0.0); for (int k = 0; k < src_proto.objective_terms_size(); ++k) { const MPTermProto& term_proto = src_proto.objective_terms(k); - const string& id = term_proto.variable_id(); + const std::string& id = term_proto.variable_id(); const int var_index = FindWithDefault(var_id_to_index_map, id, -1); if (var_index == -1) { LOG(DFATAL) << "Non-existent variable with id " << id @@ -81,17 +81,15 @@ bool ConvertOldMPModelProtoToNew(const MPModelProto& src_proto, new_cst->set_name(ct_proto.id()); for (int k = 0; k < ct_proto.terms_size(); ++k) { const MPTermProto& term_proto = ct_proto.terms(k); - const string& id = term_proto.variable_id(); + const std::string& id = term_proto.variable_id(); const int var_index = FindWithDefault(var_id_to_index_map, id, -1); if (var_index == -1) { LOG(DFATAL) << "Non-existent variable with id " << id << " used in constraint # " << cst_index << "."; return false; } - new_proto::MPConstraintProto::UnaryTerm* new_term = - new_cst->add_linear_term(); - new_term->set_var_index(var_index); - new_term->set_coefficient(term_proto.coefficient()); + new_cst->add_var_index(var_index); + new_cst->add_coefficient(term_proto.coefficient()); } } return true; @@ -108,10 +106,10 @@ bool ConvertNewMPModelProtoToOld(const new_proto::MPModelProto& src_proto, // Note(user): we assume the name to be suitable as ids. If not, the generated // proto will be invalid (which will be detected when trying to solve it). // TODO(user): detect this now? - std::vector var_index_to_id; + std::vector var_index_to_id; for (int i = 0; i < src_proto.variable_size(); ++i) { const new_proto::MPVariableProto& var_proto = src_proto.variable(i); - const string& id = var_proto.name(); + const std::string& id = var_proto.name(); var_index_to_id.push_back(id); // Create the variables. @@ -138,24 +136,31 @@ bool ConvertNewMPModelProtoToOld(const new_proto::MPModelProto& src_proto, new_cst->set_id(cst_proto.name()); // Copy the linear terms. - for (int k = 0; k < cst_proto.linear_term_size(); ++k) { - const new_proto::MPConstraintProto::UnaryTerm& term_proto - = cst_proto.linear_term(k); + // TODO(user): test this error in unittests. + if (cst_proto.var_index_size() != cst_proto.coefficient_size()) { + LOG(ERROR) << "In constraint #" << i << " (name: '" << cst_proto.name() + << "'):" << " var_index_size() != coefficient_size()" + << cst_proto.DebugString(); + return false; + } + for (int k = 0; k < cst_proto.var_index_size(); ++k) { + const int var_index = cst_proto.var_index(k); MPTermProto* new_term = new_cst->add_terms(); - if (term_proto.var_index() >= var_index_to_id.size()) { + if (var_index >= var_index_to_id.size() || + var_index < 0) { LOG(DFATAL) << "Variable index out of bound in constraint named " << cst_proto.name() << "."; return false; } - new_term->set_variable_id(var_index_to_id[term_proto.var_index()]); - new_term->set_coefficient(term_proto.coefficient()); + new_term->set_variable_id(var_index_to_id[var_index]); + new_term->set_coefficient(cst_proto.coefficient(k)); } } return true; } -bool ReadFileToProto(const string& file_name, google::protobuf::Message* proto) { - string data; +bool ReadFileToProto(const std::string& file_name, google::protobuf::Message* proto) { + std::string data; file::GetContents(file_name, &data, file::Defaults()).CheckSuccess(); // Note that gzipped files are currently not supported. // Try binary format first, then text format, then give up. @@ -166,12 +171,12 @@ bool ReadFileToProto(const string& file_name, google::protobuf::Message* proto) } bool WriteProtoToFile( - const string& file_name, const google::protobuf::Message& proto, + const std::string& file_name, const google::protobuf::Message& proto, bool binary, bool gzipped) { // Note that gzipped files are currently not supported. gzipped = false; - string output_string; + std::string output_string; google::protobuf::io::StringOutputStream stream(&output_string); if (binary) { if (!proto.SerializeToZeroCopyStream(&stream)) { @@ -180,10 +185,10 @@ bool WriteProtoToFile( } } else { if (!google::protobuf::TextFormat::PrintToString(proto, &output_string)) { - LOG(WARNING) << "Printing to string failed."; + LOG(WARNING) << "Printing to std::string failed."; } } - const string output_file_name = + const std::string output_file_name = StrCat(file_name, binary ? ".bin" : "", gzipped ? ".gz" : ""); VLOG(1) << "Writing " << output_string.size() << " bytes to " << output_file_name; @@ -197,9 +202,9 @@ bool WriteProtoToFile( namespace { void WriteFullProtocolMessage(const google::protobuf::Message& message, - int indent_level, string* out) { - string temp_string; - const string indent(indent_level * 2, ' '); + int indent_level, std::string* out) { + std::string temp_string; + const std::string indent(indent_level * 2, ' '); const Descriptor* desc = message.GetDescriptor(); const Reflection* refl = message.GetReflection(); for (int i = 0; i < desc->field_count(); ++i) { @@ -225,9 +230,9 @@ void WriteFullProtocolMessage(const google::protobuf::Message& message, } } // namespace -string FullProtocolMessageAsString( +std::string FullProtocolMessageAsString( const google::protobuf::Message& message, int indent_level) { - string message_str; + std::string message_str; WriteFullProtocolMessage(message, indent_level, &message_str); return message_str; } diff --git a/src/linear_solver/proto_tools.h b/src/linear_solver/proto_tools.h index 9ee73f0904..976609ae97 100644 --- a/src/linear_solver/proto_tools.h +++ b/src/linear_solver/proto_tools.h @@ -14,7 +14,6 @@ #define OR_TOOLS_LINEAR_SOLVER_PROTO_TOOLS_H_ #include -using std::string; #include "linear_solver/linear_solver.pb.h" #include "linear_solver/linear_solver2.pb.h" @@ -33,20 +32,20 @@ bool ConvertNewMPModelProtoToOld(const new_proto::MPModelProto& src_proto, // Exactly like file::ReadFileToProto() but also supports GZipped files. // TODO(user): move this to ../util ? -bool ReadFileToProto(const string& file_name, google::protobuf::Message* proto); +bool ReadFileToProto(const std::string& file_name, google::protobuf::Message* proto); // Like file::WriteProtoToFile() or file::WriteProtoToASCIIFile(), but also // supports GZipped output. // If 'binary'is true, ".bin" is appended to file_name. // If 'gzipped'is true, ".gz" is appended to file_name. // TODO(user): move this to ../util ? -bool WriteProtoToFile(const string& file_name, const google::protobuf::Message& proto, +bool WriteProtoToFile(const std::string& file_name, const google::protobuf::Message& proto, bool binary, bool gzipped); -// Prints a proto2 message as a string, it behaves like TextFormat::Print() +// Prints a proto2 message as a std::string, it behaves like TextFormat::Print() // but also prints the default values of unset fields which is useful for // printing parameters. -string FullProtocolMessageAsString( +std::string FullProtocolMessageAsString( const google::protobuf::Message& message, int indent_level); } // namespace operations_research diff --git a/src/linear_solver/scip_interface.cc b/src/linear_solver/scip_interface.cc index c96491565c..70d9673f3a 100644 --- a/src/linear_solver/scip_interface.cc +++ b/src/linear_solver/scip_interface.cc @@ -117,7 +117,7 @@ class SCIPInterface : public MPSolverInterface { virtual void ExtractNewConstraints(); virtual void ExtractObjective(); - virtual string SolverVersion() const { + virtual std::string SolverVersion() const { return StringPrintf("SCIP %d.%d.%d [LP solver: %s]", SCIPmajorVersion(), SCIPminorVersion(), SCIPtechVersion(), SCIPlpiGetSolverName()); @@ -138,8 +138,8 @@ class SCIPInterface : public MPSolverInterface { virtual void SetScalingMode(int value); virtual void SetLpAlgorithm(int value); - virtual bool ReadParameterFile(const string& filename); - virtual string ValidFileExtensionForParameterFile() const; + virtual bool ReadParameterFile(const std::string& filename); + virtual std::string ValidFileExtensionForParameterFile() const; void CreateSCIP(); void DeleteSCIP(); @@ -654,11 +654,11 @@ void SCIPInterface::SetLpAlgorithm(int value) { } } -bool SCIPInterface::ReadParameterFile(const string& filename) { +bool SCIPInterface::ReadParameterFile(const std::string& filename) { return SCIPreadParams(scip_, filename.c_str()) == SCIP_OKAY; } -string SCIPInterface::ValidFileExtensionForParameterFile() const { +std::string SCIPInterface::ValidFileExtensionForParameterFile() const { return ".set"; } diff --git a/src/linear_solver/sulum_interface.cc b/src/linear_solver/sulum_interface.cc index c767357858..ab73985229 100644 --- a/src/linear_solver/sulum_interface.cc +++ b/src/linear_solver/sulum_interface.cc @@ -131,7 +131,7 @@ class SLMInterface : public MPSolverInterface { // ----- Misc ----- // Write model - virtual void WriteModel(const string& filename); + virtual void WriteModel(const std::string& filename); // Query problem type. virtual bool IsContinuous() const { return IsLP(); } @@ -142,7 +142,7 @@ class SLMInterface : public MPSolverInterface { virtual void ExtractNewConstraints(); virtual void ExtractObjective(); - virtual string SolverVersion() const { + virtual std::string SolverVersion() const { int major,minor,interim; SlmGetSulumVersion(&major,&minor,&interim); @@ -232,7 +232,7 @@ void SLMInterface::Reset() { ResetExtractionInformation(); } -void SLMInterface::WriteModel(const string& filename) { +void SLMInterface::WriteModel(const std::string& filename) { CheckReturnKey(SlmWriteProblem(model_, filename.c_str())); } diff --git a/src/sat/boolean_problem.cc b/src/sat/boolean_problem.cc index 2e7ca26706..a0b57af7b0 100644 --- a/src/sat/boolean_problem.cc +++ b/src/sat/boolean_problem.cc @@ -169,8 +169,8 @@ bool IsAssignmentValid(const LinearBooleanProblem& problem, // max-sat problem. Namely that the slack variable from the constraints are // always in first position, and appears in the same order in the objective and // in the constraints. -string LinearBooleanProblemToCnfString(const LinearBooleanProblem& problem) { - string output; +std::string LinearBooleanProblemToCnfString(const LinearBooleanProblem& problem) { + std::string output; const bool is_wcnf = (problem.type() == LinearBooleanProblem::MINIMIZATION); const LinearObjective& objective = problem.objective(); diff --git a/src/sat/boolean_problem.h b/src/sat/boolean_problem.h index 96f20f0c79..49e9a7f1a8 100644 --- a/src/sat/boolean_problem.h +++ b/src/sat/boolean_problem.h @@ -39,8 +39,8 @@ bool IsAssignmentValid(const LinearBooleanProblem& problem, // Converts a LinearBooleanProblem to the cnf file format. // Note that this only works for pure SAT problems (only clauses), max-sat or -// weighted max-sat problems. Returns an empty string on error. -string LinearBooleanProblemToCnfString(const LinearBooleanProblem& problem); +// weighted max-sat problems. Returns an empty std::string on error. +std::string LinearBooleanProblemToCnfString(const LinearBooleanProblem& problem); // Store a variable assignment into the given BooleanAssignement proto. // Note that only the assigned variables are stored, so the assignment may be diff --git a/src/sat/sat_base.h b/src/sat/sat_base.h index c49ea91c9a..34fd086e9c 100644 --- a/src/sat/sat_base.h +++ b/src/sat/sat_base.h @@ -24,7 +24,6 @@ #include "base/int_type.h" #include "util/bitset.h" -using std::string; namespace operations_research { namespace sat { @@ -77,7 +76,7 @@ class Literal { Literal Negated() const { return Literal(NegatedIndex()); } - string DebugString() const { return StringPrintf("%+d", SignedValue()); } + std::string DebugString() const { return StringPrintf("%+d", SignedValue()); } bool operator==(Literal other) const { return index_ == other.index_; } bool operator!=(Literal other) const { return index_ != other.index_; } @@ -231,11 +230,11 @@ struct AssignmentInfo { // Some data about this assignment used to compute the reason clause when it // becomes needed. Note that depending on the type, these fields will not be // used and be left uninitialized. - #if defined(_MSC_VER) +#if defined(_MSC_VER) struct { - #else +#else union { - #endif +#endif Literal literal; int source_trail_index; }; diff --git a/src/sat/sat_conflict.cc b/src/sat/sat_conflict.cc index 05650c0368..cac1c34679 100644 --- a/src/sat/sat_conflict.cc +++ b/src/sat/sat_conflict.cc @@ -381,8 +381,8 @@ void SatSolver::MinimizeConflictExperimental(std::vector* conflict) { } } std::sort(variables_sorted_by_level.begin(), - variables_sorted_by_level.end(), - VariableWithLargerWeightFirst()); + variables_sorted_by_level.end(), + VariableWithLargerWeightFirst()); // Then process the reason of the variable with highest level first. std::vector to_remove; diff --git a/src/sat/sat_solver.cc b/src/sat/sat_solver.cc index 0d26ca39eb..d22b260d76 100644 --- a/src/sat/sat_solver.cc +++ b/src/sat/sat_solver.cc @@ -453,8 +453,8 @@ bool SatClause::IsSatisfied(const VariablesAssignment& assignment) const { return false; } -string SatClause::DebugString() const { - string result; +std::string SatClause::DebugString() const { + std::string result; for (const Literal literal : *this) { if (!result.empty()) result.append(" "); result.append(literal.DebugString()); @@ -521,10 +521,10 @@ void SatSolver::SetParameters(const SatParameters& parameters) { parameters_ = parameters; } -string SatSolver::Indent() const { +std::string SatSolver::Indent() const { SCOPED_TIME_STAT(&stats_); const int level = choice_points_.size(); - string result; + std::string result; for (int i = 0; i < level; ++i) { result.append("| "); } @@ -986,7 +986,7 @@ int SatSolver::ComputeLbd(const LiteralList& literals) { return is_level_marked_.NumberOfSetCallsWithDifferentArguments(); } -string SatSolver::StatusString() const { +std::string SatSolver::StatusString() const { const double time_in_s = timer_.Get(); return StringPrintf(" time: %fs\n", time_in_s) @@ -1025,7 +1025,7 @@ string SatSolver::StatusString() const { + StringPrintf(" num restarts: %d\n", restart_count_); } -string SatSolver::RunningStatisticsString() const { +std::string SatSolver::RunningStatisticsString() const { const double time_in_s = timer_.Get(); const int learned = learned_clauses_.size(); return StringPrintf("%6.2lfs, mem:%s, fails:%" GG_LL_FORMAT "d, " @@ -1321,7 +1321,7 @@ bool SatSolver::IsAssignmentValid(const VariablesAssignment& assignment) const { return false; } } - string result; + std::string result; for (VariableIndex var(0); var < num_variables_; ++var) { result.append(trail_.Assignment() .GetTrueLiteralForAssignedVariable(var).DebugString()); @@ -1330,13 +1330,13 @@ bool SatSolver::IsAssignmentValid(const VariablesAssignment& assignment) const { return true; } -string SatSolver::DebugString(const SatClause& clause) const { - string result; +std::string SatSolver::DebugString(const SatClause& clause) const { + std::string result; for (const Literal literal : clause) { if (!result.empty()) { result.append(" || "); } - const string value = trail_.Assignment().IsLiteralTrue(literal) + const std::string value = trail_.Assignment().IsLiteralTrue(literal) ? "true" : (trail_.Assignment().IsLiteralFalse(literal) ? "false" : "undef"); result.append( diff --git a/src/sat/sat_solver.h b/src/sat/sat_solver.h index e788f1883b..cf0c8c615b 100644 --- a/src/sat/sat_solver.h +++ b/src/sat/sat_solver.h @@ -38,7 +38,6 @@ #include "util/stats.h" #include "base/adjustable_priority_queue.h" -using std::string; namespace operations_research { namespace sat { @@ -186,7 +185,7 @@ class SatClause { // and actually detach it. void LazyDetach() { is_attached_ = false; } - string DebugString() const; + std::string DebugString() const; private: // The data is packed so that only 16 bytes are used for these fields. @@ -461,7 +460,7 @@ class SatSolver { int literal_trail_index; Literal decision; }; - const std::vector& ChoicePoints() { return choice_points_; } + const std::vector& ChoicePoints() const { return choice_points_; } const Trail& LiteralTrail() const { return trail_; } const VariablesAssignment& Assignment() const { return trail_.Assignment(); } @@ -477,7 +476,7 @@ class SatSolver { // Utility function to insert spaces proportional to the search depth. // It is used in the pretty print of the search. - string Indent() const; + std::string Indent() const; // Returns the decision level of a given variable. int DecisionLevel(VariableIndex var) const { @@ -566,9 +565,9 @@ class SatSolver { // Statistics on one clause, added indicates if we are adding the // clause, or deleting it. - template - void UpdateStatisticsOnOneClause( - const Literals& literals, int size, bool added) { + template + void UpdateStatisticsOnOneClause(const Literals& literals, int size, + bool added) { SCOPED_TIME_STAT(&stats_); for (const Literal literal : literals) { const VariableIndex var = literal.Variable(); @@ -682,9 +681,9 @@ class SatSolver { void SetNumVariables(int num_variables); - string DebugString(const SatClause& clause) const; - string StatusString() const; - string RunningStatisticsString() const; + std::string DebugString(const SatClause& clause) const; + std::string StatusString() const; + std::string RunningStatisticsString() const; VariableIndex num_variables_; diff --git a/src/util/bitset.h b/src/util/bitset.h index 9eec3cfd02..7c859e2e20 100644 --- a/src/util/bitset.h +++ b/src/util/bitset.h @@ -16,7 +16,8 @@ #ifndef OR_TOOLS_UTIL_BITSET_H_ #define OR_TOOLS_UTIL_BITSET_H_ -#include +#include +#include #include #include "base/basictypes.h" diff --git a/src/util/filelineiter.h b/src/util/filelineiter.h index 6e99d64816..9eb6b0fb57 100644 --- a/src/util/filelineiter.h +++ b/src/util/filelineiter.h @@ -11,12 +11,12 @@ // See the License for the specific language governing permissions and // limitations under the License. // Allows to read a text file line by line with: -// for (const string& line : FileLines("myfile.txt")) { ... } +// for (const std::string& line : FileLines("myfile.txt")) { ... } // // More details: // * The lines are separated by '\n' (which is removed) and have no size limits. // * Consecutive '\n' result in empty lines being produced. -// * If not empty, the string after the last '\n' is produced as the last line. +// * If not empty, the std::string after the last '\n' is produced as the last line. // #ifndef OR_TOOLS_UTIL_FILELINEITER_H_ #define OR_TOOLS_UTIL_FILELINEITER_H_ @@ -34,7 +34,7 @@ class FileLineIterator { : next_position_after_eol_(0), buffer_size_(0), file_(file) { ReadNextLine(); } - const string& operator*() const { return line_; } + const std::string& operator*() const { return line_; } bool operator!=(const FileLineIterator& other) const { return file_ != other.file_; } @@ -77,12 +77,12 @@ class FileLineIterator { int next_position_after_eol_; int buffer_size_; File* file_; - string line_; + std::string line_; }; class FileLines { public: - explicit FileLines(const string& filename) { + explicit FileLines(const std::string& filename) { file_ = File::Open(filename, "r"); } ~FileLines() { diff --git a/src/util/fp_utils.h b/src/util/fp_utils.h index 9ff9eace98..943b1521b5 100644 --- a/src/util/fp_utils.h +++ b/src/util/fp_utils.h @@ -32,6 +32,7 @@ #include #endif +#include #include #include @@ -87,7 +88,7 @@ inline bool IsPositiveOrNegativeInfinity(FloatType x) { // tolerances. // Returns true if |x - y| <= a (with a being the absolute_tolerance). // The above case is useful for values that are close to zero. -// Returns true if |x - y| <= max(|x|, |y|) * r. (with r being the relative +// Returns true if |x - y| <= std::max(|x|, |y|) * r. (with r being the relative // tolerance.) // The cases for infinities are treated separately to avoid generating NaNs. template bool AreWithinAbsoluteOrRelativeTolerances( diff --git a/src/util/graph_export.cc b/src/util/graph_export.cc index 802b492ff8..8a3d7ba300 100644 --- a/src/util/graph_export.cc +++ b/src/util/graph_export.cc @@ -30,29 +30,29 @@ class GraphSyntax { virtual ~GraphSyntax() {} // Node in the right syntax. - virtual string Node(const string& name, - const string& label, - const string& shape, - const string& color) = 0; + virtual std::string Node(const std::string& name, + const std::string& label, + const std::string& shape, + const std::string& color) = 0; // Adds one link in the generated graph. - virtual string Link(const string& source, - const string& destination, - const string& label) = 0; + virtual std::string Link(const std::string& source, + const std::string& destination, + const std::string& label) = 0; // File header. - virtual string Header(const string& name) = 0; + virtual std::string Header(const std::string& name) = 0; // File footer. - virtual string Footer() = 0; + virtual std::string Footer() = 0; }; class DotSyntax : public GraphSyntax { public: virtual ~DotSyntax() {} - virtual string Node(const string& name, - const string& label, - const string& shape, - const string& color) { + virtual std::string Node(const std::string& name, + const std::string& label, + const std::string& shape, + const std::string& color) { return StringPrintf("%s [shape=%s label=\"%s\" color=%s]\n", name.c_str(), shape.c_str(), @@ -61,9 +61,9 @@ class DotSyntax : public GraphSyntax { } // Adds one link in the generated graph. - virtual string Link(const string& source, - const string& destination, - const string& label) { + virtual std::string Link(const std::string& source, + const std::string& destination, + const std::string& label) { return StringPrintf("%s -> %s [label=%s]\n", source.c_str(), destination.c_str(), @@ -71,12 +71,12 @@ class DotSyntax : public GraphSyntax { } // File header. - virtual string Header(const string& name) { + virtual std::string Header(const std::string& name) { return StringPrintf("graph %s {\n", name.c_str()); } // File footer. - virtual string Footer() { + virtual std::string Footer() { return "}\n"; } }; @@ -85,10 +85,10 @@ class GmlSyntax : public GraphSyntax { public: virtual ~GmlSyntax() {} - virtual string Node(const string& name, - const string& label, - const string& shape, - const string& color) { + virtual std::string Node(const std::string& name, + const std::string& label, + const std::string& shape, + const std::string& color) { return StringPrintf(" node [\n" " name \"%s\"\n" " label \"%s\"\n" @@ -104,9 +104,9 @@ class GmlSyntax : public GraphSyntax { } // Adds one link in the generated graph. - virtual string Link(const string& source, - const string& destination, - const string& label) { + virtual std::string Link(const std::string& source, + const std::string& destination, + const std::string& label) { return StringPrintf(" edge [\n" " label \"%s\"\n" " source \"%s\"\n" @@ -118,14 +118,14 @@ class GmlSyntax : public GraphSyntax { } // File header. - virtual string Header(const string& name) { + virtual std::string Header(const std::string& name) { return StringPrintf("graph [\n" " name \"%s\"\n" , name.c_str()); } // File footer. - virtual string Footer() { + virtual std::string Footer() { return "]\n"; } }; @@ -140,21 +140,21 @@ class FileGraphExporter : public GraphExporter { virtual ~FileGraphExporter() {} // Write node in GML or DOT format. - virtual void WriteNode(const string& name, - const string& label, - const string& shape, - const string& color) { + virtual void WriteNode(const std::string& name, + const std::string& label, + const std::string& shape, + const std::string& color) { Append(syntax_->Node(name, label, shape, color)); } // Adds one link in the generated graph. - virtual void WriteLink(const string& source, - const string& destination, - const string& label) { + virtual void WriteLink(const std::string& source, + const std::string& destination, + const std::string& label) { Append(syntax_->Link(source, destination, label)); } - virtual void WriteHeader(const string& name) { + virtual void WriteHeader(const std::string& name) { Append(syntax_->Header(name)); } @@ -163,8 +163,8 @@ class FileGraphExporter : public GraphExporter { } private: - void Append(const string& string) { - file_->Write(string.c_str(), string.size()); + void Append(const std::string& str) { + file_->Write(str.c_str(), str.size()); } File* const file_; diff --git a/src/util/graph_export.h b/src/util/graph_export.h index 63b93713d2..0017b21376 100644 --- a/src/util/graph_export.h +++ b/src/util/graph_export.h @@ -20,7 +20,6 @@ #include "base/macros.h" #include "base/file.h" -using std::string; namespace operations_research { // ----- Export to graph file ----- @@ -38,21 +37,21 @@ class GraphExporter { virtual ~GraphExporter(); // Write the header of the graph file. - virtual void WriteHeader(const string& name) = 0; + virtual void WriteHeader(const std::string& name) = 0; // Write the footer of the graph file. virtual void WriteFooter() = 0; // Write node in GML or DOT format. - virtual void WriteNode(const string& name, - const string& label, - const string& shape, - const string& color) = 0; + virtual void WriteNode(const std::string& name, + const std::string& label, + const std::string& shape, + const std::string& color) = 0; // Adds one link in the generated graph. - virtual void WriteLink(const string& source, - const string& destination, - const string& label) = 0; + virtual void WriteLink(const std::string& source, + const std::string& destination, + const std::string& label) = 0; // Creates a graph exporter that will write to file with a given format. static GraphExporter* MakeFileExporter(File* const file, diff --git a/src/util/monoid_operation_tree.h b/src/util/monoid_operation_tree.h index d02d24f1a1..a955bb9ac3 100644 --- a/src/util/monoid_operation_tree.h +++ b/src/util/monoid_operation_tree.h @@ -46,7 +46,7 @@ namespace operations_research { // * Have a = operator method that sets its value to the given one. // * Have a Compute(const T& left, const T& right) method that sets its value // to the result of the binary operation for the two given operands. -// * Have a string DebugString() const method. +// * Have a std::string DebugString() const method. // // Possible use cases are: // * Maintain a sum or a product of doubles, with a guarantee that the queried @@ -82,7 +82,7 @@ class MonoidOperationTree { DiveInTree(0, diver); } - string DebugString() const; + std::string DebugString() const; private: // Computes the index of the first leaf for the given size. @@ -206,8 +206,8 @@ void MonoidOperationTree::Compute(int position) { } template -string MonoidOperationTree::DebugString() const { - string out; +std::string MonoidOperationTree::DebugString() const { + std::string out; int layer = 0; for (int i = 0; i < num_nodes_; ++i) { if (((i+1) & i) == 0) { diff --git a/src/util/piecewise_linear_function.cc b/src/util/piecewise_linear_function.cc index 1f9425d250..9fb14e018c 100644 --- a/src/util/piecewise_linear_function.cc +++ b/src/util/piecewise_linear_function.cc @@ -251,8 +251,8 @@ void PiecewiseSegment::AddConstantToY(int64 constant) { reference_y_ = CapAdd(reference_y_, constant); } -string PiecewiseSegment::DebugString() const { - string result = StringPrintf( +std::string PiecewiseSegment::DebugString() const { + std::string result = StringPrintf( "PiecewiseSegment(& segments() const { return segments_; } - string DebugString() const; + std::string DebugString() const; private: // Takes the sequence of segments, sorts them on increasing start and inserts diff --git a/src/util/stats.cc b/src/util/stats.cc index b8e4c8a87d..ead62b46c6 100644 --- a/src/util/stats.cc +++ b/src/util/stats.cc @@ -20,7 +20,7 @@ namespace operations_research { -string MemoryUsage() { +std::string MemoryUsage() { static const int64 kDisplayThreshold = 2; static const int64 kKiloByte = 1024; static const int64 kMegaByte = kKiloByte * kKiloByte; @@ -40,12 +40,12 @@ static const int64 kDisplayThreshold = 2; } } -Stat::Stat(const string& name, StatsGroup *group) : name_(name) { +Stat::Stat(const std::string& name, StatsGroup *group) : name_(name) { group->Register(this); } -string Stat::StatString() const { - return string(name_ + ": " + ValueAsString()); +std::string Stat::StatString() const { + return std::string(name_ + ": " + ValueAsString()); } StatsGroup::~StatsGroup() { @@ -68,7 +68,7 @@ bool CompareStatPointerByName(Stat* s1, Stat *s2) { } } // namespace -string StatsGroup::StatString() const { +std::string StatsGroup::StatString() const { // Computes the longest name of all the stats we want to display. // Also create a temporary vector so we can sort the stats by names. int longest_name_size = 0; @@ -85,7 +85,7 @@ string StatsGroup::StatString() const { if (sorted_stats.empty()) return ""; // Pretty-print all the stats. - string result(name_ + " {\n"); + std::string result(name_ + " {\n"); for (int i = 0; i < sorted_stats.size(); ++i) { result += " "; result += sorted_stats[i]->Name(); @@ -96,7 +96,7 @@ string StatsGroup::StatString() const { return result; } -TimeDistribution *StatsGroup::LookupOrCreateTimeDistribution(string name) { +TimeDistribution *StatsGroup::LookupOrCreateTimeDistribution(std::string name) { TimeDistribution* &ref = time_distributions_[name]; if (ref == NULL) { ref = new TimeDistribution(name); @@ -105,12 +105,12 @@ TimeDistribution *StatsGroup::LookupOrCreateTimeDistribution(string name) { return ref; } -DistributionStat::DistributionStat(const string& name) +DistributionStat::DistributionStat(const std::string& name) : Stat(name), sum_(0.0), average_(0.0), sum_squares_from_average_(0.0), min_(0.0), max_(0.0), num_(0) {} -DistributionStat::DistributionStat(const string& name, StatsGroup* group) +DistributionStat::DistributionStat(const std::string& name, StatsGroup* group) : Stat(name, group), sum_(0.0), average_(0.0), sum_squares_from_average_(0.0), min_(0.0), max_(0.0), num_(0) {} @@ -156,7 +156,7 @@ double TimeDistribution::CyclesToSeconds(double cycles) { return cycles * seconds_per_cycles; } -string TimeDistribution::PrintCyclesAsTime(double cycles) { +std::string TimeDistribution::PrintCyclesAsTime(double cycles) { DCHECK_GE(cycles, 0.0); // This epsilon is just to avoid displaying 1000.00ms instead of 1.00s. double eps1 = 1 + 1e-3; @@ -180,7 +180,7 @@ void TimeDistribution::AddTimeInCycles(double cycles) { AddToDistribution(cycles); } -string TimeDistribution::ValueAsString() const { +std::string TimeDistribution::ValueAsString() const { return StringPrintf("%8llu [%8s, %8s] %8s %8s %8s\n", num_, PrintCyclesAsTime(min_).c_str(), @@ -195,7 +195,7 @@ void RatioDistribution::Add(double value) { AddToDistribution(value); } -string RatioDistribution::ValueAsString() const { +std::string RatioDistribution::ValueAsString() const { return StringPrintf("%8llu [%7.2lf%%, %7.2lf%%] %7.2lf%% %7.2lf%%\n", num_, 100.0 * min_, @@ -208,7 +208,7 @@ void DoubleDistribution::Add(double value) { AddToDistribution(value); } -string DoubleDistribution::ValueAsString() const { +std::string DoubleDistribution::ValueAsString() const { return StringPrintf("%8llu [%8.1e, %8.1e] %8.1e %8.1e\n", num_, min_, @@ -221,7 +221,7 @@ void IntegerDistribution::Add(int64 value) { AddToDistribution(static_cast(value)); } -string IntegerDistribution::ValueAsString() const { +std::string IntegerDistribution::ValueAsString() const { return StringPrintf("%8llu [%8.lf, %8.lf] %8.2lf %8.2lf %8.lf\n", num_, min_, diff --git a/src/util/stats.h b/src/util/stats.h index fe3955e441..46353b2b0e 100644 --- a/src/util/stats.h +++ b/src/util/stats.h @@ -73,12 +73,11 @@ #include "base/scoped_ptr.h" #include "base/timer.h" -using std::string; namespace operations_research { -// Returns the current thread's total memory usage in an human-readable string. -string MemoryUsage(); +// Returns the current thread's total memory usage in an human-readable std::string. +std::string MemoryUsage(); // Forward declaration. class StatsGroup; @@ -87,20 +86,20 @@ class TimeDistribution; // Base class for a statistic that can be pretty-printed. class Stat { public: - explicit Stat(const string& name) : name_(name) {} + explicit Stat(const std::string& name) : name_(name) {} // Also add this stat to the given group. - Stat(const string& name, StatsGroup * group); + Stat(const std::string& name, StatsGroup * group); virtual ~Stat() {} // Only used for display purpose. - string Name() const { return name_; } + std::string Name() const { return name_; } // Returns a human-readable formated line of the form "name: ValueAsString()". - string StatString() const; + std::string StatString() const; // Prints information about this statistic. - virtual string ValueAsString() const = 0; + virtual std::string ValueAsString() const = 0; // Is this stat worth printing? usually false if nothing was measured. virtual bool WorthPrinting() const = 0; @@ -109,37 +108,37 @@ class Stat { virtual void Reset() = 0; private: - const string name_; + const std::string name_; }; // Base class to print a nice summary of a group of statistics. class StatsGroup { public: - explicit StatsGroup(const string& name) + explicit StatsGroup(const std::string& name) : name_(name), stats_(), time_distributions_() {} ~StatsGroup(); - // Registers a Stat, which will appear in the string returned by StatString(). + // Registers a Stat, which will appear in the std::string returned by StatString(). // The Stat object must live as long as this StatsGroup. void Register(Stat* stat); // Returns this group name, followed by one line per Stat registered with this // group (this includes the ones created by LookupOrCreateTimeDistribution()). // Note that only the stats WorthPrinting() are printed. - string StatString() const; + std::string StatString() const; // Returns and if needed creates and registers a TimeDistribution with the // given name. Note that this involve a map lookup and his thus slower than // directly accessing a TimeDistribution variable. - TimeDistribution *LookupOrCreateTimeDistribution(string name); + TimeDistribution *LookupOrCreateTimeDistribution(std::string name); // Calls Reset() on all the statistics registered with this group. void Reset(); private: - string name_; + std::string name_; std::vector stats_; - std::map time_distributions_; + std::map time_distributions_; DISALLOW_COPY_AND_ASSIGN(StatsGroup); }; @@ -149,14 +148,14 @@ class StatsGroup { // the values are added to the sequence and in the way the stats are printed. class DistributionStat : public Stat { public: - explicit DistributionStat(const string& name); - DistributionStat(const string& name, StatsGroup* group); + explicit DistributionStat(const std::string& name); + DistributionStat(const std::string& name, StatsGroup* group); virtual ~DistributionStat() {} virtual void Reset(); virtual bool WorthPrinting() const { return num_ != 0; } // Implemented by the subclasses. - virtual string ValueAsString() const = 0; + virtual std::string ValueAsString() const = 0; // Trivial statistics on all the values added so far. double Sum() const { return sum_; } @@ -194,11 +193,11 @@ class DistributionStat : public Stat { // if the sum of times reaches 52 days for a 2GHz processor. class TimeDistribution : public DistributionStat { public: - explicit TimeDistribution(const string& name) + explicit TimeDistribution(const std::string& name) : DistributionStat(name), timer_() {} - TimeDistribution(const string& name, StatsGroup* group) + TimeDistribution(const std::string& name, StatsGroup* group) : DistributionStat(name, group), timer_() {} - virtual string ValueAsString() const; + virtual std::string ValueAsString() const; // Internaly the TimeDistribution stores cpu cycles (to do a bit less work // on each StopTimerAndAddElapsedTime()). Use this function to convert @@ -227,37 +226,37 @@ class TimeDistribution : public DistributionStat { private: // Converts and prints a number of cycles in an human readable way using the // proper time unit depending on the value (ns, us, ms, s, m or h). - static string PrintCyclesAsTime(double cycles); + static std::string PrintCyclesAsTime(double cycles); CycleTimer timer_; }; // Statistic on the distribution of a sequence of ratios, displayed as %. class RatioDistribution : public DistributionStat { public: - explicit RatioDistribution(const string& name) : DistributionStat(name) {} - RatioDistribution(const string& name, StatsGroup* group) + explicit RatioDistribution(const std::string& name) : DistributionStat(name) {} + RatioDistribution(const std::string& name, StatsGroup* group) : DistributionStat(name, group) {} - virtual string ValueAsString() const; + virtual std::string ValueAsString() const; void Add(double value); }; // Statistic on the distribution of a sequence of doubles. class DoubleDistribution : public DistributionStat { public: - explicit DoubleDistribution(const string& name) : DistributionStat(name) {} - DoubleDistribution(const string& name, StatsGroup* group) + explicit DoubleDistribution(const std::string& name) : DistributionStat(name) {} + DoubleDistribution(const std::string& name, StatsGroup* group) : DistributionStat(name, group) {} - virtual string ValueAsString() const; + virtual std::string ValueAsString() const; void Add(double value); }; // Statistic on the distribution of a sequence of integers. class IntegerDistribution : public DistributionStat { public: - explicit IntegerDistribution(const string& name) : DistributionStat(name) {} - IntegerDistribution(const string& name, StatsGroup* group) + explicit IntegerDistribution(const std::string& name) : DistributionStat(name) {} + IntegerDistribution(const std::string& name, StatsGroup* group) : DistributionStat(name, group) {} - virtual string ValueAsString() const; + virtual std::string ValueAsString() const; void Add(int64 value); }; diff --git a/src/util/string_array.h b/src/util/string_array.h index b4eea7bbac..60c5c1335e 100644 --- a/src/util/string_array.h +++ b/src/util/string_array.h @@ -19,45 +19,44 @@ #include "base/integral_types.h" #include "base/stringprintf.h" -using std::string; namespace operations_research { // ---------- Pretty Print Helpers ---------- // See the straightforward (and unique) usage of this macro below. #define RETURN_STRINGIFIED_VECTOR(vector, separator, method)\ - string out;\ + std::string out;\ for (int i = 0; i < vector.size(); ++i) {\ if (i > 0) out += separator;\ out += vector[i] method;\ }\ return out -// Converts a vector into a string by calling the given method (or simply -// getting the given string member), on all elements, and concatenating +// Converts a vector into a std::string by calling the given method (or simply +// getting the given std::string member), on all elements, and concatenating // the obtained strings with the given separator. // Join v[i].DebugString(). template -string JoinDebugString(const std::vector& v, const string& separator) { +std::string JoinDebugString(const std::vector& v, const std::string& separator) { RETURN_STRINGIFIED_VECTOR(v, separator, .DebugString()); } // Join v[i]->DebugString(). template -string JoinDebugStringPtr(const std::vector& v, const string& separator) { +std::string JoinDebugStringPtr(const std::vector& v, const std::string& separator) { RETURN_STRINGIFIED_VECTOR(v, separator, ->DebugString()); } // Join v[i]->name(). template -string JoinNamePtr(const std::vector& v, const string& separator) { +std::string JoinNamePtr(const std::vector& v, const std::string& separator) { RETURN_STRINGIFIED_VECTOR(v, separator, ->name()); } // Join v[i]->name. template -string JoinNameFieldPtr(const std::vector& v, const string& separator) { +std::string JoinNameFieldPtr(const std::vector& v, const std::string& separator) { RETURN_STRINGIFIED_VECTOR(v, separator, ->name); } @@ -65,10 +64,10 @@ string JoinNameFieldPtr(const std::vector& v, const string& separator) { // TODO(user): use strings::Join instead of the methods below. -// Creates a string from an array of int64, and a separator. -inline string Int64ArrayToString(const int64* const array, int size, - const string& separator) { - string out; +// Creates a std::string from an array of int64, and a separator. +inline std::string Int64ArrayToString(const int64* const array, int size, + const std::string& separator) { + std::string out; for (int i = 0; i < size; ++i) { if (i > 0) { out.append(separator); @@ -78,10 +77,10 @@ inline string Int64ArrayToString(const int64* const array, int size, return out; } -// Creates a string from an array of int, and a separator. -inline string IntArrayToString(const int* const array, int size, - const string& separator) { - string out; +// Creates a std::string from an array of int, and a separator. +inline std::string IntArrayToString(const int* const array, int size, + const std::string& separator) { + std::string out; for (int i = 0; i < size; ++i) { if (i > 0) { out.append(separator); @@ -91,15 +90,15 @@ inline string IntArrayToString(const int* const array, int size, return out; } -// Creates a string from an vector of int64, and a separator. -inline string IntVectorToString(const std::vector& array, - const string& separator) { +// Creates a std::string from an vector of int64, and a separator. +inline std::string IntVectorToString(const std::vector& array, + const std::string& separator) { return Int64ArrayToString(array.data(), array.size(), separator); } -// Creates a string from an vector of int, and a separator. -inline string IntVectorToString(const std::vector& array, - const string& separator) { +// Creates a std::string from an vector of int, and a separator. +inline std::string IntVectorToString(const std::vector& array, + const std::string& separator) { return IntArrayToString(array.data(), array.size(), separator); } diff --git a/src/util/time_limit.cc b/src/util/time_limit.cc index e65a0ee22d..51f055e464 100644 --- a/src/util/time_limit.cc +++ b/src/util/time_limit.cc @@ -12,6 +12,7 @@ // limitations under the License. #include "util/time_limit.h" +#include #include namespace operations_research { diff --git a/src/util/xml_helper.cc b/src/util/xml_helper.cc index 5fa53f0ae1..327bfeebad 100644 --- a/src/util/xml_helper.cc +++ b/src/util/xml_helper.cc @@ -28,7 +28,7 @@ void XmlHelper::StartDocument() { direction_down_ = false; } -void XmlHelper::StartElement(const string& name) { +void XmlHelper::StartElement(const std::string& name) { if (direction_down_) { content_.append(">\n"); } @@ -37,14 +37,14 @@ void XmlHelper::StartElement(const string& name) { direction_down_ = true; } -void XmlHelper::AddAttribute(const string& key, int value) { +void XmlHelper::AddAttribute(const std::string& key, int value) { AddAttribute(key, StringPrintf("%d", value)); } -void XmlHelper::AddAttribute(const string& key, const string& value) { +void XmlHelper::AddAttribute(const std::string& key, const std::string& value) { std::ostringstream escaped_value; - for (string::const_iterator it = value.begin(); it != value.end(); ++it) { + for (std::string::const_iterator it = value.begin(); it != value.end(); ++it) { unsigned char c = (unsigned char)*it; switch (c) { @@ -73,7 +73,7 @@ void XmlHelper::AddAttribute(const string& key, const string& value) { } void XmlHelper::EndElement() { - string tag = tags_.top(); + std::string tag = tags_.top(); if (direction_down_) { content_.append(" />\n"); @@ -87,5 +87,5 @@ void XmlHelper::EndElement() { void XmlHelper::EndDocument() {} -const string& XmlHelper::GetContent() const { return content_; } +const std::string& XmlHelper::GetContent() const { return content_; } } // namespace operations_research diff --git a/src/util/xml_helper.h b/src/util/xml_helper.h index cb2cc75f65..b0f146f528 100644 --- a/src/util/xml_helper.h +++ b/src/util/xml_helper.h @@ -19,7 +19,6 @@ #include #include "base/macros.h" -using std::string; namespace operations_research { @@ -34,13 +33,13 @@ class XmlHelper { void StartDocument(); // Starts a new element - void StartElement(const string& name); + void StartElement(const std::string& name); // Adds a key-value pair to the current element. - void AddAttribute(const string& key, int value); + void AddAttribute(const std::string& key, int value); // Adds a key-value pair to the current element. - void AddAttribute(const string& key, const string& value); + void AddAttribute(const std::string& key, const std::string& value); // Ends the current element and goes back to the previous element. void EndElement(); @@ -49,12 +48,12 @@ class XmlHelper { void EndDocument(); // Returns the XML content written so far. - const string& GetContent() const; + const std::string& GetContent() const; private: - typedef std::pair EscapePair; - string content_; - std::stack tags_; + typedef std::pair EscapePair; + std::string content_; + std::stack tags_; bool direction_down_; DISALLOW_COPY_AND_ASSIGN(XmlHelper); diff --git a/src/util/zvector.h b/src/util/zvector.h index e8aeea4bf5..424dc6a7a5 100644 --- a/src/util/zvector.h +++ b/src/util/zvector.h @@ -19,7 +19,7 @@ #elif !defined(_MSC_VER) #include #endif -#include +#include #include #include #include