Exemplo n.º 1
0
 static void CodeSample()
 {
     // Creates the model.
     CpModel model = new CpModel();
     // Creates the Boolean variable.
     IntVar x = model.NewBoolVar("x");
 }
Exemplo n.º 2
0
    static void Main()
    {
        CpModel model   = new CpModel();
        int     horizon = 100;

        // C# code supports constant of affine expressions.
        IntVar      start_var    = model.NewIntVar(0, horizon, "start");
        IntVar      end_var      = model.NewIntVar(0, horizon, "end");
        IntVar      presence_var = model.NewBoolVar("presence");
        IntervalVar interval     = model.NewOptionalIntervalVar(start_var, 10, end_var + 2, presence_var, "interval");

        Console.WriteLine(interval);

        // If the size is fixed, a simpler version uses the start expression, the size and the
        // literal.
        IntervalVar fixedSizeIntervalVar =
            model.NewOptionalFixedSizeIntervalVar(start_var, 10, presence_var, "fixed_size_interval_var");

        Console.WriteLine(fixedSizeIntervalVar);

        // A fixed interval can be created using the same API.
        IntervalVar fixedInterval = model.NewOptionalFixedSizeIntervalVar(5, 10, presence_var, "fixed_interval");

        Console.WriteLine(fixedInterval);
    }
Exemplo n.º 3
0
    static void MinimalCpSatWithTimeLimit()
    {
        // Creates the model.
        CpModel model = new CpModel();
        // Creates the variables.
        int num_vals = 3;

        IntVar x = model.NewIntVar(0, num_vals - 1, "x");
        IntVar y = model.NewIntVar(0, num_vals - 1, "y");
        IntVar z = model.NewIntVar(0, num_vals - 1, "z");

        // Creates the constraints.
        model.Add(x != y);

        // Creates a solver and solves the model.
        CpSolver solver = new CpSolver();

        // Adds a time limit. Parameters are stored as strings in the solver.
        solver.StringParameters = "max_time_in_seconds:10.0";

        CpSolverStatus status = solver.Solve(model);

        if (status == CpSolverStatus.Feasible)
        {
            Console.WriteLine("x = " + solver.Value(x));
            Console.WriteLine("y = " + solver.Value(y));
            Console.WriteLine("z = " + solver.Value(z));
        }
    }
Exemplo n.º 4
0
    static void Main()
    {
        // Creates the model.
        // [START model]
        CpModel model = new CpModel();
        // [END model]

        // Creates the variables.
        // [START variables]
        int num_vals = 3;

        IntVar x = model.NewIntVar(0, num_vals - 1, "x");
        IntVar y = model.NewIntVar(0, num_vals - 1, "y");
        IntVar z = model.NewIntVar(0, num_vals - 1, "z");

        // [END variables]

        // Adds a different constraint.
        // [START constraints]
        model.Add(x != y);
        // [END constraints]

        // Creates a solver and solves the model.
        // [START solve]
        CpSolver solver            = new CpSolver();
        VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] { x, y, z });

        // Search for all solutions.
        solver.StringParameters = "enumerate_all_solutions:true";
        // And solve.
        solver.Solve(model, cb);
        // [END solve]

        Console.WriteLine($"Number of solutions found: {cb.SolutionCount()}");
    }
Exemplo n.º 5
0
    static void MinimalCpSatPrintIntermediateSolutions()
    {
        // Creates the model.
        CpModel model = new CpModel();
        // Creates the variables.
        int num_vals = 3;

        IntVar x = model.NewIntVar(0, num_vals - 1, "x");
        IntVar y = model.NewIntVar(0, num_vals - 1, "y");
        IntVar z = model.NewIntVar(0, num_vals - 1, "z");

        // Creates the constraints.
        model.Add(x != y);
        // Create the objective.
        model.Maximize(x + 2 * y + 3 * z);

        // Creates a solver and solves the model.
        CpSolver solver = new CpSolver();
        VarArraySolutionPrinterWithObjective cb =
            new VarArraySolutionPrinterWithObjective(new IntVar[] { x, y, z });

        solver.SearchAllSolutions(model, cb);
        Console.WriteLine(String.Format("Number of solutions found: {0}",
                                        cb.SolutionCount()));
    }
