Ejemplo n.º 1
0
        protected override DevicePlanNode InternalPrepare(Schema.DevicePlan plan, PlanNode planNode)
        {
            // return a DevicePlanNode appropriate for execution of the given node
            TableNode tableNode = planNode as TableNode;

            if (tableNode != null)
            {
                var fhirTableNode = new FHIRDeviceTableNode(tableNode);
                fhirTableNode.Prepare(plan);
                if (plan.IsSupported)
                {
                    return(fhirTableNode);
                }

                return(null);
            }

            CreateTableNode createTableNode = planNode as CreateTableNode;

            if (createTableNode != null)
            {
                var fhirCreateTableNode = new FHIRCreateTableNode(createTableNode);
                return(fhirCreateTableNode);
            }

            DropTableNode dropTableNode = planNode as DropTableNode;

            if (dropTableNode != null)
            {
                var fhirDropTableNode = new FHIRDropTableNode(dropTableNode);
                return(fhirDropTableNode);
            }

            return(null);
        }
Ejemplo n.º 2
0
        protected override object InternalExecute(Program program, PlanNode planNode)
        {
            if (planNode.DeviceNode == null)
            {
                throw new DeviceException(DeviceException.Codes.UnpreparedDevicePlan, ErrorSeverity.System);
            }

            var fhirTableNode = planNode.DeviceNode as FHIRDeviceTableNode;

            if (fhirTableNode != null)
            {
                var fhirTable = new FHIRTable(this, program, fhirTableNode);
                fhirTable.Open();
                return(fhirTable);
            }

            var fhirCreateTableNode = planNode.DeviceNode as FHIRCreateTableNode;

            if (fhirCreateTableNode != null)
            {
                return(null);                // TODO: Throw an error if reconilication is not none...
            }

            var fhirDropTableNode = planNode.DeviceNode as FHIRDropTableNode;

            if (fhirDropTableNode != null)
            {
                return(null);                // TODO: Throw an error if reconciliation is not none...
            }

            return(base.InternalExecute(program, planNode));
        }
Ejemplo n.º 3
0
        // parse expression inside "(...)" or base class for Filter
        private PlanNode parseAtom()
        {
            if (nextTokenIs("("))
            {
                tokens.Pop();
                PlanNode node = parseOr();
                if (!nextTokenIs(")"))
                {
                    throw new Exception("Unmatched parenthesis");
                }
                tokens.Pop();
                return(node);
            }
            if (tokens.Count == 0)
            {
                throw new Exception("Unexpected end of input stream");
            }
            if (!tokens.Peek().StartsWith("-"))
            {
                throw new Exception("Unexpected token " + tokens.Peek());
            }
            // 这个name就是参数名,例如-type的"type",-size的"size"
            String name = tokens.Pop().Substring(1);
            // 在registry中找到与参数名对应的parser
            ParserBase parser = optionParserRegistry.GetValueOrDefault(name);

            if (parser == null)
            {
                throw new Exception("Unrecognized option " + name);
            }
            // Parser各自的parse()方法用于parse参数的arguments
            // 例如 -size +1M,那么"size"所对应的parser应当知道如何parse"+1M"
            return(parser.parse(tokens));
        }
Ejemplo n.º 4
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject Token = JObject.Load(reader);

            if (!Token.TryGetValue("@type", StringComparison.OrdinalIgnoreCase, out JToken TypeToken))
            {
                throw new InvalidOperationException("Invalid presto query plan node object.");
            }

            Type ActualType = PlanNode.GetType(TypeToken.ToObject <PlanNodeType>(serializer));

            if (existingValue == null || existingValue.GetType() != ActualType)
            {
                // Don't use this approach, since there are no default constructors
                // JsonContract Contract = serializer.ContractResolver.ResolveContract(ActualType);
                // existingValue = Contract.DefaultCreator();
                return(Token.ToObject(ActualType, serializer));
            }
            else
            {
                using (JsonReader DerivedTypeReader = Token.CreateReader())
                {
                    serializer.Populate(DerivedTypeReader, existingValue);
                }

                return(existingValue);
            }
        }
