Пример #1
0
        /// <summary>
        /// Returns the possible ways that a query term can unify with a program term
        /// </summary>
        public static IBindings Unify(this ILiteral query, ILiteral program, IBindings bindings = null)
        {
            var simpleUnifier = new SimpleUnifier();
            var freeVariables = new HashSet<ILiteral>();

            // Run the unifier
            var queryFreeVars = simpleUnifier.QueryUnifier.Compile(query, bindings);
            if (queryFreeVars == null) return null;

            simpleUnifier.PrepareToRunProgram();

            var programFreeVars = simpleUnifier.ProgramUnifier.Compile(program, bindings);
            if (programFreeVars == null) return null;

            freeVariables.UnionWith(queryFreeVars);

            // Retrieve the unified value for the program
            var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query);

            // If the result was valid, return as the one value from this function
            if (result != null)
            {
                var variableBindings = freeVariables.ToDictionary(variable => variable,
                    variable => simpleUnifier.UnifiedValue(variable));

                return new BasicBinding(result, variableBindings);
            }
            else
            {
                return null;
            }
        }
Пример #2
0
        /// <summary>
        /// Compiles a literal for unification using a query unifier
        /// </summary>
        /// <returns>
        /// The list of variables in the literal
        /// </returns>
        public static IEnumerable<ILiteral> Compile(this IQueryUnifier unifier, ILiteral literal, IBindings bindings = null)
        {
            if (unifier == null) throw new ArgumentNullException("unifier");
            if (literal == null) throw new ArgumentNullException("literal");

            // Flatten the literal
            var assignments = literal.Flatten().ToList();

            // Bind the variables in order
            var freeVariables = unifier.Bind(assignments);

            // Rebind the assignments if necessary
            if (bindings != null)
            {
                assignments = assignments.BindVariables(bindings).ToList();
            }

            // Compile the result
            if (!unifier.Compile(assignments))
            {
                return null;
            }

            return freeVariables;
        }
Пример #3
0
        public bool GetStructure(ILiteral termName, int termLength, ILiteral variable)
        {
            var variableIndex = _bindingForVariable[variable];
            _usedVariables.Add(variableIndex);

            _program.Write(Operation.GetStructure, termName, variableIndex, termLength);
            return true;
        }
Пример #4
0
        /// <summary>
        /// Adds a positive literal to a negative Horn clause
        /// </summary>
        public static IClause Then(this IClause negativeHornClause, ILiteral then)
        {
            if (negativeHornClause == null) throw new ArgumentNullException("negativeHornClause");
            if (negativeHornClause.Implies != null) throw new ArgumentException("Clause already has an implication", "negativeHornClause");
            if (then == null) throw new ArgumentNullException("then");

            return new PositiveClause(negativeHornClause, then);
        }
Пример #5
0
        public void BindVariable(int index, ILiteral variableName)
        {
            while (_variables.Count <= index)
            {
                _variables.Add(new SimpleReference());
            }

            _addressForName[variableName] = _variables[index];
            _indexForVariable[variableName] = index;
        }
Пример #6
0
        public bool GetValue(ILiteral variable1, ILiteral variable2)
        {
            var variableIndex1 = _bindingForVariable[variable1];
            var variableIndex2 = _bindingForVariable[variable2];

            _usedVariables.Add(variableIndex1);
            _usedVariables.Add(variableIndex2);

            _program.Write(Operation.GetValue, variableIndex1, variableIndex2);
            return true;
        }
Пример #7
0
 public ILiteral GetValueForVariable(ILiteral variable)
 {
     ILiteral result;
     if (_valueForVariable.TryGetValue(variable, out result))
     {
         return result;
     }
     else
     {
         return null;
     }
 }
Пример #8
0
 /// <summary>
 /// Returns the mapped version of a particular variable
 /// </summary>
 public ILiteral MapVariable(ILiteral variable)
 {
     ILiteral result;
     if (_variableMapping.TryGetValue(variable, out result))
     {
         return result;
     }
     else
     {
         return variable;
     }
 }
        /// <summary>
        /// Retrieves an object representing the assignments for a particular literal when used as a predicate
        /// </summary>
        public static PredicateAssignmentList FromPredicate(ILiteral predicate)
        {
            var result = new PredicateAssignmentList();

            if (predicate.UnificationKey != null)
            {
                foreach (var argument in predicate.Dependencies)
                {
                    result.AddArgument(argument);
                }
            }

            return result;
        }