Exemplo n.º 6
0
        public void NegativeIntVar()
        {
            CpModel model        = new CpModel();
            IntVar  boolvar      = model.NewBoolVar("boolvar");
            IntVar  x            = model.NewIntVar(0, 10, "x");
            IntVar  delta        = model.NewIntVar(-5, 5, "delta");
            IntVar  squaredDelta = model.NewIntVar(0, 25, "squaredDelta");

            model.Add(x == boolvar * 4);
            model.Add(delta == x - 5);
            model.AddProdEquality(squaredDelta, new IntVar[] { delta, delta });
            model.Minimize(squaredDelta);
            //Console.WriteLine("model = " + model.Model.ToString());

            CpSolver       solver = new CpSolver();
            CpSolverStatus status = solver.Solve(model);

            Assert.Equal(CpSolverStatus.Optimal, status);

            CpSolverResponse response = solver.Response;

            Assert.Equal(1, solver.Value(boolvar));
            Assert.Equal(4, solver.Value(x));
            Assert.Equal(-1, solver.Value(delta));
            Assert.Equal(1, solver.Value(squaredDelta));
            Assert.Equal(new long[] { 1, 4, -1, 1 }, response.Solution);
            Assert.Equal(1, response.ObjectiveValue);
            //Console.WriteLine("response = " + reponse.ToString());
        }
Exemplo n.º 7
0
    static void MinimalCpSat()
    {
        // Creates the model.
        CpModel model = new CpModel();
        // Creates the variables.
        int num_vals = 3;

        IntVar x = model.NewIntVar(0, num_vals - 1, "x");
        IntVar y = model.NewIntVar(0, num_vals - 1, "y");
        IntVar z = model.NewIntVar(0, num_vals - 1, "z");

        // Creates the constraints.
        model.Add(x != y);

        // Creates a solver and solves the model.
        CpSolver       solver = new CpSolver();
        CpSolverStatus status = solver.Solve(model);

        if (status == CpSolverStatus.Feasible)
        {
            Console.WriteLine("x = " + solver.Value(x));
            Console.WriteLine("y = " + solver.Value(y));
            Console.WriteLine("z = " + solver.Value(z));
        }
    }
Exemplo n.º 8
0
        public void NegativeSquareVar()
        {
            CpModel model        = new CpModel();
            IntVar  boolvar      = model.NewBoolVar("boolvar");
            IntVar  x            = model.NewIntVar(0, 10, "x");
            IntVar  delta        = model.NewIntVar(-5, 5, "delta");
            IntVar  squaredDelta = model.NewIntVar(0, 25, "squaredDelta");

            model.Add(x == 4).OnlyEnforceIf(boolvar);
            model.Add(x == 0).OnlyEnforceIf(boolvar.Not());
            model.Add(delta == x - 5);
            long[,] tuples = { { -5, 25 }, { -4, 16 }, { -3, 9 }, { -2,  4 }, { -1,  1 }, { 0, 0 },
                               {  1,  1 }, {  2,  4 }, {  3, 9 }, {  4, 16 }, {  5, 25 } };
            model.AddAllowedAssignments(new IntVar[] { delta, squaredDelta }, tuples);
            model.Minimize(squaredDelta);
            //Console.WriteLine("model = " + model.Model.ToString());

            CpSolver       solver = new CpSolver();
            CpSolverStatus status = solver.Solve(model);

            Assert.Equal(CpSolverStatus.Optimal, status);

            CpSolverResponse response = solver.Response;

            Assert.Equal(1, solver.Value(boolvar));
            Assert.Equal(4, solver.Value(x));
            Assert.Equal(-1, solver.Value(delta));
            Assert.Equal(1, solver.Value(squaredDelta));
            Assert.Equal(new long[] { 1, 4, -1, 1 }, response.Solution);
            Assert.Equal(1, response.ObjectiveValue);
            //Console.WriteLine("response = " + reponse.ToString());
        }
Exemplo n.º 9
0
    static void TestNegativeSquareVar()
    {
        CpModel model = new CpModel();

        IntVar boolvar      = model.NewBoolVar("boolvar");
        IntVar x            = model.NewIntVar(0, 10, "x");
        IntVar delta        = model.NewIntVar(-5, 5, "delta");
        IntVar squaredDelta = model.NewIntVar(0, 25, "squaredDelta");

        model.Add(x == 4).OnlyEnforceIf(boolvar);
        model.Add(x == 0).OnlyEnforceIf(boolvar.Not());
        model.Add(delta == x - 5);

        long[,] tuples = { { -5, 25 }, { -4, 16 }, { -3, 9 }, { -2,  4 }, { -1,  1 }, { 0, 0 },
                           {  1,  1 }, {  2,  4 }, {  3, 9 }, {  4, 16 }, {  5, 25 } };
        model.AddAllowedAssignments(new IntVar[] { delta, squaredDelta }, tuples);

        model.Minimize(squaredDelta);

        // Creates the solver and solve.
        CpSolver       solver = new CpSolver();
        CpSolverStatus status = solver.Solve(model);

        Console.WriteLine(solver.ResponseStats());
    }
