Пример #1
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.
        solver.StringParameters = "search_branching:FIXED_SEARCH";

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

        solver.SearchAllSolutions(model, cb);
    }
Пример #2
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);

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

            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.0, response.ObjectiveValue, 6);
        }
Пример #3
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);
            CpSolverResponse response = solver.Response;

            Console.WriteLine("response = " + response.ToString());

            Assert.Equal(CpSolverStatus.Optimal, status);

            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.0, response.ObjectiveValue, 5);
        }
Пример #4
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.ModelSat)
        {
            Console.WriteLine("x = " + solver.Value(x));
            Console.WriteLine("y = " + solver.Value(y));
            Console.WriteLine("z = " + solver.Value(z));
        }
    }
Пример #5
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.ModelSat)
        {
            Console.WriteLine("x = " + solver.Value(x));
            Console.WriteLine("y = " + solver.Value(y));
            Console.WriteLine("z = " + solver.Value(z));
        }
    }
Пример #6
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()));
    }
    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()));
    }
Пример #8
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');

        // Adds a different constraint.
        model.Add(x != y);

        // Maximizes a linear combination of variables.
        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.SolveWithSolutionCallback(model, cb);
        Console.WriteLine(String.Format('Number of solutions found: {0}',
                                        cb.SolutionCount()));
    }
Пример #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());
    }
Пример #10
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()}");
    }
Пример #11
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());
        }
Пример #12
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);
    }
Пример #14
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]
    }
Пример #15
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());
    }
Пример #16
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);
        }
Пример #17
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));
        }
    }
Пример #18
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;
            }
        }
Пример #19
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]
    }
Пример #20
0
        public static void Main(string[] args)
        {
            // -- CREATE THE MODEL --
            var model = new CpModel();

            // -- SET UP THE DATA --
            var jobs = CreateJobsList();

            // Number of machines
            var machinesCount = 1 + jobs.Max(job => job.Max(task => task.Item1));

            // List of machines
            var machines = new List <int>();

            InitMachinesList(machinesCount, machines);

            // Total duration of a single task
            var horizon = jobs.Sum(job => job.Sum(task => task.Item2));

            // -- ADD VARIABLES TO MODEL --
            // Dictionary of all tasks using a tuple of job and task as key
            var tasks = new Dictionary <(int, int), Task>();

            // List containing each machines' intervals
            // Interval is time between tasks
            var machineIntervals = new List <List <IntervalVar> >();

            InitMachineIntervalsList(machinesCount, machineIntervals);

            // Add all variables to the model
            AddModelVariables(jobs, model, horizon, tasks, machineIntervals);

            // Add all constraints to the model
            AddConstraints(machines, model, machineIntervals, jobs, tasks, horizon);

            // Solve the model
            var solver = new CpSolver();
            var status = solver.Solve(model);

            // If an optimal solution is found, print it
            if (status == CpSolverStatus.Optimal)
            {
                PrintSolution(
                    machinesCount,
                    AssignTasks(machinesCount, jobs, solver, tasks),
                    solver);
            }
        }
Пример #21
0
    static void TestSimpleLinearModel2()
    {
        Console.WriteLine("TestSimpleLinearModel2");
        CpModel model = new CpModel();
        IntVar  v1    = model.NewIntVar(-10, 10, "v1");
        IntVar  v2    = model.NewIntVar(-10, 10, "v2");

        model.AddLinearConstraint(new[] { v1, v2 }, new[] { 1, 1 }, -1000000, 100000);
        model.Maximize(v1 - 2 * v2);

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

        Check(status == CpSolverStatus.Optimal, "Wrong status after solve");
        CheckDoubleEq(30.0, solver.ObjectiveValue, "Wrong solution value");
        Console.WriteLine("response = " + solver.Response.ToString());
    }
Пример #22
0
        public static void SatVerifier(
            string inFileName,
            string strResult)
        {
            string outFile  = inFileName.Replace("In", "Out");
            string expected = File.ReadAllText(outFile);

            Debug.WriteLine($"Solving {Path.GetFileName(outFile)}");

            var lines = strResult.Split(TestTools.NewLineChars, StringSplitOptions.RemoveEmptyEntries);

            long expCount, varCount;

            TestTools.ParseTwoNumbers(lines[0], out expCount, out varCount);
            CpModel  model  = new CpModel();
            CpSolver solver = new CpSolver();

            solver.StringParameters = "max_time_in_seconds:5.0";

            ILiteral[] variables = Enumerable.Range(0, (int)varCount + 1).Select(n => model.NewBoolVar($"x{n}")).ToArray();

            List <ILiteral[]> cnf = lines
                                    .Skip(1)
                                    .Select(e => e.Split(TestTools.IgnoreChars, StringSplitOptions.RemoveEmptyEntries)
                                            .Select(s => int.Parse(s))
                                            .Where(v => v != 0)
                                            .Select(v => v > 0 ? variables[v]: variables[-1 * v].Not())
                                            .ToArray())
                                    .ToList();

            foreach (var clause in cnf)
            {
                model.AddBoolOr(clause);
            }

            var result = solver.Solve(model);

            bool bSat = result == CpSolverStatus.Feasible;

            Debug.WriteLine($"Solution found: {bSat}");
            var bExpectedSat =
                expected.Trim(TestTools.IgnoreChars) == "SATISFIABLE";

            Assert.AreEqual(bExpectedSat, bSat);
        }