Пример #10
0
        /// <summary>
        /// Queries a solver for a goal
        /// </summary>
        public static IQueryResult Query(this ISolver solver, ILiteral goal)
        {
            // Result is false for something without a key
            if (goal.UnificationKey == null)
            {
                return new BasicQueryResult(false, new EmptyBinding(null));
            }

            // Compile the query
            var unifier = new SimpleUnifier();
            var assignments = new PredicateAssignmentList();

            // Assume we have a basic predicate
            foreach (var arg in goal.Dependencies)
            {
                assignments.AddArgument(arg);
            }

            // Run through the unifier
            var freeVariableNames = unifier.QueryUnifier.Bind(assignments.Assignments);
            var freeVariables = freeVariableNames.Select(variable => unifier.GetVariableLocation(variable).Dereference());
            unifier.QueryUnifier.Compile(assignments.Assignments);

            // Call via the solver
            var moveNext = solver.Call(goal.UnificationKey, unifier.GetArgumentVariables(assignments.CountArguments()));

            Func<IQueryResult> nextResult = () =>
                {
                    // Update the variables to the next result
                    var succeeded = moveNext();

                    // Nothing to do if we didn't succeed
                    if (!succeeded)
                    {
                        return new BasicQueryResult(false, new EmptyBinding(null));
                    }

                    // Bind the variables
                    var variableValues = freeVariables
                        .Select(varRef => varRef.Freeze())
                        .Zip(freeVariableNames, (value, name) => new { Value = value, Name = name }).ToArray();
                    var binding = new BasicBinding(null, variableValues.ToDictionary(val => val.Name, val => val.Value));

                    // Return the result
                    return new BasicQueryResult(true, binding);
                };

            // Chain to produce the final result
            return new ChainedResult(nextResult(), () => Task.FromResult(nextResult()));
        }
Пример #11
0
        public ByteCodeExecutor(ByteCodePoint[] program, ILiteral[] literals, int maxVariableIndex)
        {
            if (program == null) throw new ArgumentNullException(nameof(program));

            _program        = program;
            _literals       = literals;
            _programCounter = 0;
            _environment    = new ByteCodeEnvironment(0, 0, null);
            _registers      = new SimpleReference[maxVariableIndex];

            for (var registerIndex = 0; registerIndex<_registers.Length; ++registerIndex)
            {
                _registers[registerIndex] = new SimpleReference();
            }
        }
Пример #12
0
        /// <summary>
        /// Binds the variables in the unifier for a set of assignments
        /// </summary>
        /// <returns>
        /// The list of free variables in the assignments
        /// </returns>
        public static IEnumerable<ILiteral> Bind(this IBaseUnifier unifier, IEnumerable<IAssignmentLiteral> assignments, IEnumerable<ILiteral> permanentVariables = null)
        {
            if (unifier == null) throw new ArgumentNullException("unifier");
            if (assignments == null) throw new ArgumentNullException("assignments");
            if (permanentVariables == null) permanentVariables = new ILiteral[0];

            var indexForPermanent = new Dictionary<ILiteral, int>();
            var freeVariables = new List<ILiteral>();
            var index = 0;

            // Assign permanent variables to indexes starting from 0
            // TODO: what if a permanent variable appears in an argument location?
            foreach (var permVariable in permanentVariables)
            {
                indexForPermanent[permVariable] = index;
                ++index;
            }

            // Bind the assignments
            foreach (var assign in assignments)
            {
                int variableIndex;

                // If the assignment is of the form X1 = Y where Y is a permanent variable, use the permanent variable index
                if (!indexForPermanent.TryGetValue(assign.Value, out variableIndex))
                {
                    // For other assignments, use an increasing index
                    variableIndex = index;
                    ++index;
                }

                if (assign.Value.UnificationKey == null)
                {
                    // Values without a unification key are free variables (they can have any value)
                    freeVariables.Add(assign.Value);
                    unifier.BindVariable(variableIndex, assign.Value);
                    unifier.BindVariable(variableIndex, assign.Variable);
                }
                else
                {
                    // Values with a unification key are not free
                    unifier.BindVariable(variableIndex, assign.Value.UnificationKey);
                    unifier.BindVariable(variableIndex, assign.Variable);
                }
            }

            return freeVariables;
        }