Exemplo n.º 10
0
        public void SimpleLinearModel()
        {
            CpModel model = new CpModel();
            IntVar  v1    = model.NewIntVar(-10, 10, "v1");
            IntVar  v2    = model.NewIntVar(-10, 10, "v2");
            IntVar  v3    = model.NewIntVar(-100000, 100000, "v3");

            model.AddLinearConstraint(v1 + v2, -1000000, 100000);
            model.AddLinearConstraint(v1 + 2 * v2 - v3, 0, 100000);
            model.Maximize(v3);
            Assert.Equal(v1.Domain.FlattenedIntervals(),
                         new long[] { -10, 10 });
            //Console.WriteLine("model = " + model.Model.ToString());

            CpSolver       solver = new CpSolver();
            CpSolverStatus status = solver.Solve(model);

            Assert.Equal(CpSolverStatus.Optimal, status);

            CpSolverResponse response = solver.Response;

            Assert.Equal(30, response.ObjectiveValue);
            Assert.Equal(new long[] { 10, 10, 30 }, response.Solution);
            //Console.WriteLine("response = " + reponse.ToString());
        }
Exemplo n.º 11
0
    static void CpModelTest()
    {
        Solver solver = new Solver("TestConstraint");
        IntVar x      = solver.MakeIntVar(0, 10, "x");
        IntVar y      = solver.MakeIntVar(0, 10, "y");

        solver.Add(x + y == 5);
        CpModel model = solver.ExportModel();

        Console.WriteLine(model);

        Solver copy = new Solver("loader");

        copy.LoadModel(model);
        CpModelLoader   loader = copy.ModelLoader();
        IntVar          xc     = loader.IntegerExpression(0).Var();
        IntVar          yc     = loader.IntegerExpression(1).Var();
        DecisionBuilder db     = copy.MakePhase(new IntVar[] { xc, yc },
                                                Solver.CHOOSE_FIRST_UNBOUND,
                                                Solver.ASSIGN_MIN_VALUE);

        copy.NewSearch(db);
        while (copy.NextSolution())
        {
            Console.WriteLine("xc = " + xc.Value() + ", yx = " + yc.Value());
        }
        copy.EndSearch();
    }
Exemplo n.º 12
0
    static void Main()
    {
        // Creates the model.
        // [START model]
        CpModel model = new CpModel();
        // [END model]

        // Creates the variables.
        // [START variables]
        int num_vals = 3;

        IntVar x = model.NewIntVar(0, num_vals - 1, "x");
        IntVar y = model.NewIntVar(0, num_vals - 1, "y");
        IntVar z = model.NewIntVar(0, num_vals - 1, "z");

        // [END variables]

        // Adds a different constraint.
        // [START constraints]
        model.Add(x != y);
        // [END constraints]

        // Creates a solver and solves the model.
        // [START solve]
        CpSolver solver            = new CpSolver();
        VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] { x, y, z });

        solver.SearchAllSolutions(model, cb);
        // [END solve]

        Console.WriteLine(String.Format("Number of solutions found: {0}", cb.SolutionCount()));
    }
Exemplo n.º 13
0
    static void Main()
    {
        // Create the CP-SAT model.
        CpModel model = new CpModel();

        // Declare our primary variable.
        IntVar x = model.NewIntVar(0, 20, "x");

        // Create the expression variable and implement the step function
        // Note it is not defined for var == 2.
        //
        //        -               3
        // -- --      ---------   2
        //                        1
        //      -- ---            0
        // 0 ================ 20
        //
        IntVar expr = model.NewIntVar(0, 3, "expr");

        // expr == 0 on [5, 6] U [8, 10]
        ILiteral b0 = model.NewBoolVar("b0");

        model.AddLinearExpressionInDomain(x, Domain.FromValues(new long[] { 5, 6, 8, 9, 10 })).OnlyEnforceIf(b0);
        model.Add(expr == 0).OnlyEnforceIf(b0);

        // expr == 2 on [0, 1] U [3, 4] U [11, 20]
        ILiteral b2 = model.NewBoolVar("b2");

        model
        .AddLinearExpressionInDomain(
            x,
            Domain.FromIntervals(new long[][] { new long[] { 0, 1 }, new long[] { 3, 4 }, new long[] { 11, 20 } }))
        .OnlyEnforceIf(b2);
        model.Add(expr == 2).OnlyEnforceIf(b2);

        // expr == 3 when x == 7
        ILiteral b3 = model.NewBoolVar("b3");

        model.Add(x == 7).OnlyEnforceIf(b3);
        model.Add(expr == 3).OnlyEnforceIf(b3);

        // At least one bi is true. (we could use a sum == 1).
        model.AddBoolOr(new ILiteral[] { b0, b2, b3 });

        // Search for x values in increasing order.
        model.AddDecisionStrategy(new IntVar[] { x }, DecisionStrategyProto.Types.VariableSelectionStrategy.ChooseFirst,
                                  DecisionStrategyProto.Types.DomainReductionStrategy.SelectMinValue);

        // Create the solver.
        CpSolver solver = new CpSolver();

        // Force solver to follow the decision strategy exactly.
        // Tells the solver to enumerate all solutions.
        solver.StringParameters = "search_branching:FIXED_SEARCH, enumerate_all_solutions:true";

        VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] { x, expr });

        solver.Solve(model, cb);
    }
