public MemoryStream WriteTaggedProblemNoState(Dictionary <string, List <Predicate> > dTags, IEnumerable <Predicate> lObserved,
                                                      Dictionary <string, double> dFunctionValues)
        {
            MemoryStream ms = new MemoryStream(1000);
            StreamWriter sw = new StreamWriter(ms);

            sw.WriteLine("(define (problem K" + Name + ")");
            sw.WriteLine("(:domain K" + Domain.Name + ")");
            sw.WriteLine("(:init"); //ff doesn't like the and (and");

            string sKP = "";

            if (Domain.TIME_STEPS > 0)
            {
                sw.WriteLine("(time0)");
            }
            foreach (KeyValuePair <string, double> f in dFunctionValues)
            {
                sw.WriteLine("(= " + f.Key + " " + f.Value + ")");
            }
            foreach (GroundedPredicate gp in lObserved)
            {
                //if (gp.Negation)
                //    continue;
                if (gp.Name == "Choice" || gp.Name == Domain.OPTION_PREDICATE)
                {
                    continue;
                }
                if (Domain.AlwaysKnown(gp) && Domain.AlwaysConstant(gp))
                {
                    sKP = "(" + gp.Name;
                    foreach (Constant c in gp.Constants)
                    {
                        sKP += " " + c.Name;
                    }
                    sw.WriteLine(sKP + ")");
                }
                else
                {
                    foreach (string sTag in dTags.Keys)
                    {
                        if (!gp.Negation)
                        {
                            Predicate pGiven = gp.GenerateGiven(sTag);
                            sw.WriteLine(pGiven);
                        }
                    }
                }
            }
            foreach (KeyValuePair <string, List <Predicate> > p in dTags)
            {
                foreach (GroundedPredicate gp in p.Value)
                {
                    if (gp.Negation)
                    {
                        continue;
                    }
                    if (gp.Name == "Choice")
                    {
                        continue;
                    }
                    if (!gp.Negation)
                    {
                        sw.WriteLine(gp.GenerateGiven(p.Key));
                    }
                    //sKP = GenerateKnowGivenLine(gp, p.Key, true);
                    //sw.WriteLine(sKP);
                }
            }

            //if (Problem.Domain.HasNonDeterministicActions())
            //    sw.WriteLine("(option opt0)");

            //if (SDRPlanner.SplitConditionalEffects)
            sw.WriteLine("(NotInAction)");

            sw.WriteLine(")");

            CompoundFormula cfGoal = new CompoundFormula("and");

            HashSet <Predicate> lGoalPredicates = new HashSet <Predicate>();

            Goal.GetAllPredicates(lGoalPredicates);


            for (int iTag = 0; iTag < dTags.Count; iTag++)
            {
                if (SDRPlanner.ConsiderStateNegations && iTag == dTags.Count - 1)
                {
                    break;//What is that?
                }
                string sTag = dTags.Keys.ElementAt(iTag);
                foreach (Predicate p in lGoalPredicates)
                {
                    if (!Domain.AlwaysKnown(p) || !Domain.AlwaysConstant(p))
                    {
                        cfGoal.AddOperand(p.GenerateGiven(sTag));
                    }
                }
            }

            if (SDRPlanner.ForceTagObservations)
            {
                foreach (string sTag1 in dTags.Keys)
                {
                    foreach (string sTag2 in dTags.Keys)
                    {
                        if (sTag1 != sTag2)
                        {
                            Predicate gpNot = Predicate.GenerateKNot(new Constant(Domain.TAG, sTag1), new Constant(Domain.TAG, sTag2));
                            cfGoal.AddOperand(gpNot);
                        }
                    }
                }
            }

            sw.WriteLine("(:goal " + cfGoal + ")");
            //sw.WriteLine("))");
            if (MetricStatement != null)
            {
                sw.WriteLine(MetricStatement);
            }
            sw.WriteLine(")");
            sw.Flush();

            return(ms);
        }
        public List <string> Plan()
        {
            bool bAllAgentsEqual = CheckAgentEquality();

            int i = 300;// countOfLandmarks;

            int[] statesNum = new int[agents.Count];
            for (int k = 0; k < statesNum.Length; k++)
            {
                statesNum[k] = 0;
            }


            PdbVertex rootVertex = new PdbVertex(statesNum, new List <Action>(), 0, 0, 0, null, null);

            rootVertex.publicState = new State((Problem)null);
            foreach (Agent agent in agents)
            {
                foreach (GroundedPredicate pgp in agent.GetPublicInitial())
                {
                    if (!rootVertex.publicState.Contains(pgp))
                    {
                        rootVertex.publicState.AddPredicate(pgp);
                    }
                }
            }
            //DateTime begin = DateTime.Now;

            int       count        = 0;
            PdbVertex curentVertex = null;
            DateTime  dtStart      = DateTime.Now;

            //for (; i < 1000; i++)
            {
                HashSet <int[]>     lVisited  = new HashSet <int[]>(new ComparerArray());
                HashSet <PdbVertex> lVisited2 = new HashSet <PdbVertex>();
                DateTime            begin     = DateTime.Now;
                List <PdbVertex>    queue     = new List <PdbVertex>();
                //PriorityQueue<PdbVertex, double> queue2 = new PriorityQueue<PdbVertex, double>(PdbVertex.ComparerDouble);
                //PriorityQueue<PdbVertex, double> queue2 = new PriorityQueue<PdbVertex, double>();
                //Heap heap = new Heap(1000000);
                //queue2.Insert(rootVertex, rootVertex.h);
                //heap.Insert(rootVertex);
                queue.Add(rootVertex);
                lVisited.Add(rootVertex.statesNubmber);
                // double priority = -1 * (rootVertex.h + (double)(rootVertex.g) / 100000 );

                //queue2.Enqueue(rootVertex, priority);
                int           temp  = 0;
                List <string> lplan = null;// new List<string>();
                bool          flag  = true;
                int           c     = 0;
                double        minh  = 99999999;
                while (queue.Count > 0)
                {
                    c++;
                    if (c % 1000 == 0)
                    {
                        //Console.Write("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bExpanded: " + c + ", open: " + queue.Count + ", h: " + curentVertex.h + ", T: " + (int)(DateTime.Now - dtStart).TotalSeconds);
                        Console.Write("\rExpanded: " + c + ", open: " + queue.Count + ", h: " + curentVertex.h + ", T: " + (int)(DateTime.Now - dtStart).TotalSeconds);
                        if (queue.Count > 200000)
                        {
                            return(null);

                            Console.WriteLine();
                            Console.WriteLine("Queue too large, breaking.");
                        }
                    }
                    flag = true;
                    //curentVertex = queue[0];
                    // List<PriorityQueueItem<PdbVertex,double>> v = queue2.ToList();
                    //curentVertex = queue2.Dequeue().Value;
                    temp++;
                    curentVertex = FindMin(queue);// queue[0];// heap.Remove();
                    // queue.Remove(curentVertex);
                    // queue.RemoveAt(0);
                    count++;
                    bool bDeadend = curentVertex.IsDeadEnd();
                    if (bDeadend)
                    {
                        continue;
                    }


                    //                    if (curentVertex.Parent != null && curentVertex.Parent.Parent != null && curentVertex.h == curentVertex.Parent.h && curentVertex.h == curentVertex.Parent.Parent.h)
                    //                        Console.WriteLine("stuck!");



                    // Program.messages += agents.Count;
                    int f = 0;
                    List <PdbVertex>          needUpDate     = new List <PdbVertex>();
                    HashSet <CompoundFormula> levelPotential = new HashSet <CompoundFormula>();
                    int  index = 1;
                    bool con   = false;
                    if (curentVertex.h == 0)
                    {
                        curentVertex.publicPredicateImplications = new List <HashSet <CompoundFormula> >();
                        PdbVertex tmp = curentVertex;
                        while (tmp != null)
                        {
                            curentVertex.publicPredicateImplications.Insert(0, tmp.canGetInParallel);
                            tmp = tmp.Parent;
                        }
                        string isGoal = curentVertex.IsGoal(out lplan);
                        if (isGoal.Equals("true"))
                        {
                            double time = ((double)((DateTime.Now.Subtract(begin)).Minutes)) * 60.0;
                            time += ((double)((DateTime.Now.Subtract(begin)).Seconds));
                            time += ((double)((DateTime.Now.Subtract(begin)).Milliseconds) / 1000);
                            //Console.WriteLine(time);
                            //Console.WriteLine(lplan.Count);
                            // Console.WriteLine(((double)((DateTime.Now.Subtract(begin)).Milliseconds) / 1000));
                            Program.times.Add(time);
                            Program.countActions.Add(lplan.Count);
                            Program.timeSum   += time;
                            Program.actionSum += lplan.Count;

                            /* foreach (Action act in curentVertex.lplan)
                             * {
                             *   sw.WriteLine(act.Name);
                             *   lplan.Add(act.Name);
                             * }
                             * sw.Close();*/
                            return(lplan);
                        }
                        if (!isGoal.Equals("false"))
                        {
                            //return null;
                        }
                    }

                    bool stop = false;
                    foreach (Agent agent in agents)
                    {
                        foreach (Action act in agent.publicActions)
                        {
                            f++;
                            Program.messages += agents.Count;
                            PdbVertex newVertex = curentVertex.Apply(agent.name, act);

                            bool bVisited = true;
                            if (newVertex != null)
                            {
                                if (bAllAgentsEqual)
                                {
                                    bVisited = lVisited2.Contains(newVertex);
                                }
                                else
                                {
                                    bVisited = lVisited.Contains(newVertex.statesNubmber);
                                }
                            }
                            if (!bVisited)
                            {
                                // newVertex.History = new List<string>(curentVertex.History);
                                // newVertex.History.Add(act.Name);

                                // newVertex.g += (double)index / 1000000;
                                queue.Add(newVertex);

                                if (minh > newVertex.h)
                                {
                                    minh = newVertex.h;
                                    //  if(minh==0)
                                    Console.WriteLine(minh);
                                    //  break;
                                }
                                if (newVertex.h < curentVertex.h)
                                {
                                    stop = true;
                                    break;
                                }
                                index++;

                                //queue2.Enqueue(newVertex, priority);
                                // needUpDate.Add(newVertex);
                                CompoundFormula effect = new CompoundFormula("and");
                                foreach (GroundedPredicate gp in act.HashEffects)
                                {
                                    if (agent.PublicPredicates.Contains(gp))
                                    {
                                        effect.AddOperand(gp);
                                    }
                                }
                                levelPotential.Add(effect);
                            }
                        }
                        if (stop)
                        {
                            break;
                        }
                    }
                    curentVertex.canGetInParallel = levelPotential;
                }
            }
            return(null);
        }
        public MemoryStream WriteTaggedProblem(Dictionary <string, List <Predicate> > dTags, IEnumerable <Predicate> lObserved,
                                               List <Predicate> lTrueState, Dictionary <string, double> dFunctionValues, bool bOnlyIdentifyStates)
        {
            MemoryStream msProblem = new MemoryStream();
            StreamWriter sw        = new StreamWriter(msProblem);

            sw.WriteLine("(define (problem K" + Name + ")");
            sw.WriteLine("(:domain K" + Domain.Name + ")");
            sw.WriteLine("(:init"); //ff doesn't like the and (and");

            string sKP = "", sP = "";

            if (Domain.TIME_STEPS > 0)
            {
                sw.WriteLine("(time0)");
            }
            if (SDRPlanner.SplitConditionalEffects)
            {
                sw.WriteLine("(NotInAction)\n");
            }
            foreach (KeyValuePair <string, double> f in dFunctionValues)
            {
                sw.WriteLine("(= " + f.Key + " " + f.Value + ")");
            }
            foreach (GroundedPredicate gp in lObserved)
            {
                if (gp.Name == "Choice")
                {
                    continue;
                }
                sKP = "(K" + gp.Name;
                sP  = "(" + gp.Name;
                foreach (Constant c in gp.Constants)
                {
                    sKP += " " + c.Name;
                    sP  += " " + c.Name;
                }
                if (gp.Negation)
                {
                    sKP += " " + Domain.FALSE_VALUE;
                }
                else
                {
                    sKP += " " + Domain.TRUE_VALUE;
                }
                if (!Domain.AlwaysKnown(gp))
                {
                    sw.WriteLine(sKP + ")");
                }
                if (!gp.Negation)
                {
                    sw.WriteLine(sP + ")");
                }
            }
            foreach (GroundedPredicate gp in lTrueState)
            {
                if (gp.Name == "Choice")
                {
                    continue;
                }
                if (!gp.Negation)
                {
                    sP = "(" + gp.Name;
                    foreach (Constant c in gp.Constants)
                    {
                        sP += " " + c.Name;
                    }
                    sw.WriteLine(sP + ")");
                }
            }
            foreach (KeyValuePair <string, List <Predicate> > p in dTags)
            {
                foreach (GroundedPredicate gp in p.Value)
                {
                    if (gp.Name == "Choice")
                    {
                        continue;
                    }
                    sKP = GenerateKnowGivenLine(gp, p.Key, false);
                    sw.WriteLine(sKP);
                }

                if (SDRPlanner.AddAllKnownToGiven)
                {
                    foreach (GroundedPredicate gp in lObserved)
                    {
                        if (gp.Name == "Choice")
                        {
                            continue;
                        }
                        if (!Domain.AlwaysKnown(gp))
                        {
                            sKP = GenerateKnowGivenLine(gp, p.Key, false);
                            sw.WriteLine(sKP);
                        }
                    }
                }
            }


            sw.WriteLine(")");
            CompoundFormula cfGoal = new CompoundFormula("and");

            cfGoal.AddOperand(Goal);
            HashSet <Predicate> lGoalPredicates = new HashSet <Predicate>();

            cfGoal.GetAllPredicates(lGoalPredicates);

            foreach (Predicate p in lGoalPredicates)
            {
                if (!Domain.AlwaysKnown(p))
                {
                    cfGoal.AddOperand(new KnowPredicate(p));
                }
            }


            sw.WriteLine("(:goal " + cfGoal + ")");
            //sw.WriteLine("))");
            if (MetricStatement != null)
            {
                sw.WriteLine(MetricStatement);
            }
            sw.WriteLine(")");
            sw.Flush();


            return(msProblem);
        }
        private void UpdateDependenciesIntoDomainsAndProblems(List <Agent> m_agents)
        {
            GroundedFunctionPredicate totalCostFunctionPredicate = GetTotalCostFunction();

            Domain  dJoined                      = new Domain("JoinedDomain", "");
            Problem pJoined                      = new Problem("JoinedProblem", dJoined);
            State   publicStartState             = new State(pJoined);
            HashSet <GroundedPredicate> allGoals = new HashSet <GroundedPredicate>();

            List <Action> allActions = new List <Action>();

            foreach (Agent agent in m_agents)
            {
                foreach (Action action in agent.m_actions)
                {
                    List <Dependency> dependenciesForAction = new List <Dependency>();
                    List <Predicate>  regularEffects        = new List <Predicate>();

                    foreach (Predicate p in action.HashEffects)
                    {
                        Dependency dependency = new Dependency(action, p);
                        if (mapDependencyToConstant.ContainsKey(dependency))
                        {
                            //Then this is a dependency dependent action, which means we need to duplicate it several times so that we have the action with the dependency revealed and without it
                            dependenciesForAction.Add(dependency);

                            /*
                             * Constant d = mapDependencyToConstant[dependency];
                             * GroundedPredicate revealedD = new GroundedPredicate("revealed");
                             * revealedD.AddConstant(d);
                             *
                             * CompoundFormula cfCondition = new CompoundFormula("when");
                             * cfCondition.AddOperand(revealedD); //condition
                             * cfCondition.AddOperand(p); //result = the predicate we want to reveal.
                             *
                             * editedEffects.AddOperand(cfCondition);
                             */
                        }
                        else
                        {
                            regularEffects.Add(p);
                            //editedEffects.AddOperand(p); //it is not a dependency, so just reveal it regularly...
                        }
                    }

                    List <List <Dependency> > allPermutations = GetAllCombos(dependenciesForAction);
                    foreach (List <Dependency> currentPermutation in allPermutations)
                    {
                        //foreach permutation, create a corresponding action
                        string          name                = action.Name;
                        CompoundFormula editedEffects       = new CompoundFormula("and");
                        CompoundFormula editedPreconditions = new CompoundFormula("and");
                        foreach (Predicate p in action.HashPrecondition)
                        {
                            editedPreconditions.AddOperand(p);
                        }

                        foreach (Predicate p in regularEffects)
                        {
                            editedEffects.AddOperand(p);
                        }

                        if (currentPermutation.Count > 0)
                        {
                            name += "_with_dependencies";
                        }
                        foreach (Dependency dependency in currentPermutation)
                        {
                            Constant          d         = mapDependencyToConstant[dependency];
                            GroundedPredicate revealedD = new GroundedPredicate("revealed");
                            revealedD.AddConstant(d);

                            name += "_" + d.Name;
                            editedPreconditions.AddOperand(revealedD);
                            editedEffects.AddOperand(dependency.predicate);
                        }

                        editedEffects.AddOperand(GetIncreaseTotalCostFunction(totalCostFunctionPredicate, regularActionCost));

                        Action editedAction = action.Clone();
                        editedAction.Name          = name;
                        editedAction.Preconditions = editedPreconditions;
                        editedAction.SetEffects(editedEffects);
                        allActions.Add(editedAction);
                    }
                }
            }

            List <ParametrizedPredicate> parametrizedPredicates = GetParametrizedPredicates(); //Add these predeicated to the joined domain. These predicates are general ones that are part of our transformation to a different problem.
            List <GroundedPredicate>     belongsToPredicates    = GetBelongsToGroundedPredicates();
            //List<GroundedPredicate> revealedSomethingPredicates = GetRevealedSomethingGroundedPredicates();
            //List<GroundedFunctionPredicate> amountOfDepRevPredicates = GetInitAmountOfDependenciesRevealedToZeroPredicates(m_agents);
            GroundedFunctionPredicate initTotalCostToZeroPredicate = GetInitTotalCostToZeroPredicate(totalCostFunctionPredicate);

            List <Action> dependenciesActions = GetDependenciesActions();

            allActions.AddRange(dependenciesActions);

            List <string> myNewTypes = GetMyNewTypes();

            dJoined.AddFunction(totalCostFunctionPredicate.ToString());
            dJoined.Actions = allActions;

            foreach (Agent agent in m_agents)
            {
                Domain d = agent.domain;
                foreach (ParametrizedPredicate pp in d.Predicates)
                {
                    dJoined.Predicates.Add(pp);
                }
                foreach (string sType in d.Types)
                {
                    if (!dJoined.Types.Contains(sType))
                    {
                        dJoined.Types.Add(sType);
                    }
                }
                foreach (KeyValuePair <string, string> pair in d.TypeHierarchy)
                {
                    dJoined.TypeHierarchy[pair.Key] = pair.Value;
                }
                foreach (Constant c in d.Constants)
                {
                    dJoined.Constants.Add(c);
                }

                foreach (GroundedPredicate pgp in agent.startState.Predicates)
                {
                    publicStartState.AddPredicate(pgp);
                }

                foreach (GroundedPredicate goalP in agent.goal)
                {
                    allGoals.Add(goalP);
                }
            }

            foreach (ParametrizedPredicate pp in parametrizedPredicates)
            {
                if (dJoined.Predicates.Contains(pp))
                {
                    throw new Exception("The dependencies predicates must be unique, and cannot be in another domain.");
                }
                dJoined.Predicates.Add(pp);
            }

            foreach (string type in myNewTypes)
            {
                if (dJoined.Types.Contains(type))
                {
                    throw new Exception("The dependency and agent types must be unique, and cannot be in another domain.");
                }
                dJoined.Types.Add(type);
                dJoined.TypeHierarchy[type] = objectType;
            }

            foreach (Constant d in dependenciesConstants)
            {
                if (dJoined.Constants.Contains(d))
                {
                    throw new Exception("The dependencies constant names must be unique, and cannot be in another domain.");
                }
                dJoined.Constants.Add(d);
            }

            foreach (Constant a in agentsConstants)
            {
                if (dJoined.Constants.Contains(a))
                {
                    throw new Exception("The agents constant names must be unique, and cannot be in another domain.");
                }
                dJoined.Constants.Add(a);
            }

            foreach (Constant n in numberConstants)
            {
                if (dJoined.Constants.Contains(n))
                {
                    throw new Exception("The numbers constant names must be unique, and cannot be in another domain.");
                }
                dJoined.Constants.Add(n);
            }


            //private List<GroundedPredicate> nextPredicates;
            //private List<GroundedPredicate> revealedNumberOfDependenciesPredicates;

            //Add to start state:

            foreach (GroundedPredicate gp in belongsToPredicates)
            {
                if (dJoined.Predicates.Contains(gp))
                {
                    throw new Exception("The belongs-to predicates must be unique, and cannot be in another domain.");
                }
                publicStartState.AddPredicate(gp);
            }

            /*
             * foreach (GroundedPredicate gp in revealedSomethingPredicates)
             * {
             *  if (dJoined.Predicates.Contains(gp))
             *      throw new Exception("The revealed-something predicates must be unique, and cannot be in another domain.");
             *  publicStartState.AddPredicate(gp);
             * }
             */

            /*
             * foreach(GroundedFunctionPredicate gfp in amountOfDepRevPredicates)
             * {
             *  if (dJoined.Predicates.Contains(gfp))
             *      throw new Exception("The amount-of-dependencies-revealed predicates must be unique, and cannot be in another domain.");
             *  publicStartState.AddPredicate(gfp);
             * }
             */
            foreach (GroundedPredicate gp in nextPredicates)
            {
                if (dJoined.Predicates.Contains(gp))
                {
                    throw new Exception("The next predicates must be unique, and cannot be in another domain.");
                }
                publicStartState.AddPredicate(gp);
            }

            foreach (GroundedPredicate gp in revealedNumberOfDependenciesPredicates)
            {
                if (dJoined.Predicates.Contains(gp))
                {
                    throw new Exception("The revealed-number-of-dependencies predicates must be unique, and cannot be in another domain.");
                }
                publicStartState.AddPredicate(gp);
            }

            if (dJoined.Predicates.Contains(initTotalCostToZeroPredicate))
            {
                throw new Exception("The initialization of total cost predicate must be unique, and cannot be in another domain.");
            }
            publicStartState.AddPredicate(initTotalCostToZeroPredicate);

            foreach (Predicate pInit in publicStartState.Predicates)
            {
                pJoined.AddKnown(pInit);
            }

            CompoundFormula goalf = new CompoundFormula("and");

            foreach (GroundedPredicate goalP in allGoals)
            {
                goalf.AddOperand(goalP);
            }

            pJoined.Goal = goalf;

            pJoined.AddMetric("(:metric " + "minimize " + totalCostFunctionPredicate.ToString() + ")");

            joinedDomain     = dJoined;
            joinedProblem    = pJoined;
            joinedStartState = publicStartState;
        }