Пример #13
0
        public void TestSafraExampleInPaper()
        {
            var ba = new BuchiAutomaton<AutomatonNode> (new AutomatonNodeFactory ());
            var q = ba.AddNode ("qI");
            var f = ba.AddNode ("f");
            var g = ba.AddNode ("g");

            var pa = new Proposition ("a");
            var pb = new Proposition ("b");
            var pc = new Proposition ("c");

            var a = new ILiteral[] { pa };
            var b = new ILiteral[] { pb };
            var c = new ILiteral [] { pc };

            // a,b from qI to qI
            ba.AddTransition (q, q, a);
            ba.AddTransition (q, q, b);

            // c from f to f
            ba.AddTransition (f, f, c);

            // a from qI to f
            ba.AddTransition (q, f, a);

            // a from f to g
            ba.AddTransition (f, g, a);

            // a from g to g
            ba.AddTransition (g, g, a);

            // a from g to f
            ba.AddTransition (g, f, a);

            ba.SetInitialNode (q);
            ba.SetAcceptanceCondition (new BuchiAcceptance<AutomatonNode> (new [] { f, g }));

            var rabin = ba.Determinize ();

            //var folder = new Fold<RabinAutomaton<AutomatonNode>, AutomatonNode> ();
            //rabin = folder.Transform (rabin);
            rabin.UnfoldTransitions ();

            Console.WriteLine (rabin.ToDot ());
        }
        public Func<bool> Call(ILiteral predicate, params IReferenceLiteral[] arguments)
        {
            // Assume that predicate is correct

            // Load the arguments into a simple unifier
            var unifier = new SimpleUnifier();
            unifier.LoadArguments(arguments);

            // Unify using the predicate
            unifier.ProgramUnifier.Bind(_clauseAssignments[0].Assignments);
            if (!unifier.ProgramUnifier.Compile(_clauseAssignments[0].Assignments))
            {
                // Fail if we can't unify
                return () => false;
            }

            // Call using the clauses
            return SolveAllSubclauses(_clauseAssignments.Skip(1), unifier);
        }
Пример #15
0
        public Func<bool> Call(ILiteral predicate, params IReferenceLiteral[] arguments)
        {
            List<ISolver> solvers;

            // Result is nothing if there are no solvers that match this key
            if (!_solverForUnificationKey.TryGetValue(predicate, out solvers))
            {
                return () => false;
            }

            // Call each solver in turn
            IEnumerator<ISolver> currentSolver = solvers.GetEnumerator();
            Func<bool> currentResult = () => false;

            return () =>
            {
                for (;;)
                {
                    // Result is true if the current solver is still returning results
                    if (currentResult())
                    {
                        return true;
                    }

                    // Get the next result
                    if (!currentSolver.MoveNext())
                    {
                        // No more solvers to try
                        return false;
                    }

                    // Call the next solver
                    // TODO: one slight problem here is we expect the solver to backtrack the argument values before returning false
                    // (which is a performance loss for the very last solver)
                    currentResult = currentSolver.Current.Call(predicate, arguments);
                }
            };
        }
Пример #16
0
        public Task<IEnumerable<IClause>> CandidatesForLiteral(ILiteral literal)
        {
            if (literal == null) throw new ArgumentNullException("literal");

            // Index by unification key
            FillClauseCache();

            // Result is all clauses if there is no unification key
            if (literal.UnificationKey == null)
            {
                return Task.FromResult(Clauses);
            }

            // Result is the clauses for this value's unification key
            IClause[] result;

            if (!_unificationCandidates.TryGetValue(literal.UnificationKey, out result))
            {
                result = new IClause[0];
            }

            return Task.FromResult<IEnumerable<IClause>>(result);
        }
Пример #17
0
 public ILiteral GetValueForVariable(ILiteral variable)
 {
     return null;
 }
Пример #18
0
 public bool GetValue(ILiteral variable1, ILiteral variable2)
 {
     Unify(_addressForName[variable1], _addressForName[variable2]);
     return(true);
 }
Пример #19
0
        public bool UnifyValue(ILiteral variable)
        {
            if (!_writeMode)
            {
                if (!Unify(_addressForName[variable], _structurePtr))
                {
                    return false;
                }
            }
            else
            {
                _lastArgument.SetTo(_addressForName[variable]);
                _lastArgument = _lastArgument.NextArgument;
            }

            _structurePtr = _structurePtr.NextArgument;

            return true;
        }