Exemplo n.º 14
0
    static void BoolOrSample()
    {
        CpModel model = new CpModel();
        IntVar  x     = model.NewBoolVar("x");
        IntVar  y     = model.NewBoolVar("y");

        model.AddBoolOr(new ILiteral[] { x, y.Not() });
    }
Exemplo n.º 15
0
        /// <summary>
        /// Returns a Made <see cref="_cells"/> <see cref="IntVar"/>.
        /// </summary>
        /// <param name="source">In this case Source is a <see cref="CpModel"/>,
        /// different from the Solver <see cref="CpSolver"/>.</param>
        /// <param name="row"></param>
        /// <param name="column"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <remarks>The vocabulary has also changed from Solver Make such and such,
        /// to Source or Model New such and such.</remarks>
        public IntVar NewCell(CpModel source, int row, int column, int value)
        {
            var variableName = $"SudokuPuzzle[{row}, {column}]";

            return(value.TrySolvedValue()
                ? source.NewConstant(value, variableName)
                : source.NewIntVar(MinimumValue + 1, MaximumValue, variableName));
        }
Exemplo n.º 16
0
        public void LinearExprBuilderCompileTest()
        {
            Console.WriteLine("LinearExprBuilderCompileTest");
            CpModel model = new CpModel();
            IntVar  v1    = model.NewIntVar(-10, 10, "v1");
            IntVar  v2    = model.NewIntVar(-10, 10, "v2");
            BoolVar b1    = model.NewBoolVar("b1");
            BoolVar b2    = model.NewBoolVar("b2");

            long[]     c1 = new long[] { 2L, 4L };
            int[]      c2 = new int[] { 2, 4 };
            LinearExpr e1 = LinearExpr.NewBuilder().AddSum(new IntVar[] { v1, v2 });

            Console.WriteLine(e1.ToString());
            LinearExpr e2 = LinearExpr.NewBuilder().AddSum(new ILiteral[] { b1, b2 });

            Console.WriteLine(e2.ToString());
            LinearExpr e3 = LinearExpr.NewBuilder().AddSum(new BoolVar[] { b1, b2 });

            Console.WriteLine(e3.ToString());
            LinearExpr e4 = LinearExpr.NewBuilder().AddWeightedSum(new IntVar[] { v1, v2 }, c1);

            Console.WriteLine(e4.ToString());
            LinearExpr e5 = LinearExpr.NewBuilder().AddWeightedSum(new ILiteral[] { b1, b2 }, c1);

            Console.WriteLine(e5.ToString());
            LinearExpr e6 = LinearExpr.NewBuilder().AddWeightedSum(new BoolVar[] { b1, b2 }, c1);

            Console.WriteLine(e6.ToString());
            LinearExpr e7 = LinearExpr.NewBuilder().AddWeightedSum(new IntVar[] { v1, v2 }, c2);

            Console.WriteLine(e7.ToString());
            LinearExpr e8 = LinearExpr.NewBuilder().AddWeightedSum(new ILiteral[] { b1, b2 }, c2);

            Console.WriteLine(e8.ToString());
            LinearExpr e9 = LinearExpr.NewBuilder().AddWeightedSum(new BoolVar[] { b1, b2 }, c2);

            Console.WriteLine(e9.ToString());
            LinearExpr e10 = LinearExpr.NewBuilder().Add(v1);

            Console.WriteLine(e10.ToString());
            LinearExpr e11 = LinearExpr.NewBuilder().Add(b1);

            Console.WriteLine(e11.ToString());
            LinearExpr e12 = LinearExpr.NewBuilder().Add(b1.Not());

            Console.WriteLine(e12.ToString());
            LinearExpr e13 = LinearExpr.NewBuilder().AddTerm(v1, -1);

            Console.WriteLine(e13.ToString());
            LinearExpr e14 = LinearExpr.NewBuilder().AddTerm(b1, -1);

            Console.WriteLine(e14.ToString());
            LinearExpr e15 = LinearExpr.NewBuilder().AddTerm(b1.Not(), -2);

            Console.WriteLine(e15.ToString());
        }