Ejemplo n.º 5
0
        public override Statement Translate(DevicePlan ADevicePlan, PlanNode APlanNode)
        {
            SQLDevicePlan LDevicePlan = (SQLDevicePlan)ADevicePlan;

            return
                (new CaseExpression
                 (
                     new CaseItemExpression[]
            {
                new CaseItemExpression
                (
                    new BinaryExpression
                    (
                        new CallExpression("UCase", new Expression[] { LDevicePlan.Device.TranslateExpression(LDevicePlan, APlanNode.Nodes[0], false) }),
                        "iEqual",
                        new CallExpression("UCase", new Expression[] { LDevicePlan.Device.TranslateExpression(LDevicePlan, APlanNode.Nodes[1], false) })
                    ),
                    new ValueExpression(0)
                ),
                new CaseItemExpression
                (
                    new BinaryExpression
                    (
                        new CallExpression("UCase", new Expression[] { LDevicePlan.Device.TranslateExpression(LDevicePlan, APlanNode.Nodes[0], false) }),
                        "iLess",
                        new CallExpression("UCase", new Expression[] { LDevicePlan.Device.TranslateExpression(LDevicePlan, APlanNode.Nodes[1], false) })
                    ),
                    new ValueExpression(-1)
                )
            },
                     new CaseElseExpression(new ValueExpression(1))
                 ));
        }