Пример #20
0
 /// <summary>
 /// Write out given data as a Literal.
 /// <param name="b">Literal representing data to write out</param>
 /// </summary>
 /// <returns>this</returns>
 public Argument WriteBytes(ILiteral b)
 {
     items.Add(b);
     return(this);
 }
Пример #21
0
 public IPropertyAssignment MakePropertyAssignment(ILiteral name, IExpression expression)
 {
     // TODO: Is calling ToString() adequate here?
     return(new PropertyAssignment(((Literal)name).ToString(), (Expression)expression));
 }
Пример #22
0
 public BasicBinding(ILiteral result, Dictionary <ILiteral, ILiteral> valueForVariable)
 {
     _result           = result;
     _valueForVariable = valueForVariable;
 }
Пример #23
0
 public virtual void Visit(ILiteral instance)
 {
 }
Пример #24
0
        public static bool TryGetLiteral(object value, out ILiteral literal)
        {
            literal = null;
            if (value is bool b)
            {
                literal = new BooleanLiteral(b);
            }
            else if (value is byte by)
            {
                literal = new IntegerLiteral(by);
            }
            else if (value is sbyte sb)
            {
                literal = new IntegerLiteral(sb);
            }
            else if (value is short sh)
            {
                literal = new IntegerLiteral(sh);
            }
            else if (value is ushort us)
            {
                literal = new IntegerLiteral(us);
            }
            else if (value is int i)
            {
                literal = new IntegerLiteral(i);
            }
            else if (value is uint ui)
            {
                literal = new IntegerLiteral(ui);
            }
            else if (value is long l)
            {
                literal = new IntegerLiteral(l);
            }
            else if (value is ulong ul)
            {
                literal = new IntegerLiteral((long)ul);
            }
            else if (value is float f)
            {
                literal = new FloatLiteral(f);
            }
            else if (value is double d)
            {
                literal = new FloatLiteral(d);
            }
            else if (value is DateTime dt)
            {
                literal = new DateTimeLiteral(dt);
            }
            else if (value is Guid g)
            {
                literal = new StringLiteral(g.ToArasId());
            }
            else if (value is string str)
            {
                literal = new StringLiteral(str);
            }
            else
            {
                return(false);
            }

            return(true);
        }
Пример #25
0
 /// <summary>
 /// Creates a new observable property access proxy
 /// </summary>
 /// <param name="modelElement">The model instance element for which to create the property access proxy</param>
 public ValueProxy(ILiteral modelElement) :
     base(modelElement, "Value")
 {
 }
Пример #26
0
 public ILiteral UnifiedValue(ILiteral name)
 {
     return(_addressForName[name].Freeze());
 }
Пример #27
0
 protected virtual ILiteral VisitLiteral(ILiteral node)
 {
     return(node);
 }