Exemplo n.º 17
0
        public void VerifyModelOnlySerializesToFile()
        {
            const string path      = "AnotherSimpleTest.dat";
            const string modelName = "TestModelLoader";

            {
                using (var s = new Solver(modelName))
                {
                    var x = s.MakeIntVar(0, 10, "x");
                    var y = s.MakeIntVar(0, 10, "y");

                    var c = x + y == 5;

                    //c.Cst.SetName("equation");

                    s.Add(c);

                    Assert.That(s.ConstraintCount(), Is.EqualTo(1));

                    var model = s.ExportModel();

                    using (var stream = File.Open(path, Create))
                    {
                        model.WriteTo(stream);
                    }
                }
            }

            {
                var model = new CpModel();

                using (var s = new Solver(modelName))
                {
                    using (var stream = File.Open(path, Open))
                    {
                        model.MergeFrom(stream);
                    }

                    s.LoadModel(model);

                    var loader = s.ModelLoader();
                    Assert.That(loader, Is.Not.Null);

                    var x = loader.IntegerExpressionByName("x").Var();
                    var y = loader.IntegerExpressionByName("y").Var();

                    // Just check that all things are equivalent.
                    var c = x + y == 5;

                    Assert.That(c.Cst.ToString(), Is.Not.EqualTo("TrueConstraint()"));

                    // Constraints should reflect what was actually there.
                    Assert.That(s.ConstraintCount(), Is.EqualTo(1));
                }
            }
        }
Exemplo n.º 18
0
    static void Main()
    {
        // Creates the model.
        // [START model]
        CpModel model = new CpModel();
        // [END model]

        // Creates the variables.
        // [START variables]
        int varUpperBound = new int[] { 50, 45, 37 }.Max();

        IntVar x = model.NewIntVar(0, varUpperBound, "x");
        IntVar y = model.NewIntVar(0, varUpperBound, "y");
        IntVar z = model.NewIntVar(0, varUpperBound, "z");

        // [END variables]

        // Creates the constraints.
        // [START constraints]
        model.Add(2 * x + 7 * y + 3 * z <= 50);
        model.Add(3 * x - 5 * y + 7 * z <= 45);
        model.Add(5 * x + 2 * y - 6 * z <= 37);
        // [END constraints]

        // [START objective]
        model.Maximize(2 * x + 2 * y + 3 * z);
        // [END objective]

        // Creates a solver and solves the model.
        // [START solve]
        CpSolver       solver = new CpSolver();
        CpSolverStatus status = solver.Solve(model);

        // [END solve]

        // [START print_solution]
        if (status == CpSolverStatus.Optimal || status == CpSolverStatus.Feasible)
        {
            Console.WriteLine($"Maximum of objective function: {solver.ObjectiveValue}");
            Console.WriteLine("x = " + solver.Value(x));
            Console.WriteLine("y = " + solver.Value(y));
            Console.WriteLine("z = " + solver.Value(z));
        }
        else
        {
            Console.WriteLine("No solution found.");
        }
        // [END print_solution]

        // [START statistics]
        Console.WriteLine("Statistics");
        Console.WriteLine($"  conflicts: {solver.NumConflicts()}");
        Console.WriteLine($"  branches : {solver.NumBranches()}");
        Console.WriteLine($"  wall time: {solver.WallTime()}s");
        // [END statistics]
    }
    static void Main()
    {
        long earliness_date = 5;
        long earliness_cost = 8;
        long lateness_date  = 15;
        long lateness_cost  = 12;

        // Create the CP-SAT model.
        CpModel model = new CpModel();

        // Declare our primary variable.
        IntVar x = model.NewIntVar(0, 20, "x");

        // Create the expression variable and implement the piecewise linear
        // function.
        //
        //  \        /
        //   \______/
        //   ed    ld
        //
        long   large_constant = 1000;
        IntVar expr           = model.NewIntVar(0, large_constant, "expr");

        // First segment.
        IntVar s1 = model.NewIntVar(-large_constant, large_constant, "s1");

        model.Add(s1 == earliness_cost * (earliness_date - x));

        // Second segment.
        IntVar s2 = model.NewConstant(0);

        // Third segment.
        IntVar s3 = model.NewIntVar(-large_constant, large_constant, "s3");

        model.Add(s3 == lateness_cost * (x - lateness_date));

        // Link together expr and x through s1, s2, and s3.
        model.AddMaxEquality(expr, new IntVar[] { s1, s2, s3 });

        // Search for x values in increasing order.
        model.AddDecisionStrategy(
            new IntVar[] { x },
            DecisionStrategyProto.Types.VariableSelectionStrategy.ChooseFirst,
            DecisionStrategyProto.Types.DomainReductionStrategy.SelectMinValue);

        // Create the solver.
        CpSolver solver = new CpSolver();

        // Force solver to follow the decision strategy exactly.
        solver.StringParameters = "search_branching:FIXED_SEARCH";

        VarArraySolutionPrinter cb =
            new VarArraySolutionPrinter(new IntVar[] { x, expr });

        solver.SearchAllSolutions(model, cb);
    }
Exemplo n.º 20
0
 static void Main()
 {
     CpModel model     = new CpModel();
     int     horizon   = 100;
     IntVar  start_var = model.NewIntVar(0, horizon, "start");
     // C# code supports IntVar or integer constants in intervals.
     int         duration = 10;
     IntVar      end_var  = model.NewIntVar(0, horizon, "end");
     IntervalVar interval = model.NewIntervalVar(start_var, duration, end_var, "interval");
 }