Ejemplo n.º 6
0
        private bool ShouldBreak(ServerProcess process, PlanNode node)
        {
            if (_disposed)
            {
                return(false);
            }

            if (process.ShouldBreak())
            {
                return(true);
            }

            if (_breakpoints.Count > 0)
            {
                DebugLocator currentLocation = process.ExecutingProgram.GetCurrentLocation();

                // Determine whether or not a breakpoint has been hit
                for (int index = 0; index < _breakpoints.Count; index++)
                {
                    Breakpoint breakpoint = _breakpoints[index];
                    if
                    (
                        (breakpoint.Locator == currentLocation.Locator) &&
                        (breakpoint.Line == currentLocation.Line) &&
                        ((breakpoint.LinePos == -1) || (breakpoint.LinePos == currentLocation.LinePos))
                    )
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 7
0
        protected override DevicePlanNode InternalPrepare(DevicePlan devicePlan, PlanNode planNode)
        {
            CatalogDevicePlan localDevicePlan = (CatalogDevicePlan)devicePlan;

            localDevicePlan.IsSupported = true;
            return(base.InternalPrepare(devicePlan, planNode));
        }
Ejemplo n.º 8
0
        //public SQLTimeSpanDays(Operator AOperator, D4.ClassDefinition AClassDefinition) : base(AOperator, AClassDefinition){}
        //public SQLTimeSpanDays(Operator AOperator, D4.ClassDefinition AClassDefinition, bool AIsSystem) : base(AOperator, AClassDefinition, AIsSystem){}

        public override Statement Translate(DevicePlan devicePlan, PlanNode planNode)
        {
            SQLDevicePlan localDevicePlan = (SQLDevicePlan)devicePlan;
            Expression    expression      = localDevicePlan.Device.TranslateExpression(localDevicePlan, planNode.Nodes[0], false);

            return(new BinaryExpression(expression, "iMultiplication", new ValueExpression(864000000000m, TokenType.Decimal)));
        }
Ejemplo n.º 9
0
        //public SQLTimeSpanReadSeconds(Operator AOperator, D4.ClassDefinition AClassDefinition) : base(AOperator, AClassDefinition){}
        //public SQLTimeSpanReadSeconds(Operator AOperator, D4.ClassDefinition AClassDefinition, bool AIsSystem) : base(AOperator, AClassDefinition, AIsSystem){}

        public override Statement Translate(DevicePlan devicePlan, PlanNode planNode)
        {
            SQLDevicePlan localDevicePlan = (SQLDevicePlan)devicePlan;
            Expression    expression      = localDevicePlan.Device.TranslateExpression(localDevicePlan, planNode.Nodes[0], false);

            return(new BinaryExpression(expression, "iDivision", new ValueExpression(10000000, TokenType.Integer)));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Collects all and or or clauses in the given node.
        /// </summary>
        /// <param name="node">The node from which the clauses will be collected.</param>
        /// <param name="instruction">The instruction, and or or, to be collected.</param>
        /// <returns>A list of clauses of the given instruction.</returns>
        /// <remarks>
        /// If the given node is a binary operator of the given instruction, the left and right operands to
        /// the node will be collected, recursively. Otherwise, the node is returned as a clause.
        /// </remarks>
        public static IEnumerable <PlanNode> CollectClauses(PlanNode node, string instruction)
        {
            var clauses = new List <PlanNode>();

            CollectClauses(node, instruction, clauses);
            return(clauses);
        }
Ejemplo n.º 11
0
        public PlanFragment(
            PlanFragmentId id,
            PlanNode root,
            IDictionary <string, string> symbols,
            PartitioningHandle partitioning,
            IEnumerable <PlanNodeId> partitionedSources,
            PartitioningScheme partitioningScheme,
            PipelineExecutionStrategy pipelineExecutionStrategy
            )
        {
            this.Id                        = id ?? throw new ArgumentNullException("id");
            this.Root                      = root ?? throw new ArgumentNullException("root");
            this.Symbols                   = symbols ?? throw new ArgumentNullException("symbols");
            this.Partitioning              = partitioning ?? throw new ArgumentNullException("partitioning");
            this.PartitionedSources        = partitionedSources ?? throw new ArgumentNullException("partitionedSources");
            this.PipelineExecutionStrategy = pipelineExecutionStrategy;
            this.PartitioningScheme        = partitioningScheme ?? throw new ArgumentNullException("partitioningScheme");

            ParameterCheck.Check(this.PartitionedSources.Distinct().Count() == this.PartitionedSources.Count(), "PartitionedSources contains duplicates.");

            this.Types = this.PartitioningScheme.OutputLayout.Select(x => x.ToString());
            // Materialize this during construction
            this.PartionedSourceNodes = new HashSet <PlanNode>(FindSources(this.Root, this.PartitionedSources));
            this.RemoteSourceNodes    = FindRemoteSourceNodes(this.Root).ToList();
        }
Ejemplo n.º 12
0
 //build tree and track the leastcostleaf node;
 public bool BuildTree(PlanNode parent, HashSet<Action> actionList, Dictionary<string, object> goalState, PlanNode leastCostLeaf)
 {
     bool hasPath = false;
     foreach (Action a in actionList) {
         if (AreConditionsInState (a.preconditions, parent.currentState)) {
             Dictionary<string, object> newState = CreateStateWithEffects (a.effects, parent.currentState);
             PlanNode newNode = new PlanNode (parent, parent.totalCost + a.cost, newState, a);
             if (AreConditionsInState (goalState, newState)) {
                 if (leastCostLeaf == null) {
                     leastCostLeaf = newNode;
                 } else if (newNode.totalCost < leastCostLeaf.totalCost) {
                     leastCostLeaf = newNode;
                 }
                 hasPath = true;
             } else {
                 //remove the current action from list of available actions and build tree based on remaining actions
                 HashSet<Action> actionsMinusOne = new HashSet<Action> (actionList);
                 actionsMinusOne.Remove (a);
                 //if any path was found, set to true
                 hasPath = hasPath || BuildTree (newNode, actionsMinusOne, goalState, leastCostLeaf);
             }
         }
     }
     return hasPath;
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Used to execute arbitrary plan nodes at compile-time.
        /// </summary>
        public object ExecuteNode(PlanNode node)
        {
            var program = new Program(_serverProcess);

            program.Code = node;
            return(program.Execute(null));
        }
Ejemplo n.º 14
0
        //public SASRetrieve(Operator AOperator, D4.ClassDefinition AClassDefinition) : base(AOperator, AClassDefinition){}
        //public SASRetrieve(Operator AOperator, D4.ClassDefinition AClassDefinition, bool AIsSystem) : base(AOperator, AClassDefinition, AIsSystem){}

        public override Statement Translate(DevicePlan ADevicePlan, PlanNode APlanNode)
        {
            SQLDevicePlan LDevicePlan = (SQLDevicePlan)ADevicePlan;
            TableVar      LTableVar   = ((TableVarNode)APlanNode).TableVar;

            if (LTableVar is BaseTableVar)
            {
                SQLRangeVar LRangeVar = new SQLRangeVar(LDevicePlan.GetNextTableAlias());
                foreach (Schema.TableVarColumn LColumn in LTableVar.Columns)
                {
                    LRangeVar.Columns.Add(new SQLRangeVarColumn(LColumn, LRangeVar.Name, LDevicePlan.Device.ToSQLIdentifier(LColumn), LDevicePlan.Device.ToSQLIdentifier(LColumn.Name)));
                }
                LDevicePlan.CurrentQueryContext().RangeVars.Add(LRangeVar);
                SelectExpression LSelectExpression = new SelectExpression();
                LSelectExpression.FromClause = new AlgebraicFromClause(new TableSpecifier(new TableExpression(D4.MetaData.GetTag(LTableVar.MetaData, "Storage.Schema", LDevicePlan.Device.Schema), LDevicePlan.Device.ToSQLIdentifier(LTableVar)), LRangeVar.Name));
                //LSelectExpression.FromClause = new CalculusFromClause(new TableSpecifier(new TableExpression(D4.MetaData.GetTag(LTableVar.MetaData, "Storage.Schema", LDevicePlan.Device.Schema), LDevicePlan.Device.ToSQLIdentifier(LTableVar)), LRangeVar.Name));
                LSelectExpression.SelectClause = new SelectClause();
                foreach (TableVarColumn LColumn in LTableVar.Columns)
                {
                    LSelectExpression.SelectClause.Columns.Add(LDevicePlan.GetRangeVarColumn(LColumn.Name, true).GetColumnExpression());
                }

                LSelectExpression.SelectClause.Distinct =
                    (LTableVar.Keys.Count == 1) &&
                    Convert.ToBoolean(D4.MetaData.GetTag(LTableVar.Keys[0].MetaData, "Storage.IsImposedKey", "false"));

                return(LSelectExpression);
            }
            else
            {
                return(LDevicePlan.Device.TranslateExpression(LDevicePlan, APlanNode.Nodes[0], false));
            }
        }
Ejemplo n.º 15
0
        public override Statement Translate(DevicePlan ADevicePlan, PlanNode APlanNode)
        {
            SQLDevicePlan LDevicePlan = (SQLDevicePlan)ADevicePlan;

            return
                (new CaseExpression
                 (
                     new CaseItemExpression[]
            {
                new CaseItemExpression
                (
                    new BinaryExpression
                    (
                        LDevicePlan.Device.TranslateExpression(LDevicePlan, APlanNode.Nodes[0], false),
                        "iEqual",
                        new ValueExpression(0, TokenType.Integer)
                    ),
                    new ValueExpression("false", TokenType.String)
                )
            },
                     new CaseElseExpression
                     (
                         new ValueExpression("true", TokenType.String)
                     )
                 ));
        }
Ejemplo n.º 16
0
        //public SQLTimeSpanReadMinutes(Operator AOperator, D4.ClassDefinition AClassDefinition) : base(AOperator, AClassDefinition){}
        //public SQLTimeSpanReadMinutes(Operator AOperator, D4.ClassDefinition AClassDefinition, bool AIsSystem) : base(AOperator, AClassDefinition, AIsSystem){}

        public override Statement Translate(DevicePlan devicePlan, PlanNode planNode)
        {
            SQLDevicePlan localDevicePlan = (SQLDevicePlan)devicePlan;
            Expression    expression      = localDevicePlan.Device.TranslateExpression(localDevicePlan, planNode.Nodes[0], false);
            Expression    Minutes         = new BinaryExpression(expression, "iDivision", new ValueExpression(600000000m, TokenType.Decimal));

            return(Minutes);
        }
Ejemplo n.º 17
0
        private static IPlanNode GetNode(IPlanNode old, double fuelOnBoard, double grossWt)
        {
            var node = PlanNode.Copy(old);

            node.FuelOnBoard = fuelOnBoard;
            node.GrossWt     = grossWt;
            return(node);
        }
Ejemplo n.º 18
0
        //public SQLTimeSpanAddTicks(Operator AOperator, D4.ClassDefinition AClassDefinition) : base(AOperator, AClassDefinition){}
        //public SQLTimeSpanAddTicks(Operator AOperator, D4.ClassDefinition AClassDefinition, bool AIsSystem) : base(AOperator, AClassDefinition, AIsSystem){}

        public override Statement Translate(DevicePlan devicePlan, PlanNode planNode)
        {
            SQLDevicePlan localDevicePlan = (SQLDevicePlan)devicePlan;
            Expression    expression1     = localDevicePlan.Device.TranslateExpression(localDevicePlan, planNode.Nodes[0], false);
            Expression    expression2     = localDevicePlan.Device.TranslateExpression(localDevicePlan, planNode.Nodes[1], false);

            return(new BinaryExpression(expression1, "iAddition", expression2));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Used to evaluate literal arguments at compile-time. The given node must be literal, or an exception is raised.
        /// </summary>
        public object EvaluateLiteralArgument(PlanNode node, string argumentName)
        {
            if (!node.IsLiteral)
            {
                throw new CompilerException(CompilerException.Codes.LiteralArgumentRequired, CompilerErrorLevel.NonFatal, argumentName);
            }

            return(ExecuteNode(node));
        }
Ejemplo n.º 20
0
        protected int CompareKeyValues(object keyValue1, object keyValue2, PlanNode compareNode)
        {
            Program.Stack.Push(keyValue1);
            Program.Stack.Push(keyValue2);
            int result = (int)compareNode.Execute(Program);

            Program.Stack.Pop();
            Program.Stack.Pop();
            return(result);
        }
Ejemplo n.º 21
0
        //public SQLTimeSpanTime2Operands(Operator AOperator, D4.ClassDefinition AClassDefinition) : base(AOperator, AClassDefinition){}
        //public SQLTimeSpanTime2Operands(Operator AOperator, D4.ClassDefinition AClassDefinition, bool AIsSystem) : base(AOperator, AClassDefinition, AIsSystem){}

        public override Statement Translate(DevicePlan devicePlan, PlanNode planNode)
        {
            SQLDevicePlan localDevicePlan = (SQLDevicePlan)devicePlan;
            Expression    expression1     = localDevicePlan.Device.TranslateExpression(localDevicePlan, planNode.Nodes[0], false);
            Expression    expression2     = localDevicePlan.Device.TranslateExpression(localDevicePlan, planNode.Nodes[1], false);
            Expression    First           = new BinaryExpression(expression1, "iMultiplication", new ValueExpression(36000000000m, TokenType.Decimal));
            Expression    Second          = new BinaryExpression(expression2, "iMultiplication", new ValueExpression(600000000m, TokenType.Decimal));

            return(new BinaryExpression(First, "iAddition", Second));
        }
 public override void PreOrderVisit(Plan plan, PlanNode node)
 {
     // If the node is a restriction
     // Convert the condition to DNF
     // Collect Ors
     // If there are any Ors, replace the entire restriction with the Union of each individual Or
     // Collect Ands
     // If there are any non-sargable conditions
     // Add an additional restriction with the non-sargable conditions
 }
Ejemplo n.º 23
0
        //private PlanNode chunk;

        public override void PreOrderVisit(Plan plan, PlanNode node)
        {
            //if (chunk == null)
            //{
            //	node.DetermineDevice(plan);
            //	if (node.DeviceSupported)
            //	{
            //		chunk = node;
            //	}
            //}
        }
Ejemplo n.º 24
0
 public void SetContext(PlanNode planNode)
 {
     if (planNode.Line > -1)
     {
         _line    = planNode.Line;
         _linePos = planNode.LinePos;
     }
     else
     {
         _context = planNode.SafeEmitStatementAsString();
     }
 }
Ejemplo n.º 25
0
 private void EnsurePrepared(PlanNode planNode)
 {
     // The determine device visitor clears prepared device nodes to reduce memory footprint
     // (The resulting optimization is significant, on the order of 100MB for a large Dataphor application)
     // However, since there are cases where subnodes are executed independently (e.g. during a default),
     // we need to check that the node to be executed is prepared and prepare it if necessary.
     if (planNode.DeviceNode == null)
     {
         _serverProcess.EnsureDeviceStarted(planNode.Device);
         planNode.Device.Prepare(Plan, planNode);
     }
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Converts the given node to an equivalent logical expression in disjunctive normal form.
        /// </summary>
        /// <param name="node">The input expression.</param>
        /// <returns>A plan node representing an equivalent logical expression in disjunctive normal form.</returns>
        /// <remarks>
        /// <para>
        /// NOTE: The runtime of this algorithm is known to be exponential in the number of elementary propositions involved in
        /// the input expression. There are known methods for improving this based on the notions of equisatisfiability, rather
        /// than pure equivalence, however, these methods would have to be reviewed for applicability to 3VL logic. The methods
        /// are described in the following references:
        /// </para>
        /// <para>
        /// Paul Jackson, Daniel Sheridan: Clause Form Conversions for Boolean Circuits. In: Holger H. Hoos, David G. Mitchell (Eds.): Theory and Applications of Satisfiability Testing, 7th International Conference, SAT 2004, Vancouver, BC, Canada, May 10–13, 2004, Revised Selected Papers. Lecture Notes in Computer Science 3542, Springer 2005, pp. 183–198
        /// G.S. Tseitin: On the complexity of derivation in propositional calculus. In: Slisenko, A.O. (ed.) Structures in Constructive Mathematics and Mathematical Logic, Part II, Seminars in Mathematics (translated from Russian), pp. 115–125. Steklov Mathematical Institute (1968)
        /// </para>
        /// </remarks>
        public static PlanNode DisjunctiveNormalize(Plan plan, PlanNode node)
        {
            node = DistributeNot(plan, node);

            var instructionNode = node as InstructionNodeBase;

            if (instructionNode != null && instructionNode.Operator != null)
            {
                switch (Schema.Object.Unqualify(instructionNode.Operator.OperatorName))
                {
                case Instructions.Or:
                    instructionNode.Nodes[0] = DisjunctiveNormalize(plan, instructionNode.Nodes[0]);
                    instructionNode.Nodes[1] = DisjunctiveNormalize(plan, instructionNode.Nodes[1]);
                    return(instructionNode);

                case Instructions.And:
                    var      left         = DisjunctiveNormalize(plan, instructionNode.Nodes[0]);
                    var      right        = DisjunctiveNormalize(plan, instructionNode.Nodes[1]);
                    var      leftClauses  = CollectClauses(left, Instructions.Or);
                    var      rightClauses = CollectClauses(right, Instructions.Or);
                    var      clausesUsed  = false;
                    PlanNode result       = null;
                    foreach (var leftClause in leftClauses)
                    {
                        foreach (var rightClause in rightClauses)
                        {
                            result =
                                Compiler.AppendNode
                                (
                                    plan,
                                    result,
                                    Instructions.Or,
                                    Compiler.AppendNode
                                    (
                                        plan,
                                        clausesUsed ? leftClause.Clone() : leftClause,
                                        Instructions.And,
                                        clausesUsed ? rightClause.Clone() : rightClause
                                    )
                                );

                            clausesUsed = true;
                        }
                    }

                    return(result);
                }
            }

            return(node);
        }
Ejemplo n.º 27
0
        public override PlanningResult GetPlan(DomainState startState, DomainState goalState, ActionSet actions)
        {
            Plan GetOptions(IPlanNode node) => RegressivePlanner.GetOptions(node, actions, startState);

            var start = new PlanNode(goalState, null, null, 0);

            var(path, graph) = FindPlan(start, startState.IsSuperstateOf, GetOptions);

            return(new PlanningResult
            {
                Plan = GetActions(path),
                SearchTree = graph
            });
        }
Ejemplo n.º 28
0
        private static void CollectClauses(PlanNode node, string instruction, List <PlanNode> clauses)
        {
            var instructionNode = node as InstructionNodeBase;

            if (instructionNode != null && instructionNode.Operator != null && Schema.Object.Unqualify(instructionNode.Operator.OperatorName) == instruction)
            {
                CollectClauses(instructionNode.Nodes[0], instruction, clauses);
                CollectClauses(instructionNode.Nodes[1], instruction, clauses);
            }
            else
            {
                clauses.Add(node);
            }
        }
Ejemplo n.º 29
0
        private static IEnumerable <RemoteSourceNode> FindRemoteSourceNodes(PlanNode node)
        {
            foreach (PlanNode Source in node.GetSources())
            {
                foreach (RemoteSourceNode Item in FindRemoteSourceNodes(Source))
                {
                    yield return(Item);
                }
            }

            if (node is RemoteSourceNode)
            {
                yield return((RemoteSourceNode)node);
            }
        }
Ejemplo n.º 30
0
        private IEnumerable <PlanNode> FindSources(PlanNode node, IEnumerable <PlanNodeId> nodeIds)
        {
            if (nodeIds.Contains(node.Id))
            {
                yield return(node);
            }

            foreach (PlanNode Source in node.GetSources())
            {
                foreach (PlanNode Item in FindSources(Source, nodeIds))
                {
                    yield return(Item);
                }
            }
        }
Ejemplo n.º 31
0
        protected (PlanNode, IDebugGraph) FindPlan(
            PlanNode start,
            Func <DomainState, bool> isTarget,
            Func <PlanNode, IEnumerable <PlanNode> > getOptions)
        {
            var visitedStates = new HashSet <DomainState>();
            var planQueue     = new PriorityQueue <PlanNode>();

            var debugGraph = _debuggingEnabled
                ? new DebugGraph()
                : null;

            planQueue.Enqueue(0, start);
            debugGraph?.AddNode(start);

            while (!planQueue.IsEmpty)
            {
                var currentNode  = planQueue.Dequeue();
                var currentState = currentNode.State;

                if (visitedStates.Contains(currentState))
                {
                    continue;
                }

                if (isTarget(currentState))
                {
                    return(currentNode, debugGraph);
                }

                visitedStates.Add(currentState);

                foreach (var planNode in getOptions(currentNode))
                {
                    planQueue.Enqueue(planNode.TotalCost, planNode);

                    debugGraph?.AddNode(planNode);
                    debugGraph?.AddEdge(planNode.Parent, planNode, planNode.SelectedAction);

                    if (_earlyExit && isTarget(planNode.State))
                    {
                        return(planNode, debugGraph);
                    }
                }
            }

            return(null, debugGraph);
        }
Ejemplo n.º 32
0
 public Queue<Action> Plan(HashSet<Action> allActions, Dictionary<string,object> currentState, Dictionary<string,object> goalState)
 {
     foreach (Action a in allActions) {
         a.Reset ();
     }
     HashSet<Action> availableActions = new HashSet<Action> ();
     foreach (Action a in allActions) {
         if (a.RequiresInRange ()) {
             //if it requires range and is in range
             if (a.CheckInRange ()) {
                 availableActions.Add (a);
             }
         } else {
             availableActions.Add (a);
         }
     }
     //check which actions can or cannot run according to their range
     List<PlanNode> leaves = new List<PlanNode> ();
     PlanNode leastCostLeaf = null;
     PlanNode first = new PlanNode (null, 0f, currentState, null);
     bool planAvailable = BuildTree (first, availableActions, goalState, leaves);
     foreach (PlanNode leaf in leaves) {
         if (leastCostLeaf == null) {
             leastCostLeaf = leaf;
         } else {
             if (leaf.totalCost < leastCostLeaf.totalCost) {
                 leastCostLeaf = leaf;
             }
         }
     }
     if (planAvailable) {
         LinkedList<Action> list = new LinkedList<Action> ();
         while (leastCostLeaf.action!=null) {
             list.AddFirst (leastCostLeaf.action);
             leastCostLeaf = leastCostLeaf.parent;
         }
         return new Queue<Action> (list);
     } else {
     //			Debug.Log ("no plan available currently");
         return null;
     }
 }
Ejemplo n.º 33
0
 //GOALSTATE: zombieAlive, false + dogAlive, true
 //pickuphealth, attackzombie
 public bool BuildTree(PlanNode parent, HashSet<Action> actionList, Dictionary<string, object> goalState, List<PlanNode> leaves)
 {
     bool hasPath = false;
     foreach (Action a in actionList) {
         if (AreConditionsInState (a.preconditions, parent.currentState)) {
             //attackzombie effects = dog loses health, zombie loses health
             Dictionary<string, object> newState = CreateStateWithEffects (a.effects, parent.currentState);
             PlanNode newNode = new PlanNode (parent, parent.totalCost + a.cost, newState, a);
             //newState: zombieAlive, false + dogAlive, true
             //goalState: zombieAlive, false + dogAlive, true
             if (AreConditionsInState (goalState, newState)) {
                 leaves.Add (newNode);
                 hasPath = true;
             } else {
                 HashSet<Action> actionsMinusOne = new HashSet<Action> (actionList);
                 actionsMinusOne.Remove (a); //this list only contains attackZombie now
                 hasPath = hasPath || BuildTree (newNode, actionsMinusOne, goalState, leaves);
             }
         }
     }
     return hasPath;
 }
Ejemplo n.º 34
0
 public PlanNode(PlanNode parent, float cost, Dictionary<string, object> state, Action a)
 {
     this.parent = parent;
     totalCost = cost;
     currentState = state;
     action = a;
 }
Ejemplo n.º 35
0
		public UsePlanNode(PlanNode bTree)
		{
	
		}