Example #5
0
        public override Formula RemoveUniversalQuantifiers(List <Constant> lConstants, List <Predicate> lConstantPredicates, Domain d)
        {
            string sOperator = "";

            if (Operator == "forall")
            {
                sOperator = "and";
            }
            if (Operator == "exists")
            {
                sOperator = "or";
            }
            CompoundFormula fNew = new CompoundFormula(sOperator);

            if (Parameters.Count > 1)
            {
                throw new NotImplementedException();
            }
            string sParamName = Parameters.Keys.First();
            string sParamType = Parameters.Values.First();

            foreach (Constant c in lConstants)
            {
                if (c.Type == sParamType)
                {
                    Dictionary <string, Constant> dBindings = new Dictionary <string, Constant>();
                    dBindings[sParamName] = c;
                    foreach (Formula fSub in Operands)
                    {
                        Formula fRemoved = fSub.PartiallyGround(dBindings);
                        if (fRemoved == null)
                        {
                            continue;
                        }
                        Formula fNewSub = fRemoved.RemoveUniversalQuantifiers(lConstants, lConstantPredicates, d);

                        if (fNewSub is PredicateFormula)
                        {
                            Predicate p = ((PredicateFormula)fNewSub).Predicate;
                            if (p == Domain.TRUE_PREDICATE)
                            {
                                if (sOperator == "and")
                                {
                                    continue;
                                }
                                else if (sOperator == "or")
                                {
                                    return(fNewSub);
                                }
                                else
                                {
                                    throw new NotImplementedException();
                                }
                            }
                            if (p == Domain.FALSE_PREDICATE)
                            {
                                if (sOperator == "and")
                                {
                                    return(fNewSub);
                                }
                                else if (sOperator == "or")
                                {
                                    continue;
                                }
                                else
                                {
                                    throw new NotImplementedException();
                                }
                            }
                        }
                        if (fNewSub != null)
                        {
                            fNew.AddOperand(fNewSub);
                        }
                    }
                }
            }
            if (fNew.Operands.Count == 0)
            {
                if (sOperator == "and")
                {
                    return(new PredicateFormula(Domain.TRUE_PREDICATE));
                }
                if (sOperator == "or" || sOperator == "oneof")
                {
                    return(new PredicateFormula(Domain.FALSE_PREDICATE));
                }
            }
            return(fNew);
        }