Пример #28
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.AddLinearConstraintWithBounds(
            new IntVar[] { x },
            new long[] { 1 },
            new long[] { 5, 6, 8, 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.AddLinearConstraintWithBounds(
            new IntVar[] { x },
            new long[] { 1 },
            new long[] { 0, 1, 3, 4, 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);
    }
Пример #29
0
 public IPropertyAssignment MakePropertySetAssignment(Scope scope, ILiteral name, IIdentifier paramName, IStatement body, Scope innerScope)
 {
   // TODO: Is calling ToString() adequate here?
   // TODO: Implement properly. This is just a quick hack to get things semi-working.
   var paramList = MakeIdentifierList();
   paramList.Add(paramName);
   var setterName = MakeIdentifier(innerScope, name.ToString(), ((Node)name).SourceOffset);
   var setter = MakeFunctionExpression(scope, setterName, paramList, body, innerScope);
   return new PropertyAssignment(name.ToString(), setter, null);
 }
Пример #30
0
 public Clause(ILiteral head) : this()
 {
     Head = head;
 }
Пример #31
0
 public Func<bool> Call(ILiteral predicate, params IReferenceLiteral[] arguments)
 {
     return () => false;
 }
Пример #32
0
 public void OnlyEnforceIf(ILiteral lit)
 {
     constraint_.EnforcementLiteral.Add(lit.GetIndex());
 }
Пример #33
0
 public bool HasVariable(ILiteral name)
 {
     return(_usedVariables.Contains(_indexForVariable[name]));
 }
Пример #34
0
        public IntervalVar NewOptionalIntervalVar <S, D, E>(S start, D duration, E end, ILiteral is_present, string name)
        {
            int i = is_present.GetIndex();

            return(new IntervalVar(model_, GetOrCreateIndex(start), GetOrCreateIndex(duration), GetOrCreateIndex(end),
                                   i, name));
        }
Пример #35
0
 /// <summary>
 /// Returns a clause indicating that a literal is unconditionally true
 /// </summary>
 public static IClause Always(ILiteral always)
 {
     return(If().Then(always));
 }
Пример #36
0
 static void Main()
 {
     CpModel  model = new CpModel();
     IntVar   x     = model.NewBoolVar("x");
     ILiteral not_x = x.Not();
 }
Пример #37
0
 public bool Equals(ILiteral other)
 {
     return(Equals(other as TermAssignment));
 }
Пример #38
0
        public IntervalVar NewOptionalIntervalVar <S, D, E>(S start, D duration, E end, ILiteral is_present, string name)
        {
            LinearExpr startExpr    = GetLinearExpr(start);
            LinearExpr durationExpr = GetLinearExpr(duration);
            LinearExpr endExpr      = GetLinearExpr(end);

            Add(startExpr + durationExpr == endExpr).OnlyEnforceIf(is_present);

            LinearExpressionProto startProto    = GetLinearExpressionProto(startExpr);
            LinearExpressionProto durationProto = GetLinearExpressionProto(durationExpr);
            LinearExpressionProto endProto      = GetLinearExpressionProto(endExpr);

            return(new IntervalVar(model_, startProto, durationProto, endProto, is_present.GetIndex(), name));
        }
Пример #39
0
 /// <exception cref="IOException"></exception>
 /// <exception cref="ProtocolException"></exception>
 private void literal(ILiteral b, Protocol p)
 {
     b.WriteTo(startLiteral(p, b.Size));
 }
Пример #40
0
        public IntervalVar NewOptionalFixedSizeIntervalVar <S>(S start, long duration, ILiteral is_present, string name)
        {
            LinearExpr startExpr    = GetLinearExpr(start);
            LinearExpr durationExpr = GetLinearExpr(duration);
            LinearExpr endExpr      = LinearExpr.Sum(new LinearExpr[] { startExpr, durationExpr });

            LinearExpressionProto startProto    = GetLinearExpressionProto(startExpr);
            LinearExpressionProto durationProto = GetLinearExpressionProto(durationExpr);
            LinearExpressionProto endProto      = GetLinearExpressionProto(endExpr);

            return(new IntervalVar(model_, startProto, durationProto, endProto, is_present.GetIndex(), name));
        }
Пример #41
0
        public bool UnifyVariable(ILiteral variable)
        {
            // This variable becomes used
            _usedVariables.Add(_indexForVariable[variable]);

            if (!_writeMode)
            {
                // Just read the value of the variable
                _addressForName[variable].SetTo(_structurePtr);
            }
            else
            {
                // Write the value of the variable
                _addressForName[variable].SetTo(_lastArgument);
                _lastArgument = _lastArgument.NextArgument;
            }

            _structurePtr = _structurePtr.NextArgument;

            return true;
        }
Пример #42
0
 public void AddAssumption(ILiteral lit)
 {
     model_.Assumptions.Add(lit.GetIndex());
 }
Пример #43
0
 public EmptyBinding(ILiteral result)
 {
     Result = result;
 }
Пример #44
0
 /// <summary>
 /// Constructs an instance.
 /// </summary>
 /// <param name="arrayLit">literal describing the referenced array</param>
 /// <param name="array">array instance</param>
 public FixedArrayRef(ILiteral arrayLit, Array array)
 {
     ArrayLit = arrayLit;
     ArrayObj = array;
 }
Пример #45
0
 public IPropertyAssignment MakePropertyAssignment(ILiteral name, IExpression expression)
 {
   // TODO: Is calling ToString() adequate here?
   return new PropertyAssignment(((Literal)name).ToString(), (Expression)expression);
 }
Пример #46
0
        /// <summary>
        /// Adds a new argument to this object
        /// </summary>
        public void AddArgument(ILiteral argument)
        {
            // Get the assignments for this argument
            var assignments = argument.Flatten().ToArray();

            // The first assignment defines the argument value, and the rest are just other variables
            var rootAssignment = assignments[0];
            var variableAssignments = assignments.Skip(1);

            // If the root assignment is a variable, use a variable argument assignment instead
            if (rootAssignment.Value.UnificationKey == null)
            {
                var variableRoot = rootAssignment;
                variableAssignments = variableAssignments.Concat(new[] { variableRoot });
                rootAssignment = new ArgumentAssignment(new Variable(), variableRoot.Variable);
            }

            // Store the list of other assignments
            _arguments.Add(rootAssignment);
            _otherAssignments.AddRange(variableAssignments);
        }
Пример #47
0
 public object EvalLiteral(ILiteral lit)
 {
     throw new NotImplementedException();
 }
Пример #48
0
        public bool UnifyVariable(ILiteral variable)
        {
            var variableIndex = _bindingForVariable[variable];
            _usedVariables.Add(variableIndex);

            _program.Write(Operation.UnifyVariable, variableIndex);
            return true;
        }
Пример #49
0
 /// <summary>
 /// Constructs an instance.
 /// </summary>
 /// <param name="arrayLit">literal describing the referenced array</param>
 /// <param name="array">array instance</param>
 /// <param name="indices">constant indices</param>
 public FixedArrayRef(ILiteral arrayLit, Array array, long[] indices)
 {
     ArrayLit = arrayLit;
     ArrayObj = array;
     Indices = indices;
 }
Пример #50
0
 static LiteralConversion FromLiteral(byte[] dest, ILiteral literal)
 {
     return(literal is INumberLiteral numberLiteral?FromNumberLiteral(dest, numberLiteral) : LiteralConversion.Failed);
 }
Пример #51
0
        public bool PutValue(ILiteral variable1, ILiteral variable2)
        {
            _addressForName[variable2].SetTo(_addressForName[variable1]);

            return(true);
        }
Пример #52
0
 public IntVar NewOptionalEnumeratedIntVar(
     IEnumerable <long> bounds, ILiteral is_present, string name)
 {
     return(new IntVar(model_, bounds, is_present.GetIndex(), name));
 }
Пример #53
0
 public bool HasVariable(ILiteral variable)
 {
     var variableIndex = _bindingForVariable[variable];
     return _usedVariables.Contains(variableIndex);
 }
Пример #54
0
 public IntVar NewOptionalConstant(
     long value, ILiteral is_present, string name)
 {
     long[] bounds = { value, value };
     return(new IntVar(model_, bounds, is_present.GetIndex(), name));
 }
Пример #55
0
 public void BindVariable(int index, ILiteral variable)
 {
     _bindingForVariable[variable] = index;
 }
Пример #56
0
    static void RankTasks(CpModel model, IntVar[] starts, ILiteral[] presences, IntVar[] ranks)
    {
        int num_tasks = starts.Length;

        // Creates precedence variables between pairs of intervals.
        ILiteral[,] precedences = new ILiteral[num_tasks, num_tasks];
        for (int i = 0; i < num_tasks; ++i)
        {
            for (int j = 0; j < num_tasks; ++j)
            {
                if (i == j)
                {
                    precedences[i, i] = presences[i];
                }
                else
                {
                    IntVar prec = model.NewBoolVar(String.Format("{0} before {1}", i, j));
                    precedences[i, j] = prec;
                    model.Add(starts[i] < starts[j]).OnlyEnforceIf(prec);
                }
            }
        }

        // Treats optional intervals.
        for (int i = 0; i < num_tasks - 1; ++i)
        {
            for (int j = i + 1; j < num_tasks; ++j)
            {
                List <ILiteral> tmp_array = new List <ILiteral>();
                tmp_array.Add(precedences[i, j]);
                tmp_array.Add(precedences[j, i]);
                tmp_array.Add(presences[i].Not());
                // Makes sure that if i is not performed, all precedences are false.
                model.AddImplication(presences[i].Not(), precedences[i, j].Not());
                model.AddImplication(presences[i].Not(), precedences[j, i].Not());
                tmp_array.Add(presences[j].Not());
                // Makes sure that if j is not performed, all precedences are false.
                model.AddImplication(presences[j].Not(), precedences[i, j].Not());
                model.AddImplication(presences[j].Not(), precedences[j, i].Not());
                // The following bool_or will enforce that for any two intervals:
                //    i precedes j or j precedes i or at least one interval is not
                //        performed.
                model.AddBoolOr(tmp_array);
                // Redundant constraint: it propagates early that at most one precedence
                // is true.
                model.AddImplication(precedences[i, j], precedences[j, i].Not());
                model.AddImplication(precedences[j, i], precedences[i, j].Not());
            }
        }

        // Links precedences and ranks.
        for (int i = 0; i < num_tasks; ++i)
        {
            IntVar[] tmp_array = new IntVar[num_tasks];
            for (int j = 0; j < num_tasks; ++j)
            {
                tmp_array[j] = (IntVar)precedences[j, i];
            }
            model.Add(ranks[i] == LinearExpr.Sum(tmp_array) - 1);
        }
    }
Пример #57
0
    static void Main()
    {
        CpModel model = new CpModel();
        // Three weeks.
        int horizon   = 100;
        int num_tasks = 4;

        IntVar[]      starts    = new IntVar[num_tasks];
        IntVar[]      ends      = new IntVar[num_tasks];
        IntervalVar[] intervals = new IntervalVar[num_tasks];
        ILiteral[]    presences = new ILiteral[num_tasks];
        IntVar[]      ranks     = new IntVar[num_tasks];

        IntVar true_var = model.NewConstant(1);

        // Creates intervals, half of them are optional.
        for (int t = 0; t < num_tasks; ++t)
        {
            starts[t] = model.NewIntVar(0, horizon, String.Format("start_{0}", t));
            int duration = t + 1;
            ends[t] = model.NewIntVar(0, horizon, String.Format("end_{0}", t));
            if (t < num_tasks / 2)
            {
                intervals[t] = model.NewIntervalVar(starts[t], duration, ends[t], String.Format("interval_{0}", t));
                presences[t] = true_var;
            }
            else
            {
                presences[t] = model.NewBoolVar(String.Format("presence_{0}", t));
                intervals[t] = model.NewOptionalIntervalVar(starts[t], duration, ends[t], presences[t],
                                                            String.Format("o_interval_{0}", t));
            }

            // Ranks = -1 if and only if the tasks is not performed.
            ranks[t] = model.NewIntVar(-1, num_tasks - 1, String.Format("rank_{0}", t));
        }

        // Adds NoOverlap constraint.
        model.AddNoOverlap(intervals);

        // Adds ranking constraint.
        RankTasks(model, starts, presences, ranks);

        // Adds a constraint on ranks.
        model.Add(ranks[0] < ranks[1]);

        // Creates makespan variable.
        IntVar makespan = model.NewIntVar(0, horizon, "makespan");

        for (int t = 0; t < num_tasks; ++t)
        {
            model.Add(ends[t] <= makespan).OnlyEnforceIf(presences[t]);
        }
        // Minimizes makespan - fixed gain per tasks performed.
        // As the fixed cost is less that the duration of the last interval,
        // the solver will not perform the last interval.
        IntVar[] presences_as_int_vars = new IntVar[num_tasks];
        for (int t = 0; t < num_tasks; ++t)
        {
            presences_as_int_vars[t] = (IntVar)presences[t];
        }
        model.Minimize(2 * makespan - 7 * LinearExpr.Sum(presences_as_int_vars));

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

        if (status == CpSolverStatus.Optimal)
        {
            Console.WriteLine(String.Format("Optimal cost: {0}", solver.ObjectiveValue));
            Console.WriteLine(String.Format("Makespan: {0}", solver.Value(makespan)));
            for (int t = 0; t < num_tasks; ++t)
            {
                if (solver.BooleanValue(presences[t]))
                {
                    Console.WriteLine(String.Format("Task {0} starts at {1} with rank {2}", t, solver.Value(starts[t]),
                                                    solver.Value(ranks[t])));
                }
                else
                {
                    Console.WriteLine(
                        String.Format("Task {0} in not performed and ranked at {1}", t, solver.Value(ranks[t])));
                }
            }
        }
        else
        {
            Console.WriteLine(String.Format("Solver exited with nonoptimal status: {0}", status));
        }
    }
Пример #58
0
 public Container(string parsedString, ILiteral value, PositionInText position)
     : base(position)
 {
     this.Value        = value;
     this.parsedString = parsedString;
 }
Пример #59
0
 public IntVar NewOptionalIntVar(
     long lb, long ub, ILiteral is_present, string name)
 {
     long[] bounds = { lb, ub };
     return(new IntVar(model_, bounds, is_present.GetIndex(), name));
 }
Пример #60
0
 /// <summary>
 /// Retrieves the storage location for the specified variable
 /// </summary>
 public IReferenceLiteral GetVariableLocation(ILiteral name)
 {
     return(_addressForName[name]);
 }