Exemplo n.º 21
0
    // [END solution_printer]

    static void Main()
    {
        // Constraint programming engine
        // [START model]
        CpModel model = new CpModel();
        // [START model]

        // [START variables]
        int BoardSize = 8;

        IntVar[] queens = new IntVar[BoardSize];
        for (int i = 0; i < BoardSize; ++i)
        {
            queens[i] = model.NewIntVar(0, BoardSize - 1, $"x{i}");
        }
        // [END variables]

        // Define constraints.
        // [START constraints]
        // All rows must be different.
        model.AddAllDifferent(queens);

        // All columns must be different because the indices of queens are all different.
        // No two queens can be on the same diagonal.
        LinearExpr[] diag1 = new LinearExpr[BoardSize];
        LinearExpr[] diag2 = new LinearExpr[BoardSize];
        for (int i = 0; i < BoardSize; ++i)
        {
            diag1[i] = LinearExpr.Affine(queens[i], /*coeff=*/ 1, /*offset=*/ i);
            diag2[i] = LinearExpr.Affine(queens[i], /*coeff=*/ 1, /*offset=*/ -i);
        }

        model.AddAllDifferent(diag1);
        model.AddAllDifferent(diag2);
        // [END constraints]

        // [START solve]
        // Creates a solver and solves the model.
        CpSolver        solver = new CpSolver();
        SolutionPrinter cb     = new SolutionPrinter(queens);

        // Search for all solutions.
        solver.StringParameters = "enumerate_all_solutions:true";
        // And solve.
        solver.Solve(model, cb);
        // [END solve]

        // [START statistics]
        Console.WriteLine("Statistics");
        Console.WriteLine($"  conflicts : {solver.NumConflicts()}");
        Console.WriteLine($"  branches  : {solver.NumBranches()}");
        Console.WriteLine($"  wall time : {solver.WallTime()} s");
        Console.WriteLine($"  number of solutions found: {cb.SolutionCount()}");
        // [END statistics]
    }
Exemplo n.º 22
0
    static void Main()
    {
        InitTaskList();
        int taskCount = GetTaskCount();

        CpModel model = new CpModel();

        IntervalVar[] tasks       = new IntervalVar[taskCount];
        BoolVar[]     taskChoosed = new BoolVar[taskCount];
        IntVar[]      allEnds     = new IntVar[GetEndTaskCount()];

        int endJobCounter = 0;

        foreach (Job j in myJobList)
        {
            BoolVar[] tmp = new BoolVar[j.AlternativeTasks.Count];
            int       i   = 0;
            foreach (Task t in j.AlternativeTasks)
            {
                long ti = taskIndexes[t.Name];
                taskChoosed[ti] = model.NewBoolVar(t.Name + "_choose");
                tmp[i++]        = taskChoosed[ti];
                IntVar start = model.NewIntVar(0, 10000, t.Name + "_start");
                IntVar end   = model.NewIntVar(0, 10000, t.Name + "_end");
                tasks[ti] = model.NewIntervalVar(start, t.Duration, end, t.Name + "_interval");
                if (j.Successor == null)
                {
                    allEnds[endJobCounter++] = end;
                }
                if (!tasksToEquipment.ContainsKey(t.Equipment))
                {
                    tasksToEquipment[t.Equipment] = new List <IntervalVar>();
                }
                tasksToEquipment[t.Equipment].Add(tasks[ti]);
            }
            model.AddExactlyOne(tmp);
        }

        foreach (KeyValuePair <long, List <IntervalVar> > pair in tasksToEquipment)
        {
            model.AddNoOverlap(pair.Value);
        }

        IntVar makespan = model.NewIntVar(0, 100000, "makespan");

        model.AddMaxEquality(makespan, allEnds);
        model.Minimize(makespan);

        // Create the solver.
        CpSolver solver = new CpSolver();

        // Solve the problem.
        solver.Solve(model);
        Console.WriteLine(solver.ResponseStats());
    }