Example #6
0
        public MemoryStream WriteKnowledgeProblem(HashSet <Predicate> lObserved, HashSet <Predicate> lAllValues)
        {
            MemoryStream msProblem = new MemoryStream();
            StreamWriter sw        = new StreamWriter(msProblem);

            sw.WriteLine("(define (problem K" + Name + ")");
            sw.WriteLine("(:domain K" + Domain.Name + ")");
            sw.WriteLine(";;" + SDRPlanner.Translation);
            sw.WriteLine("(:init"); //ff doesn't like the and (and");


            foreach (GroundedPredicate gp in lObserved)
            {
                if (gp.Name == "Choice")
                {
                    continue;
                }
                sw.WriteLine(gp);
                if (!Domain.AlwaysKnown(gp))
                {
                    Predicate kp = new KnowPredicate(gp);
                    sw.WriteLine(kp);
                }
            }
            HashSet <Predicate> lHidden = new HashSet <Predicate>(lAllValues.Except(lObserved));



            foreach (GroundedPredicate gp in lHidden)
            {
                sw.WriteLine(gp);
            }



            sw.WriteLine(")");

            HashSet <Predicate> lGoalPredicates = Goal.GetAllPredicates();


            CompoundFormula cfGoal = new CompoundFormula("and");

            foreach (Predicate p in lGoalPredicates)
            {
                if (Domain.AlwaysKnown(p))
                {
                    cfGoal.AddOperand(p);
                }
                else
                {
                    cfGoal.AddOperand(new KnowPredicate(p));
                }
            }

            CompoundFormula cfAnd = new CompoundFormula(cfGoal);

            sw.WriteLine("(:goal " + cfAnd.Simplify() + ")");
            //sw.WriteLine("))");

            sw.WriteLine(")");
            sw.Flush();


            return(msProblem);
        }
        public PatternDatabase(List <Domain> domains, List <Problem> problems, List <Agent> agents, string path)
        {
            try
            {
                Console.WriteLine("Computing PDB");
                if (File.Exists(path))
                {
                    cooperationCanGet = new Dictionary <GroundedPredicate, Dictionary <GroundedPredicate, int> >();
                    Dictionary <string, GroundedPredicate> mapStringtoPublicPredicate = new Dictionary <string, GroundedPredicate>();
                    foreach (Agent agent in agents)
                    {
                        foreach (GroundedPredicate publicGp in agent.PublicPredicates)
                        {
                            if (!mapStringtoPublicPredicate.ContainsKey(publicGp.ToString()))
                            {
                                mapStringtoPublicPredicate.Add(publicGp.ToString(), publicGp);
                            }
                        }
                    }
                    StreamReader pdbReader = new StreamReader(path);
                    while (!pdbReader.EndOfStream)
                    {
                        string   line  = pdbReader.ReadLine();
                        string[] items = line.Split('~');
                        if (!mapStringtoPublicPredicate.ContainsKey(items[0]))
                        {
                            continue;
                        }
                        cooperationCanGet.Add(mapStringtoPublicPredicate[items[0]], new Dictionary <GroundedPredicate, int>());
                        for (int i = 1; i < items.Length; i++)
                        {
                            string[] targetCost = items[i].Split('&');
                            cooperationCanGet[mapStringtoPublicPredicate[items[0]]].Add(mapStringtoPublicPredicate[targetCost[0]], int.Parse(targetCost[1]));
                        }
                    }
                }
                else
                {
                    DateTime startTime           = DateTime.Now;
                    int      privateActionsCount = 0;
                    foreach (Agent ag in agents)
                    {
                        privateActionsCount += ag.privateActions.Count;
                    }



                    Dictionary <GroundedPredicate, Dictionary <GroundedPredicate, int> >         canGet      = null;
                    List <Dictionary <GroundedPredicate, Dictionary <GroundedPredicate, int> > > agentCanGet = new List <Dictionary <GroundedPredicate, Dictionary <GroundedPredicate, int> > >();
                    HSPHeuristic                hsp              = null;
                    ForwardSearchPlanner        forwardSearch    = null;
                    HashSet <GroundedPredicate> publicPredicates = null;
                    int i = 0;
                    cooperationCanGet = new Dictionary <GroundedPredicate, Dictionary <GroundedPredicate, int> >();
                    foreach (Agent agent in agents)
                    {
                        canGet           = new Dictionary <GroundedPredicate, Dictionary <GroundedPredicate, int> >();
                        publicPredicates = new HashSet <GroundedPredicate>();
                        foreach (GroundedPredicate publicPredicate in agent.PublicPredicates)
                        {
                            if (!cooperationCanGet.ContainsKey(publicPredicate))
                            {
                                cooperationCanGet.Add(publicPredicate, new Dictionary <GroundedPredicate, int>());
                                cooperationCanGet[publicPredicate].Add(publicPredicate, 0);
                            }
                            if (publicPredicate.Negation || agent.invariantPredicate.Contains(publicPredicate) || publicPredicate.ToString().Equals("") || ((publicPredicate.Constants.Count > 1) && publicPredicate.Constants[0].Equals(publicPredicate.Constants[1])))
                            {
                                continue;
                            }
                            if (PDB_FACT_NAMES.Contains(publicPredicate.Name))
                            {
                                publicPredicates.Add(publicPredicate);
                            }
                        }
                        int counter = 0;
                        foreach (GroundedPredicate publicPredicate in publicPredicates)
                        {
                            counter++;
                            Console.Write("\rAgent " + i + ": " + counter + "/" + publicPredicates.Count + "           ");
                            if (!agent.MutuallyExclusive.ContainsKey(publicPredicate))
                            {
                                continue;
                            }
                            Constant constant1 = publicPredicate.Constants[0];
                            State    s         = new State(problems.ElementAt(i));
                            s.AddPredicate(publicPredicate);
                            foreach (Action publicAction in agent.publicActions)
                            {
                                if (publicAction.HashPrecondition.Contains(publicPredicate))
                                {
                                    foreach (var p in publicAction.HashPrecondition)
                                    {
                                        s.AddPredicate(p);
                                    }
                                }
                            }
                            HashSet <GroundedPredicate> mutex = new HashSet <GroundedPredicate>();
                            foreach (GroundedPredicate p in s.m_lPredicates)
                            {
                                if (agent.MutuallyExclusive.ContainsKey(p))
                                {
                                    foreach (GroundedPredicate mutexPredicate in agent.MutuallyExclusive[p])
                                    {
                                        mutex.Add(mutexPredicate);
                                    }
                                }
                            }

                            foreach (var gp in agent.Predicates)
                            {
                                if (!gp.Negation && !publicPredicates.Contains(gp) && !mutex.Contains(gp))
                                {
                                    //  if (!gp.ToString().Contains("at tru"))
                                    {
                                        s.AddPredicate(gp);
                                    }
                                }
                            }
                            int count2 = 0;
                            List <GroundedPredicate> facts = new List <GroundedPredicate>();

                            /*  facts.Add(publicPredicate);
                             * bool stop = false;
                             * while (!stop)
                             * {
                             *    stop = true;
                             *    List<GroundedPredicate> tmp = new List<GroundedPredicate>();
                             *    foreach (GroundedPredicate mGp in facts)
                             *    {
                             *        foreach (GroundedPredicate fact2 in agent.MutuallyExclusive[mGp])
                             *        {
                             *            if (!facts.Contains(fact2))
                             *            {
                             *                tmp.Add(fact2);
                             *                stop = false;
                             *            }
                             *        }
                             *
                             *    }
                             *    foreach (GroundedPredicate add in tmp)
                             *    {
                             *        facts.Add(add);
                             *    }
                             * }
                             */
                            bool mutexGoal;
                            foreach (GroundedPredicate goal in publicPredicates)
                            {
                                count2++;
                                mutexGoal = true;
                                if (!publicPredicate.Name.Equals(goal.Name) || !publicPredicate.Constants[0].Equals(goal.Constants[0]))
                                {
                                    continue;
                                }

                                /*if (privateActionsCount == 0)
                                 * {
                                 *  if (!goal.Equals(publicPredicate))
                                 *      continue;
                                 * }*/
                                Constant constant2 = goal.Constants[0];
                                if (!agent.MutuallyExclusive[publicPredicate].Contains(goal) || !constant1.Equals(constant2))
                                {
                                    mutexGoal = false;
                                    //  if(!facts.Contains(goal))
                                    continue;
                                }
                                List <Predicate> localGoal = new List <Predicate>();
                                localGoal.Add(goal);
                                hsp           = new HSPHeuristic(agent.m_actions, localGoal, false);
                                forwardSearch = new ForwardSearchPlanner(agent.m_actions, hsp, 30);
                                List <Action>   todo   = forwardSearch.Plan(s, localGoal);
                                CompoundFormula goalCf = new CompoundFormula("and");
                                foreach (GroundedPredicate gp in localGoal)
                                {
                                    goalCf.AddOperand(gp);
                                }
                                bool             isSolve;
                                ExternalPlanners externalPlanners = new ExternalPlanners();
                                // List<string> todo = externalPlanners.PdbFFPlan(domains.ElementAt(i), problems.ElementAt(i), s, goalCf, agent.m_actions, 5000, out isSolve);
                                //  List<string> todo = externalPlanners.Plan(true,true,domains.ElementAt(i), problems.ElementAt(i), s, goalCf, agent.m_actions, 5000, out isSolve);
                                // List<string> todo = externalPlanners.FFPlan(domains.ElementAt(i), problems.ElementAt(i), s, goalCf, agent.m_actions, 5000, out isSolve);

                                /* List<string> todo = new List<string>();
                                 * todo.Add("stump1");
                                 * todo.Add("stump2");
                                 * todo.Add("stump3");*/
                                if (todo != null)
                                {
                                    /* List<Action> actions = new List<Action>();
                                     * bool insert = false;
                                     * foreach (string actionName in todo)
                                     * {
                                     *   Action act = agent.domain.mapActionNameToAction[actionName];
                                     *   actions.Add(act);
                                     *   if (act.Preconditions.GetAllPredicates().Contains(publicPredicate))
                                     *   {
                                     *       insert = true;
                                     *   }
                                     *
                                     * }*/
                                    //if (insert && (mutexGoal || todo.Count > 0))
                                    {
                                        if (!canGet.ContainsKey(publicPredicate))
                                        {
                                            canGet.Add(publicPredicate, new Dictionary <GroundedPredicate, int>());
                                        }
                                        canGet[publicPredicate].Add(goal, todo.Count);
                                        if (!mutexGoal & todo.Count > 0)
                                        {
                                            // Console.WriteLine(publicPredicate.ToString()+"   "+goal.ToString());
                                            //Program.messages3 += (agents.Count) * 2;
                                        }
                                    }
                                }
                            }
                            if (DateTime.Now.Subtract(startTime).TotalMinutes > 15)
                            {
                                WritePdb(path);
                                return;
                            }
                        }
                        agentCanGet.Add(canGet);
                        i++;
                    }


                    publicPredicates = new HashSet <GroundedPredicate>();
                    foreach (Agent agent in agents)
                    {
                        foreach (GroundedPredicate publicPredicate in agent.PublicPredicates)
                        {
                            if (publicPredicate.Negation || agent.invariantPredicate.Contains(publicPredicate) || publicPredicate.ToString().Equals("") || ((publicPredicate.Constants.Count > 1) && publicPredicate.Constants[0].Equals(publicPredicate.Constants[1])))
                            {
                                continue;
                            }
                            if (PDB_FACT_NAMES.Contains(publicPredicate.Name))
                            {
                                publicPredicates.Add(publicPredicate);
                            }
                        }
                    }
                    //cooperationCanGet = new Dictionary<GroundedPredicate, Dictionary<GroundedPredicate, int>>();
                    foreach (GroundedPredicate startPredicate in publicPredicates)
                    {
                        Dictionary <GroundedPredicate, int> openList  = new Dictionary <GroundedPredicate, int>();
                        Dictionary <GroundedPredicate, int> closeList = new Dictionary <GroundedPredicate, int>();
                        openList.Add(startPredicate, 0);
                        while (openList.Count > 0)
                        {
                            KeyValuePair <GroundedPredicate, int> courentPredicate = openList.ElementAt(0);
                            openList.Remove(courentPredicate.Key);
                            closeList.Add(courentPredicate.Key, courentPredicate.Value);
                            int courentCost = courentPredicate.Value;
                            foreach (Dictionary <GroundedPredicate, Dictionary <GroundedPredicate, int> > canGetSet in agentCanGet)
                            {
                                if (!canGetSet.ContainsKey(courentPredicate.Key))
                                {
                                    continue;
                                }
                                foreach (KeyValuePair <GroundedPredicate, int> canGetPredicate in canGetSet[courentPredicate.Key])
                                {
                                    int addingCost = canGetPredicate.Value;
                                    if (openList.ContainsKey(canGetPredicate.Key))
                                    {
                                        if (openList[canGetPredicate.Key] > courentCost + addingCost)
                                        {
                                            openList[canGetPredicate.Key] = courentCost + addingCost;
                                        }
                                        continue;
                                    }
                                    if (closeList.ContainsKey(canGetPredicate.Key))
                                    {
                                        if (closeList[canGetPredicate.Key] > courentCost + addingCost)
                                        {
                                            closeList.Remove(canGetPredicate.Key);
                                            openList.Add(canGetPredicate.Key, courentCost + addingCost);
                                        }
                                        continue;
                                    }
                                    openList.Add(canGetPredicate.Key, courentCost + addingCost);
                                }
                            }
                        }
                        // cooperationCanGet.Add(startPredicate, new Dictionary<GroundedPredicate, int>());
                        foreach (KeyValuePair <GroundedPredicate, int> target in closeList)
                        {
                            if (!cooperationCanGet.ContainsKey(target.Key))
                            {
                                cooperationCanGet.Add(target.Key, new Dictionary <GroundedPredicate, int>());
                            }
                            if (!cooperationCanGet[target.Key].ContainsKey(startPredicate))
                            {
                                cooperationCanGet[target.Key].Add(startPredicate, target.Value);
                            }
                        }
                        //cooperationCanGet[startPredicate].Remove(startPredicate);
                    }

                    Program.messages2 += (agents.Count - 1) * agents.Count;
                    WritePdb(path);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Example #8
0
        public MemoryStream WriteKnowledgeProblem(HashSet <Predicate> lObserved, HashSet <Predicate> lHidden, int cMinMishaps, int cMishaps)
        {
            MemoryStream msProblem = new MemoryStream();
            StreamWriter sw        = new StreamWriter(msProblem);

            sw.WriteLine("(define (problem K" + Name + ")");
            sw.WriteLine("(:domain K" + Domain.Name + ")");
            sw.WriteLine(";;" + SDRPlanner.Translation);
            sw.WriteLine("(:init"); //ff doesn't like the and (and");

            string sKP = "", sP = "";

            foreach (GroundedPredicate gp in lObserved)
            {
                if (gp.Name == "Choice")
                {
                    continue;
                }
                if (Domain.AlwaysKnown(gp))
                {
                    sw.WriteLine(gp);
                }
                if (!Domain.AlwaysKnown(gp))
                {
                    Predicate kp = new KnowPredicate(gp);
                    sw.WriteLine(kp);
                }
            }
            foreach (GroundedPredicate gp in lHidden)
            {
                //GroundedPredicate kp = new GroundedPredicate(gp);
                //kp.Name = "NotK" + kp.Name;
                //sw.WriteLine(kp);
            }

            if (cMinMishaps > cMishaps)
            {
                sw.WriteLine("(MishapCount m" + cMishaps + ")");
            }

            sw.WriteLine(")");

            HashSet <Predicate> lGoalPredicates = Goal.GetAllPredicates();


            CompoundFormula cfGoal = new CompoundFormula("and");

            foreach (Predicate p in lGoalPredicates)
            {
                if (Domain.AlwaysKnown(p))
                {
                    cfGoal.AddOperand(p);
                }
                else
                {
                    cfGoal.AddOperand(new KnowPredicate(p));
                }
            }

            CompoundFormula cfAnd = new CompoundFormula(cfGoal);

            if (cMinMishaps > cMishaps && SDRPlanner.Translation != SDRPlanner.Translations.Conformant)
            {
                GroundedPredicate gp = new GroundedPredicate("MishapCount");
                gp.AddConstant(new Constant("mishaps", "m" + cMinMishaps));
                cfAnd.AddOperand(gp);
            }

            sw.WriteLine("(:goal " + cfAnd.Simplify() + ")");
            //sw.WriteLine("))");

            sw.WriteLine(")");
            sw.Flush();


            return(msProblem);
        }
Example #9
0
        public MemoryStream WriteKnowledgeProblem(HashSet <Predicate> lObserved, HashSet <Predicate> lHidden, int cMinMishaps, int cMishaps, bool bRemoveNegativePreconditions)
        {
            MemoryStream msProblem = new MemoryStream();
            StreamWriter sw        = new StreamWriter(msProblem);

            sw.WriteLine("(define (problem K" + Name + ")");
            sw.WriteLine("(:domain K" + Domain.Name + ")");
            sw.WriteLine(";;" + SDRPlanner.Translation);
            sw.WriteLine("(:init"); //ff doesn't like the and (and");

            string sKP = "", sP = "";

            HashSet <string> lNegativePreconditons = new HashSet <string>();

            if (bRemoveNegativePreconditions)
            {
                foreach (Predicate p in Domain.IdentifyNegativePreconditions())
                {
                    lNegativePreconditons.Add(p.Name);
                }
            }

            foreach (GroundedPredicate gp in lObserved)
            {
                if (gp.Name == "Choice")
                {
                    continue;
                }
                if (Domain.AlwaysKnown(gp))
                {
                    sw.WriteLine(gp);
                }
                if (!Domain.AlwaysKnown(gp))
                {
                    Predicate kp = new KnowPredicate(gp);
                    sw.WriteLine(kp);
                }
                if (gp.Negation && bRemoveNegativePreconditions && lNegativePreconditons.Contains(gp.Name))
                {
                    Predicate np = gp.Negate().Clone();
                    np.Name = "Not" + gp.Name;
                    sw.WriteLine(np);
                }
            }
            if (bRemoveNegativePreconditions)
            {
                foreach (GroundedPredicate gp in lHidden)
                {
                    Predicate nkp = gp.Clone();
                    nkp.Name = "NotK" + gp.Name;
                    sw.WriteLine(nkp);
                    Predicate nknp = gp.Clone();
                    nknp.Name = "NotKN" + gp.Name;
                    sw.WriteLine(nknp);
                }
            }

            if (cMinMishaps > cMishaps)
            {
                sw.WriteLine("(MishapCount m" + cMishaps + ")");
            }

            if (SDRPlanner.AddActionCosts)
            {
                sw.WriteLine("(= (total-cost) 0)");
            }

            sw.WriteLine(")");

            HashSet <Predicate> lGoalPredicates    = Goal.GetAllPredicates();


            CompoundFormula cfGoal = new CompoundFormula("and");

            foreach (Predicate p in lGoalPredicates)
            {
                if (Domain.AlwaysKnown(p))
                {
                    cfGoal.AddOperand(p);
                }
                else
                {
                    cfGoal.AddOperand(new KnowPredicate(p));
                }
            }

            CompoundFormula cfAnd = new CompoundFormula(cfGoal);

            if (cMinMishaps > cMishaps && SDRPlanner.Translation != SDRPlanner.Translations.Conformant)
            {
                GroundedPredicate gp = new GroundedPredicate("MishapCount");
                gp.AddConstant(new Constant("mishaps", "m" + cMinMishaps));
                cfAnd.AddOperand(gp);
            }

            sw.WriteLine("(:goal " + cfAnd.Simplify() + ")");
            if (MetricStatement != null)
            {
                sw.WriteLine(MetricStatement);
            }

            sw.WriteLine(")");
            sw.Flush();


            return(msProblem);
        }
Example #10
0
        public List <Action> getProjectionPublicActionForAgent(string agent)
        {
            List <Action>       allPublicActions   = new List <Action>();
            HashSet <Predicate> allPublicPredicate = new HashSet <Predicate>();
            HashSet <Predicate> allPublicPredicateWithMyPrivate = new HashSet <Predicate>();

            foreach (var name in publicAgentPredicate.Keys)
            {
                foreach (GroundedPredicate gp in publicAgentPredicate[name])
                {
                    if (!allPublicPredicate.Contains(gp))
                    {
                        allPublicPredicate.Add(gp);
                    }

                    if (!allPublicPredicateWithMyPrivate.Contains(gp))
                    {
                        allPublicPredicateWithMyPrivate.Add(gp);
                    }
                }

                /*if (name.Equals(agent))
                 * {
                 *
                 *
                 *
                 *      foreach (GroundedPredicate gp2 in agentPredicate[name])
                 *      {
                 *          if (!allPublicPredicateWithMyPrivate.Contains(gp2))
                 *              allPublicPredicateWithMyPrivate.Add(gp2);
                 *      }
                 *
                 * }*/
            }


            foreach (var name in publicAgentPredicate.Keys)
            {
                if (!name.Equals(agent))
                {
                    foreach (Action act in publicAgentActions[name])
                    {
                        Action          newAct  = new Action(act.Name);
                        CompoundFormula effect  = new CompoundFormula("and");
                        CompoundFormula preCond = new CompoundFormula("and");
                        foreach (GroundedPredicate eff in act.HashEffects)
                        {
                            if (allPublicPredicate.Contains(eff) || allPublicPredicate.Contains(eff.Negate()))
                            {
                                effect.AddOperand(eff);
                            }
                        }
                        foreach (GroundedPredicate pre in act.HashPrecondition)
                        {
                            if (allPublicPredicate.Contains(pre) || allPublicPredicate.Contains(pre.Negate()))
                            {
                                preCond.AddOperand(pre);
                            }
                        }

                        newAct.Effects       = effect;
                        newAct.Preconditions = preCond;
                        newAct.LoadPrecondition();
                        allPublicActions.Add(newAct);
                    }
                }
            }

            return(allPublicActions);
        }
        public void WriteTaggedProblem(string sProblemFile, Dictionary <string, List <Predicate> > dTags, IEnumerable <Predicate> lObserved,
                                       List <Predicate> lTrueState, Dictionary <string, double> dFunctionValues, bool bOnlyIdentifyStates)
        {
            StreamWriter sw = new StreamWriter(sProblemFile);

            sw.WriteLine("(define (problem K" + Name + ")");
            sw.WriteLine("(:domain K" + Domain.Name + ")");
            sw.WriteLine("(:init");         //ff doesn't like the and (and");

            string sKP = "", sP = "";

            if (Domain.TIME_STEPS > 0)
            {
                sw.WriteLine("(time0)");
            }
            if (SDRPlanner.SplitConditionalEffects)
            {
                sw.WriteLine("(NotInAction)\n");
            }
            foreach (KeyValuePair <string, double> f in dFunctionValues)
            {
                sw.WriteLine("(= " + f.Key + " " + f.Value + ")");
            }
            foreach (GroundedPredicate gp in lObserved)
            {
                if (gp.Name == "Choice")
                {
                    continue;
                }
                sKP = "(K" + gp.Name;
                sP  = "(" + gp.Name;
                foreach (Constant c in gp.Constants)
                {
                    sKP += " " + c.Name;
                    sP  += " " + c.Name;
                }
                if (gp.Negation)
                {
                    sKP += " " + Domain.FALSE_VALUE;
                }
                else
                {
                    sKP += " " + Domain.TRUE_VALUE;
                }
                if (!Domain.AlwaysKnown(gp))
                {
                    sw.WriteLine(sKP + ")");
                }
                if (!gp.Negation)
                {
                    sw.WriteLine(sP + ")");
                }
            }
            foreach (GroundedPredicate gp in lTrueState)
            {
                if (gp.Name == "Choice")
                {
                    continue;
                }
                if (!gp.Negation)
                {
                    sP = "(" + gp.Name;
                    foreach (Constant c in gp.Constants)
                    {
                        sP += " " + c.Name;
                    }
                    sw.WriteLine(sP + ")");
                }
            }
            foreach (KeyValuePair <string, List <Predicate> > p in dTags)
            {
                foreach (GroundedPredicate gp in p.Value)
                {
                    if (gp.Name == "Choice")
                    {
                        continue;
                    }
                    sKP = GenerateKnowGivenLine(gp, p.Key, false);
                    sw.WriteLine(sKP);
                }

                if (SDRPlanner.AddAllKnownToGiven)
                {
                    foreach (GroundedPredicate gp in lObserved)
                    {
                        if (gp.Name == "Choice")
                        {
                            continue;
                        }
                        if (!Domain.AlwaysKnown(gp))
                        {
                            sKP = GenerateKnowGivenLine(gp, p.Key, false);
                            sw.WriteLine(sKP);
                        }
                    }
                }
            }

            //if (Problem.Domain.HasNonDeterministicActions())
            //    sw.WriteLine("(option opt0)");

            sw.WriteLine(")");

            CompoundFormula cfGoal = new CompoundFormula("and");

            if (!bOnlyIdentifyStates)
            {
                cfGoal.AddOperand(Goal);
                HashSet <Predicate> lGoalPredicates = new HashSet <Predicate>();
                Goal.GetAllPredicates(lGoalPredicates);
                //string sGoal = Problem.Goal.ToString();
                //sw.WriteLine("(:goal " + sGoal + ")");

                //sw.Write("(:goal (and ");
                //sw.Write( sGoal );

                foreach (Predicate p in lGoalPredicates)
                {
                    //Problem.Domain.WriteKnowledgePredicate(sw, p);
                    if (!Domain.AlwaysKnown(p))
                    {
                        cfGoal.AddOperand(new KnowPredicate(p));
                    }
                }
            }
            if (bOnlyIdentifyStates || SDRPlanner.AddTagRefutationToGoal)
            {
                for (int iTag = 1; iTag < dTags.Count; iTag++)
                {
                    GroundedPredicate gp = new GroundedPredicate("KNot");
                    gp.AddConstant(new Constant("TAG_TYPE", "tag" + iTag));
                    cfGoal.AddOperand(gp);
                    //sw.Write(" (KNot t" + iTag + ")");
                }
            }
            if (SDRPlanner.ForceTagObservations)
            {
                foreach (Predicate p in lTrueState)
                {
                    if (Domain.Observable(p))
                    {
                        cfGoal.AddOperand(new KnowPredicate(p));
                    }
                }
            }
            sw.WriteLine("(:goal " + cfGoal + ")");
            //sw.WriteLine("))");
            if (MetricStatement != null)
            {
                sw.WriteLine(MetricStatement);
            }
            sw.WriteLine(")");
            sw.Close();
        }
Example #12
0
        private List <Formula> RegressLandmark(Formula fCurrentLandmark, Dictionary <Predicate, List <Action> > dLandmarkAchievers, HashSet <Predicate> lInitialState)
        {
            //when landmark is (or p1 p2), and p1 requires (or q1 q2) (or r1 r2) and p2 requires p3 and r3, then the result should be (or q1 q2 q3) (or r1 r2 r3)
            List <Formula> lFormulas = new List <Formula>();
            Dictionary <string, CompoundFormula> dAll = null;
            int cPredicatesToAchieve = 0;

            foreach (GroundedPredicate pLandmark in dLandmarkAchievers.Keys)
            {
                List <Action> lActions = dLandmarkAchievers[pLandmark];
                Dictionary <string, CompoundFormula> dRegressedFormulas = new Dictionary <string, CompoundFormula>();
                RegressLandmark(pLandmark, dLandmarkAchievers[pLandmark], lInitialState, dRegressedFormulas);
                string sLandmarkName = GetNameAndTag(pLandmark);
                if (dAll == null)
                {
                    dAll = dRegressedFormulas;
                }
                else
                {
                    Dictionary <string, CompoundFormula> dNew = new Dictionary <string, CompoundFormula>();
                    foreach (string sKey in dAll.Keys)
                    {
                        if (dRegressedFormulas.ContainsKey(sKey))
                        {
                            CompoundFormula cfOr = new CompoundFormula("or");
                            cfOr.AddOperand(dAll[sKey]);
                            cfOr.AddOperand(dRegressedFormulas[sKey]);
                            dNew[sKey] = cfOr;
                        }
                    }
                    dAll = dNew;
                }
            }
            foreach (string sPreType in dAll.Keys)
            {
                Formula fSimplified = dAll[sPreType].Simplify();
                //4 options here:
                //fSimplified is a single predicate
                //fSimplified is a simple disjunction
                //fSimplified is a simple conjunction
                //fSimplified is a disjunction of simple conjunctions
                if (fSimplified is PredicateFormula)
                {
                    lFormulas.Add(fSimplified);
                }
                else
                {
                    CompoundFormula cf = (CompoundFormula)fSimplified;
                    if (cf.Operator == "and")
                    {
                        foreach (PredicateFormula pf in cf.Operands)
                        {
                            lFormulas.Add(pf);
                        }
                    }
                    else
                    {
                        lFormulas.Add(RemoveConjunctions(cf));
                    }
                }
            }



            return(lFormulas);
        }
Example #13
0
        private void UpdateDependenciesIntoDomainsAndProblems(List <Agent> m_agents)
        {
            //GroundedFunctionPredicate totalCostFunctionPredicate = GetTotalCostFunction();

            Domain  dJoined                      = new Domain("JoinedDomain", "");
            Problem pJoined                      = new Problem("JoinedProblem", dJoined);
            State   publicStartState             = new State(pJoined);
            HashSet <GroundedPredicate> allGoals = new HashSet <GroundedPredicate>();

            List <Action> allActions = new List <Action>();

            foreach (Agent agent in m_agents)
            {
                Dictionary <Predicate, List <Dependency> > predicate2DependenciesThatAcomplishIt = this.agentsPreconditionDictionary[agent];
                Dictionary <Action, List <Dependency> >    action2DependenciesInItsEffects       = this.agentsActions2DependenciesInEffect[agent];

                Tuple <GroundedPredicate, List <Predicate> > tuple = GetGoingSoloPredicatesForAgent(agent, m_agents);

                GroundedPredicate agentGoingSolo          = tuple.Item1;
                List <Predicate>  otherAgentsNotGoingSolo = tuple.Item2;

                foreach (Action action in agent.m_actions)
                {
                    //List<Dependency> dependenciesForAction = new List<Dependency>();
                    //List<Predicate> regularEffects = new List<Predicate>();

                    /*
                     * if(action.Name == OptimalDependenciesPlanner.startStateDummyActionName)
                     * {
                     *  continue;
                     * }
                     */

                    CompoundFormula editedEffects       = new CompoundFormula("and");
                    CompoundFormula editedPreconditions = new CompoundFormula("and");

                    if (!action.isPublic)
                    {
                        //if it is a private action, just use it as is...
                        Action editedPrivateAction = action.Clone();

                        foreach (Predicate p in action.HashPrecondition)
                        {
                            editedPreconditions.AddOperand(p); //anyways, add this precondition to the preconditions list...
                        }

                        foreach (Predicate notGoingSolo in otherAgentsNotGoingSolo)
                        {
                            editedPreconditions.AddOperand(notGoingSolo);
                        }

                        editedPrivateAction.Preconditions = editedPreconditions;
                        editedPrivateAction.SetEffects(action.Effects);

                        allActions.Add(editedPrivateAction);
                        continue;
                    }

                    List <Dependency> dependenciesInEffect = action2DependenciesInItsEffects[action];



                    foreach (Predicate notGoingSolo in otherAgentsNotGoingSolo)
                    {
                        editedPreconditions.AddOperand(notGoingSolo);
                    }

                    foreach (Predicate p in action.HashPrecondition)
                    {
                        editedPreconditions.AddOperand(p); //anyways, add this precondition to the preconditions list...

                        if (predicate2DependenciesThatAcomplishIt.ContainsKey(p))
                        {
                            //Than this is a precondition that comes from a dependency...
                            //We should now go over all the possible dependencies that achive this predicate and add them to the following formula:
                            CompoundFormula cfOr = new CompoundFormula("or");

                            //Add the going-solo predicate as a precondition in the "or" so we will capture it as well:
                            cfOr.AddOperand(agentGoingSolo);

                            List <Dependency> dependenciesThatAcomplish = predicate2DependenciesThatAcomplishIt[p];

                            Predicate negationP         = p.Negate();
                            bool      negationInEffects = action.HashEffects.Contains(negationP);

                            foreach (Dependency dependency in dependenciesThatAcomplish)
                            {
                                Constant d = mapDependencyToConstant[dependency];

                                CompoundFormula   cfAnd              = new CompoundFormula("and");
                                GroundedPredicate usedDependency     = GetUsedDependencyGrounded(d);
                                GroundedPredicate revealedDependency = GetRevealedGrounded(d);
                                cfAnd.AddOperand(usedDependency);
                                cfAnd.AddOperand(revealedDependency);

                                /*
                                 * if (dependency.action.Name == OptimalDependenciesPlanner.startStateDummyActionName)
                                 * {
                                 *  cfOr.AddOperand(usedDependency);
                                 * }
                                 * else
                                 */
                                {
                                    cfOr.AddOperand(cfAnd);
                                }

                                if (negationInEffects)
                                {
                                    //than we should put the negation of used-dependency in the effects as well:
                                    Predicate negationUsedDependency = usedDependency.Negate();
                                    editedEffects.AddOperand(negationUsedDependency);
                                }
                            }

                            editedPreconditions.AddOperand(cfOr);
                        }
                    }

                    foreach (Predicate p in action.HashEffects)
                    {
                        editedEffects.AddOperand(p); //anyways, add this effect to the effects list...
                    }

                    foreach (Dependency dependency in dependenciesInEffect)
                    {
                        //Then this is a dependency dependent action, which means we need to duplicate it several times so that we have the action with the dependency revealed and without it
                        //dependenciesForAction.Add(dependency);

                        Constant          d = mapDependencyToConstant[dependency];
                        GroundedPredicate usedDependency = GetUsedDependencyGrounded(d);
                        //GroundedPredicate revealedD = new GroundedPredicate("revealed");
                        //revealedD.AddConstant(d);

                        //CompoundFormula cfCondition = new CompoundFormula("when");
                        //cfCondition.AddOperand(revealedD); //condition
                        //cfCondition.AddOperand(p); //result = the predicate we want to reveal.


                        editedEffects.AddOperand(usedDependency);
                    }

                    //Current:
                    Action editedAction = action.Clone();
                    //editedAction.Name = name;
                    editedAction.Name          = action.Name;
                    editedAction.Preconditions = editedPreconditions;
                    editedAction.SetEffects(editedEffects);
                    allActions.Add(editedAction);
                }
            }

            List <ParametrizedPredicate> parametrizedPredicates = GetParametrizedPredicates(); //Add these predeicated to the joined domain. These predicates are general ones that are part of our transformation to a different problem.
            List <GroundedPredicate>     belongsToPredicates    = GetBelongsToGroundedPredicates();
            //List<GroundedPredicate> revealedSomethingPredicates = GetRevealedSomethingGroundedPredicates();
            //List<GroundedFunctionPredicate> amountOfDepRevPredicates = GetInitAmountOfDependenciesRevealedToZeroPredicates(m_agents);
            //GroundedFunctionPredicate initTotalCostToZeroPredicate = GetInitTotalCostToZeroPredicate(totalCostFunctionPredicate);
            GroundedPredicate inJoinedStageGrounded = GetGroundedInJoinedStagePredicate();
            List <Predicate>  notGoingSolos         = GetNotGoingSoloForStartState(m_agents);

            List <Action> dependenciesActions = GetDependenciesActions();

            allActions.AddRange(dependenciesActions);

            List <string> myNewTypes = GetMyNewTypes();

            //dJoined.AddFunction(totalCostFunctionPredicate.ToString());
            dJoined.Actions = allActions;

            foreach (Agent agent in m_agents)
            {
                Domain d = agent.domain;
                foreach (ParametrizedPredicate pp in d.Predicates)
                {
                    dJoined.Predicates.Add(pp);
                }
                foreach (string sType in d.Types)
                {
                    if (!dJoined.Types.Contains(sType))
                    {
                        dJoined.Types.Add(sType);
                    }
                }
                foreach (KeyValuePair <string, string> pair in d.TypeHierarchy)
                {
                    dJoined.TypeHierarchy[pair.Key] = pair.Value;
                }
                foreach (Constant c in d.Constants)
                {
                    dJoined.Constants.Add(c);
                }

                foreach (GroundedPredicate pgp in agent.startState.Predicates)
                {
                    publicStartState.AddPredicate(pgp);
                }

                foreach (GroundedPredicate goalP in agent.goal)
                {
                    allGoals.Add(goalP);
                }
            }

            /*
             * foreach (Dependency dependency in OptimalDependenciesPlanner.startStateDependencies)
             * {
             *  Constant dep = mapDependencyToConstant[dependency];
             *  GroundedPredicate usedDependency = GetUsedDependencyGrounded(dep);
             *  publicStartState.AddPredicate(usedDependency);
             * }
             */

            foreach (ParametrizedPredicate pp in parametrizedPredicates)
            {
                if (dJoined.Predicates.Contains(pp))
                {
                    throw new Exception("The dependencies predicates must be unique, and cannot be in another domain.");
                }
                dJoined.Predicates.Add(pp);
            }

            foreach (string type in myNewTypes)
            {
                if (dJoined.Types.Contains(type))
                {
                    throw new Exception("The dependency and agent types must be unique, and cannot be in another domain.");
                }
                dJoined.Types.Add(type);
                dJoined.TypeHierarchy[type] = objectType;
            }

            foreach (Constant d in dependenciesConstants)
            {
                if (dJoined.Constants.Contains(d))
                {
                    throw new Exception("The dependencies constant names must be unique, and cannot be in another domain.");
                }
                dJoined.Constants.Add(d);
            }

            foreach (Constant a in agentsConstants)
            {
                if (dJoined.Constants.Contains(a))
                {
                    throw new Exception("The agents constant names must be unique, and cannot be in another domain.");
                }
                dJoined.Constants.Add(a);
            }

            foreach (Constant n in numberConstants)
            {
                if (dJoined.Constants.Contains(n))
                {
                    throw new Exception("The numbers constant names must be unique, and cannot be in another domain.");
                }
                dJoined.Constants.Add(n);
            }


            //private List<GroundedPredicate> nextPredicates;
            //private List<GroundedPredicate> revealedNumberOfDependenciesPredicates;

            //Add to start state:

            foreach (GroundedPredicate gp in belongsToPredicates)
            {
                if (dJoined.Predicates.Contains(gp))
                {
                    throw new Exception("The belongs-to predicates must be unique, and cannot be in another domain.");
                }
                publicStartState.AddPredicate(gp);
            }

            /*
             * foreach (GroundedPredicate gp in revealedSomethingPredicates)
             * {
             *  if (dJoined.Predicates.Contains(gp))
             *      throw new Exception("The revealed-something predicates must be unique, and cannot be in another domain.");
             *  publicStartState.AddPredicate(gp);
             * }
             */

            /*
             * foreach(GroundedFunctionPredicate gfp in amountOfDepRevPredicates)
             * {
             *  if (dJoined.Predicates.Contains(gfp))
             *      throw new Exception("The amount-of-dependencies-revealed predicates must be unique, and cannot be in another domain.");
             *  publicStartState.AddPredicate(gfp);
             * }
             */
            foreach (GroundedPredicate gp in nextPredicates)
            {
                if (dJoined.Predicates.Contains(gp))
                {
                    throw new Exception("The next predicates must be unique, and cannot be in another domain.");
                }
                publicStartState.AddPredicate(gp);
            }

            foreach (GroundedPredicate gp in revealedNumberOfDependenciesPredicates)
            {
                if (dJoined.Predicates.Contains(gp))
                {
                    throw new Exception("The revealed-number-of-dependencies predicates must be unique, and cannot be in another domain.");
                }
                publicStartState.AddPredicate(gp);
            }

            if (dJoined.Predicates.Contains(inJoinedStageGrounded))
            {
                throw new Exception("The in-joined-stage predicate must be unique, and cannot be in another domain.");
            }
            publicStartState.AddPredicate(inJoinedStageGrounded);

            foreach (Predicate p in notGoingSolos)
            {
                if (dJoined.Predicates.Contains(p))
                {
                    throw new Exception("The not(going-solo agent) predicates must be unique, and cannot be in another domain.");
                }
                publicStartState.AddPredicate(p);
            }

            /*
             * if (dJoined.Predicates.Contains(initTotalCostToZeroPredicate))
             *  throw new Exception("The initialization of total cost predicate must be unique, and cannot be in another domain.");
             * publicStartState.AddPredicate(initTotalCostToZeroPredicate);
             */
            foreach (Predicate pInit in publicStartState.Predicates)
            {
                pJoined.AddKnown(pInit);
            }

            CompoundFormula goalf = new CompoundFormula("and");

            foreach (GroundedPredicate goalP in allGoals)
            {
                goalf.AddOperand(goalP);
            }

            pJoined.Goal = goalf;

            //pJoined.AddMetric("(:metric " + "minimize " + totalCostFunctionPredicate.ToString() + ")");

            joinedDomain     = dJoined;
            joinedProblem    = pJoined;
            joinedStartState = publicStartState;
        }
        public static bool Grounding(out List <string> finalPlan, out string fault)
        {
            Console.WriteLine("\nPublic global plan found, searching for private plans");
            List <Dictionary <CompoundFormula, string> >   newPlan = new List <Dictionary <CompoundFormula, string> >();
            List <KeyValuePair <string, CompoundFormula> > lplan   = new List <KeyValuePair <string, CompoundFormula> >();

            foreach (string actname in highLevelplan)
            {
                Action          act    = mapActionNameToAction[actname];
                CompoundFormula effect = new CompoundFormula("and");
                foreach (GroundedPredicate gp in act.HashEffects)
                {
                    if (agents[map[act.agent]].PublicPredicates.Contains(gp))
                    {
                        effect.AddOperand(gp);
                    }
                }
                lplan.Add(new KeyValuePair <string, CompoundFormula>(act.agent, effect));
            }
            int count = 0;

            finalPlan = new List <string>();
            fault     = "";
            int level = 0;

            Dictionary <string, State> agentState = new Dictionary <string, State>();

            foreach (Agent a in agents)
            {
                agentState.Add(a.name, new State(a.startState));
            }
            CompoundFormula goalFormula = new CompoundFormula("and");
            string          agentName;

            foreach (KeyValuePair <string, CompoundFormula> eff in lplan)
            {
                agentName   = eff.Key;
                goalFormula = new CompoundFormula(eff.Value);

                HashSet <GroundedPredicate> mutex = new HashSet <GroundedPredicate>();
                foreach (GroundedPredicate gp in goalFormula.GetAllPredicates())
                {
                    if (agents[map[agentName]].MutuallyExclusive.ContainsKey(gp))
                    {
                        foreach (GroundedPredicate mgp in agents[map[agentName]].MutuallyExclusive[gp])
                        {
                            mutex.Add(mgp);
                        }
                    }
                }

                /*
                 * foreach (GroundedPredicate publicPos in agents[map[agentName]].PublicPredicates)
                 * {
                 *  if (agentState[agentName].m_lPredicates.Contains(publicPos))
                 *  {
                 *      if (!mutex.Contains(publicPos) && !goalFormula.GetAllPredicates().Contains(publicPos.Negate()))
                 *          goalFormula.AddOperand(publicPos);
                 *  }
                 * }
                 * */
                bool             bUnsolvable      = false;
                ExternalPlanners externalPlanners = new ExternalPlanners();
                ffLplan = externalPlanners.FFPlan(agents[map[agentName]].domain, agents[map[agentName]].problem, agentState[agentName], goalFormula, agents[map[agentName]].m_actions, 5 * 60 * 1000, out bUnsolvable);

                //List<string> todo = Plan(d, p, agentState[agentName], goalFormula, agents[map[agentName]].m_actions);
                //planTheard = new Thread(() => FF_Plan(agents[map[agentName]].domain, agents[map[agentName]].problem, agentState[agentName], goalFormula, agents[map[agentName]].m_actions));
                //List<string> todo = Plan(d, p, agentState[agentName], localGoal, agents[map[agentName]].m_actions);
                //planTheard.Start();
                //planTheard.Join(3000);
                //planTheard.Abort();
                if (ffLplan != null)
                {
                    List <string> todo = ffLplan;
                    foreach (string act in todo)
                    {
                        State s = agentState[agentName].ApplyII(agents[map[agentName]].domain.mapActionNameToAction[act]);
                        if (s == null)
                        {
                            throw new Exception();
                        }
                        agentState[agentName] = s;
                        finalPlan.Add(act);
                        foreach (Agent a in agents)
                        {
                            if (!a.name.Equals(agentName))
                            {
                                agentState[a.name] = agentState[a.name].ApplyEffect(agents[map[agentName]].domain.mapActionNameToAction[act], a.Predicates);
                            }
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }
            Dictionary <string, CompoundFormula> agentGoal = new Dictionary <string, CompoundFormula>();

            foreach (Agent a in agents)
            {
                agentGoal.Add(a.name, new CompoundFormula("and"));
                foreach (GroundedPredicate goalPredicate in a.goal)
                {
                    bool sat = false;

                    /* foreach (var state in agentState.Values)
                     * {
                     *   if (state.m_lPredicates.Contains(goalPredicate))
                     *   {
                     *       sat = true;
                     *       break;
                     *   }
                     * }*/
                    if (true)//!sat)
                    {
                        agentGoal[a.name].AddOperand(goalPredicate);
                    }
                }

                /*  HashSet<GroundedPredicate> mutex = new HashSet<GroundedPredicate>();
                 * foreach (GroundedPredicate gp in agentGoal[a.name].GetAllPredicates())
                 * {
                 *    if (a.MutuallyExclusive.ContainsKey(gp))
                 *    {
                 *        foreach (GroundedPredicate mgp in a.MutuallyExclusive[gp])
                 *            mutex.Add(mgp);
                 *    }
                 * }
                 * foreach (GroundedPredicate publicPos in a.PublicPredicates)
                 * {
                 *    if (agentState[a.name].m_lPredicates.Contains(publicPos) && !mutex.Contains(publicPos))
                 *        agentGoal[a.name].AddOperand(publicPos);
                 * }*/
            }
            foreach (var agent in agents)
            {
                if (agentGoal[agent.name].Operands.Count > 0)
                {
                    //List<string> todo = Plan(d, p, agentState[agent.name], agentGoal[agent.name]);
                    // hsp = new HSPHeuristic(agent.m_actions, agentGoal[agent.name].GetAllPredicates().ToList(), admisabiliy);
                    //  forwardSearch = new ForwardSearchPlanner(agent.m_actions, hsp);
                    // List<Action> todo = forwardSearch.Plan(agentState[agent.name], agentGoal[agent.name].GetAllPredicates().ToList());
                    //List<string> todo = Plan(d, p, agentState[agent.name], agentGoal[agent.name], agent.m_actions);
                    bool             bUnsolvable      = false;
                    ExternalPlanners externalPlanners = new ExternalPlanners();
                    ffLplan = externalPlanners.FFPlan(agents[map[agent.name]].domain, agents[map[agent.name]].problem, agentState[agent.name], agentGoal[agent.name], agent.m_actions, 5 * 60 * 1000, out bUnsolvable);
                    if (ffLplan != null)
                    {
                        List <string> todo = ffLplan;

                        foreach (string act in todo)
                        {
                            agentState[agent.name] = agentState[agent.name].ApplyII(agents[map[agent.name]].domain.mapActionNameToAction[act]);
                            finalPlan.Add(act);
                            foreach (Agent a in agents)
                            {
                                if (!a.name.Equals(agent.name))
                                {
                                    agentState[a.name] = agentState[a.name].ApplyEffect(agents[map[agent.name]].domain.mapActionNameToAction[act], a.Predicates);
                                }
                            }
                        }
                    }
                    else
                    {
                        Program.KillPlanners();
                        //return planToGoalIIII(out finalPlan, out fault);
                    }
                }
            }
            foreach (var agSt in agentState)
            {
                if (agSt.Value == null)
                {
                    return(false);
                }
            }

            return(true);
        }