Пример #23
0
        public void SimpleLinearModel2()
        {
            CpModel model = new CpModel();
            IntVar v1 = model.NewIntVar(-10, 10, "v1");
            IntVar v2 = model.NewIntVar(-10, 10, "v2");
            model.AddLinearConstraint(new[] {v1, v2}, new[] {1, 1}, -1000000, 100000);
            model.Maximize(v1 - 2 * v2);
            //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}, response.Solution);
            //Console.WriteLine("response = " + reponse.ToString());
        }
Пример #24
0
    static void Main()
    {
        // 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 a solver and solves the model.
        CpSolver solver = new CpSolver();
        VarArraySolutionPrinterWithLimit cb = new VarArraySolutionPrinterWithLimit(new IntVar[] { x, y, z }, 5);

        solver.SearchAllSolutions(model, cb);
        Console.WriteLine(String.Format("Number of solutions found: {0}", cb.SolutionCount()));
    }
Пример #25
0
    static void TestDivision()
    {
        Console.WriteLine("TestDivision");
        CpModel model = new CpModel();
        IntVar  v1    = model.NewIntVar(0, 10, "v1");
        IntVar  v2    = model.NewIntVar(1, 10, "v2");

        model.AddDivisionEquality(3, v1, v2);

        Console.WriteLine(model.Model);

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

        Check(status == CpSolverStatus.Feasible, "Wrong status after solve");
        Console.WriteLine("v1 = {0}", solver.Value(v1));
        Console.WriteLine("v2 = {0}", solver.Value(v2));
    }
Пример #26
0
        public void SolverTest(bool callGC)
        {
            CpModel model = new CpModel();

            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");

            model.Add(x != y);

            CpSolver solver = new CpSolver();

            if (callGC)
            {
                GC.Collect();
            }
            CpSolverStatus status = solver.Solve(model);
        }
Пример #27
0
    static void TestSimpleLinearModel3()
    {
        Console.WriteLine("TestSimpleLinearModel3");
        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);

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

        Check(status == CpSolverStatus.Optimal, "Wrong status after solve");
        CheckDoubleEq(-30.0, solver.ObjectiveValue, "Wrong solution value");
        CheckLongEq(-10, solver.Value(v1), "Wrong value");
        CheckLongEq(10, solver.Value(v2), "Wrong value");
        CheckLongEq(-30, solver.Value(v1 - 2 * v2), "Wrong value");
    }
Пример #28
0
        public void Modulo()
        {
            CpModel model = new CpModel();
            IntVar v1 = model.NewIntVar(1, 10, "v1");
            IntVar v2 = model.NewIntVar(1, 10, "v2");
            model.AddModuloEquality(3, v1, v2);
            //Console.WriteLine(model.Model);

            CpSolver solver = new CpSolver();
            CpSolverStatus status = solver.Solve(model);
            Assert.Equal(CpSolverStatus.Feasible, status);

            CpSolverResponse response = solver.Response;
            Assert.Equal(3, solver.Value(v1));
            Assert.Equal(4, solver.Value(v2));
            Assert.Equal(new long[] {3, 4, 3}, response.Solution);
            Assert.Equal(0, response.ObjectiveValue);
            //Console.WriteLine("response = " + reponse.ToString());
        }
Пример #29
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]

        // Creates the constraints.
        // [START constraints]
        model.Add(x != y);
        // [END constraints]

        // 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("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]
    }
Пример #30
0
        public void SimpleLinearModel3()
        {
            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);
            //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(-10, solver.Value(v1));
            Assert.Equal(10, solver.Value(v2));
            Assert.Equal(new long[] {-10, 10}, response.Solution);
            Assert.Equal(-30, solver.Value(v1 - 2 * v2));
            Assert.Equal(-30, response.ObjectiveValue);
            //Console.WriteLine("response = " + reponse.ToString());
        }