Exemplo n.º 23
0
    static void Main()
    {
        CpModel model = new CpModel();
        // Three weeks.
        int horizon = 21;

        // Task 0, duration 2.
        IntVar      start_0    = model.NewIntVar(0, horizon, "start_0");
        int         duration_0 = 2;
        IntVar      end_0      = model.NewIntVar(0, horizon, "end_0");
        IntervalVar task_0     =
            model.NewIntervalVar(start_0, duration_0, end_0, "task_0");

        //  Task 1, duration 4.
        IntVar      start_1    = model.NewIntVar(0, horizon, "start_1");
        int         duration_1 = 4;
        IntVar      end_1      = model.NewIntVar(0, horizon, "end_1");
        IntervalVar task_1     =
            model.NewIntervalVar(start_1, duration_1, end_1, "task_1");

        // Task 2, duration 3.
        IntVar      start_2    = model.NewIntVar(0, horizon, "start_2");
        int         duration_2 = 3;
        IntVar      end_2      = model.NewIntVar(0, horizon, "end_2");
        IntervalVar task_2     =
            model.NewIntervalVar(start_2, duration_2, end_2, "task_2");

        // Weekends.
        IntervalVar weekend_0 = model.NewIntervalVar(5, 2, 7, "weekend_0");
        IntervalVar weekend_1 = model.NewIntervalVar(12, 2, 14, "weekend_1");
        IntervalVar weekend_2 = model.NewIntervalVar(19, 2, 21, "weekend_2");

        // No Overlap constraint.
        model.AddNoOverlap(new IntervalVar[] { task_0, task_1, task_2, weekend_0,
                                               weekend_1, weekend_2 });

        // Makespan objective.
        IntVar obj = model.NewIntVar(0, horizon, "makespan");

        model.AddMaxEquality(obj, new IntVar[] { end_0, end_1, end_2 });
        model.Minimize(obj);

        // Creates a solver and solves the model.
        CpSolver       solver = new CpSolver();
        CpSolverStatus status = solver.Solve(model);

        if (status == CpSolverStatus.Optimal)
        {
            Console.WriteLine("Optimal Schedule Length: " + solver.ObjectiveValue);
            Console.WriteLine("Task 0 starts at " + solver.Value(start_0));
            Console.WriteLine("Task 1 starts at " + solver.Value(start_1));
            Console.WriteLine("Task 2 starts at " + solver.Value(start_2));
        }
    }
Exemplo n.º 24
0
        public void TestInterval()
        {
            Console.WriteLine("TestInterval test");
            CpModel     model = new CpModel();
            IntVar      v     = model.NewIntVar(-10, 10, "v");
            IntervalVar i     = model.NewFixedSizeIntervalVar(v, 3, "i");

            Assert.Equal("v", i.StartExpr().ShortString());
            Assert.Equal("3", i.SizeExpr().ShortString());
            Assert.Equal("(v + 3)", i.EndExpr().ShortString());
        }
Exemplo n.º 25
0
        public void ExportModel()
        {
            CpModel model = new CpModel();
            IntVar  v1    = model.NewIntVar(-10, 10, "v1");
            IntVar  v2    = model.NewIntVar(-10, 10, "v2");

            model.Add(-100000 <= v1 + 2 * v2 <= 100000);
            model.Minimize(v1 - 2 * v2);
            Assert.True(model.ExportToFile("test_model_dotnet.pbtxt"));
            Console.WriteLine("Model written to file");
        }
Exemplo n.º 26
0
    static void CpModelTest()
    {
        Solver solver = new Solver("TestConstraint");
        IntVar x      = solver.MakeIntVar(0, 10, "x");
        IntVar y      = solver.MakeIntVar(0, 10, "y");

        solver.Add(x + y == 5);
        CpModel model = solver.ExportModel();

        Console.WriteLine(model);
    }
Exemplo n.º 27
0
        public void Solve()
        {
            // Creates the model.
            CpModel model = new CpModel();
            // Creates the variables.
            int num_vals = 9;

            //Creat the Sudoku grid
            IntVar[][] grid = new IntVar[9][];
            for (int k = 0; k < 9; k++)
            {
                grid[k] = new IntVar[9];
            }

            //get initial sudoku grid and put the 9 possibilities in Empty cells
            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    if (Sudoku.getCaseInitialSudoku(i, j) == 0)
                    {
                        grid[i][j] = model.NewIntVar(1, num_vals, "C" + i.ToString() + j.ToString());
                    }
                    else
                    {
                        grid[i][j] = model.NewIntVar(Sudoku.getCaseInitialSudoku(i, j), Sudoku.getCaseInitialSudoku(i, j), "C" + i.ToString() + j.ToString());
                    }
                }
            }


            // Adds a different constraint.
            for (int k = 0; k < 9; k++)
            {
                //All the ligne might have a different number in each cells
                model.AddAllDifferent(GetRow(grid, k));
                //All the columns might have a different number in each cells
                model.AddAllDifferent(GetColumn(grid, k));
            }
            //All 9 Regions might have a different number in each cells
            for (int region = 0; region < 9; region++)
            {
                model.AddAllDifferent(GetRegion(grid, region));
            }

            // Creates a solver and solves the model.
            CpSolver solver            = new CpSolver();
            VarArraySolutionPrinter cb = new VarArraySolutionPrinter(grid);

            solver.SearchAllSolutions(model, cb);
            int[][] values = cb.getValues();

            Sudoku.setSudoku(values);
        }
Exemplo n.º 28
0
    // [END solution_printer]

    // Solve the CP+IS+FUN==TRUE cryptarithm.
    static void Main()
    {
        // Constraint programming engine
        // [START model]
        CpModel model = new CpModel();
        // [START model]

        // [START variables]
        int kBase = 10;

        IntVar c = model.NewIntVar(1, kBase - 1, "C");
        IntVar p = model.NewIntVar(0, kBase - 1, "P");
        IntVar i = model.NewIntVar(1, kBase - 1, "I");
        IntVar s = model.NewIntVar(0, kBase - 1, "S");
        IntVar f = model.NewIntVar(1, kBase - 1, "F");
        IntVar u = model.NewIntVar(0, kBase - 1, "U");
        IntVar n = model.NewIntVar(0, kBase - 1, "N");
        IntVar t = model.NewIntVar(1, kBase - 1, "T");
        IntVar r = model.NewIntVar(0, kBase - 1, "R");
        IntVar e = model.NewIntVar(0, kBase - 1, "E");

        // We need to group variables in a list to use the constraint AllDifferent.
        IntVar[] letters = new IntVar[] { c, p, i, s, f, u, n, t, r, e };
        // [END variables]

        // [START constraints]
        // Define constraints.
        model.AddAllDifferent(letters);

        // CP + IS + FUN = TRUE
        model.Add(c * kBase + p + i * kBase + s + f * kBase * kBase + u * kBase + n ==
                  t * kBase * kBase * kBase + r * kBase * kBase + u * kBase + e);
        // [END constraints]

        // [START solve]
        // Creates a solver and solves the model.
        CpSolver solver            = new CpSolver();
        VarArraySolutionPrinter cb = new VarArraySolutionPrinter(letters);

        // Search for all solutions.
        solver.StringParameters = "enumerate_all_solutions:true";
        // And solve.
        solver.Solve(model, cb);
        // [END solve]

        // [START statistics]
        Console.WriteLine("Statistics");
        Console.WriteLine($"  conflicts : {solver.NumConflicts()}");
        Console.WriteLine($"  branches  : {solver.NumBranches()}");
        Console.WriteLine($"  wall time : {solver.WallTime()} s");
        Console.WriteLine($"  number of solutions found: {cb.SolutionCount()}");
        // [END statistics]
    }
Exemplo n.º 29
0
 static void OptionalIntervalSample()
 {
     CpModel model     = new CpModel();
     int     horizon   = 100;
     IntVar  start_var = model.NewIntVar(0, horizon, "start");
     // C# code supports IntVar or integer constants in intervals.
     int         duration     = 10;
     IntVar      end_var      = model.NewIntVar(0, horizon, "end");
     IntVar      presence_var = model.NewBoolVar("presence");
     IntervalVar interval     = model.NewOptionalIntervalVar(
         start_var, duration, end_var, presence_var, "interval");
 }
Exemplo n.º 30
0
        // Configuration for engine / wheels combinations
        public void ConfigureSecondDomain(EngineType engine)
        {
            Console.WriteLine("Engine / Wheels");
            CpModel model = new CpModel();

            IntVar gas      = model.NewBoolVar("gas");
            IntVar electric = model.NewBoolVar("electric");

            IntVar w0 = model.NewBoolVar("90/45_17'");
            IntVar w1 = model.NewBoolVar("160/45 12'");
            IntVar w2 = model.NewBoolVar("165/55 15'");
            IntVar w3 = model.NewBoolVar("195/65 16'");
            IntVar w4 = model.NewBoolVar("255/65 17'");
            IntVar w5 = model.NewBoolVar("300/70 20'");
            IntVar w6 = model.NewBoolVar("325/65 24'");

            model.AddBoolXor(new[] { gas, electric });

            model.Add(electric != w1);
            model.Add(electric != w2);
            model.Add(electric != w3);
            model.Add(electric != w4);
            model.Add(electric != w5);
            model.Add(electric != w6);

            model.Add(gas != w0);

            CpSolver solver = new CpSolver();

            SolutionPrinter cb =
                new SolutionPrinter(new IntVar[] { gas, electric,
                                                   w0, w1, w2, w3, w4, w5, w6 });

            Console.WriteLine(String.Format("Number of solutions found: {0}",
                                            cb.SolutionCount()));

            solver.SearchAllSolutions(model, cb);

            var secondDomain = cb.FeasibleSolutions();
            var wheels       = _wheelsService.Get();

            if (engine == EngineType.Gas)
            {
                List <Wheels> feasibleWheels = wheels.FindAll(x => x.type == gas.ShortString());
                feasible_wheels_ = feasibleWheels;
            }

            if (engine == EngineType.Electric)
            {
                List <Wheels> feasibleWheels = wheels.FindAll(x => x.type == electric.ShortString());
                feasible_wheels_ = feasibleWheels;
            }
        }