private GroundedPredicate GetUsedDependencyGrounded(Constant d)
        {
            GroundedPredicate usedDependency = new GroundedPredicate(usedDependencyPredicateName);

            usedDependency.AddConstant(d);
            return(usedDependency);
        }
        private GroundedPredicate GetRevealedGrounded(Constant d)
        {
            GroundedPredicate revealedD = new GroundedPredicate("revealed");

            revealedD.AddConstant(d);
            return(revealedD);
        }
        private Action GetResetDependenciesRevealedAction(GroundedFunctionPredicate totalCostFunctionPredicate)
        {
            Action resetDependenciesRevealed = new Action(resetDependenciesActionName);

            CompoundFormula preconditions = new CompoundFormula("and");
            CompoundFormula effects       = new CompoundFormula("and");

            foreach (Constant agent in agentsConstants)
            {
                GroundedPredicate revealedSomething = new GroundedPredicate("revealed-something");
                revealedSomething.AddConstant(agent);

                Predicate notRevealedSomething = revealedSomething.Negate();

                preconditions.AddOperand(revealedSomething);
                effects.AddOperand(notRevealedSomething);
            }

            effects.AddOperand(GetIncreaseTotalCostFunction(totalCostFunctionPredicate, revealedDependencyCost));

            resetDependenciesRevealed.Preconditions = preconditions;
            resetDependenciesRevealed.SetEffects(effects);

            return(resetDependenciesRevealed);
        }
Ejemplo n.º 4
0
        public void AddHidden(CompoundFormula cf)
        {
            Domain.AddHidden(cf);

            HashSet <Predicate> hs = cf.GetAllPredicates();

            foreach (GroundedPredicate gp in hs)
            {
                m_lInitiallyUnknown.Add(gp.Canonical());
                GroundedPredicate gpCanonical = (GroundedPredicate)gp.Canonical();
                if (!m_dRelevantPredicates.ContainsKey(gpCanonical))
                {
                    m_dRelevantPredicates[gpCanonical] = new HashSet <GroundedPredicate>();
                }
                foreach (GroundedPredicate gpOther in hs)
                {
                    GroundedPredicate gpOtherCanonical = (GroundedPredicate)gpOther.Canonical();
                    if (gpOtherCanonical != gpCanonical)
                    {
                        m_dRelevantPredicates[gpCanonical].Add(gpOtherCanonical);
                    }
                }
            }

            m_lHidden.Add(cf);
        }
        private Action GetRevealedDummyDependencyAction(Agent agent)
        {
            Constant a           = mapAgentToConstant[agent];
            Action   dummyAction = new Action("reveal-dummy-dependency_" + a.Name);

            CompoundFormula preconditions = new CompoundFormula("and");


            GroundedPredicate revealedSomething = new GroundedPredicate("revealed-something");

            revealedSomething.AddConstant(a);

            Predicate notRevealedSomething = revealedSomething.Negate();

            preconditions.AddOperand(notRevealedSomething);
            PredicateFormula effects = new PredicateFormula(revealedSomething);

            foreach (Dependency dependency in agentsDependencies[agent])
            {
                GroundedPredicate revealedDependency = new GroundedPredicate("revealed");
                Constant          d = mapDependencyToConstant[dependency];
                revealedDependency.AddConstant(d);

                preconditions.AddOperand(revealedDependency);
            }

            dummyAction.Preconditions = preconditions;
            dummyAction.SetEffects(effects);

            return(dummyAction);
        }
Ejemplo n.º 6
0
        public static Predicate ReadFunctionExpression(CompoundExpression exp, Dictionary <string, string> dParameterNameToType, Domain d)
        {
            Constant c     = null;
            string   sName = exp.SubExpressions[0].ToString();

            if (exp.Type == "=")
            {
                GroundedPredicate gp = new GroundedPredicate("=");
                gp.AddConstant(new Constant("cost", "(total-cost)"));
                gp.AddConstant(new Constant("", "0"));
                return(gp);



                /*
                 * string sParam1 = exp.SubExpressions[0].ToString();
                 * string sParam2 = exp.SubExpressions[1].ToString();
                 * if (!dParameterNameToType.ContainsKey(sParam1))
                 *  throw new ArgumentException("First argument of = must be a parameter");
                 * ParameterizedPredicate pp = new ParameterizedPredicate("=");
                 * pp.AddParameter(new Parameter(dParameterNameToType[sParam1], sParam1));
                 * if (dParameterNameToType.ContainsKey(sParam2))
                 *  pp.AddParameter(new Parameter(dParameterNameToType[sParam2], sParam2));
                 * else
                 *  pp.AddParameter(new Constant(d.ConstantNameToType[sParam2], sParam2));
                 * return pp;*/

                /*
                 * Sag: I dont know what was the meaning of this code, but it was meant not to work. If = is given,
                 * dParameterNameToType will be null and then if (!dParameterNameToType.ContainsKey(sParam1)) will throw null exception.
                 * */
            }


            GroundedPredicate p      = new GroundedPredicate(exp.Type);
            double            dValue = 0.0;

            if (d.Functions.Contains(sName))
            {
                c = new Constant("Function", sName);
            }
            else
            {
                throw new ArgumentException("First argument of increase or decrease must be a function");
            }
            p.AddConstant(c);

            sName = exp.SubExpressions[1].ToString();
            if (double.TryParse(sName, out dValue))
            {
                c = new Constant("Number", sName);
            }
            else
            {
                throw new ArgumentException("Second argument of increase or decrease must be a number");
            }
            p.AddConstant(c);
            return(p);
        }
 private void InitializeAllRevealedNumberPredicates(List <Agent> m_agents)
 {
     foreach (Agent agent in m_agents)
     {
         GroundedPredicate revealedNumber = GetGroundedRevealedNumberOfDependencies(agent, num0Constant);
         revealedNumberOfDependenciesPredicates.Add(revealedNumber);
     }
 }
Ejemplo n.º 8
0
 public bool IsRelevantFor(GroundedPredicate gp, GroundedPredicate gpRelevant)
 {
     if (!m_dRelevantPredicates.ContainsKey((GroundedPredicate)gp.Canonical()))
     {
         return(false);
     }
     return(m_dRelevantPredicates[(GroundedPredicate)gp.Canonical()].Contains((GroundedPredicate)gpRelevant.Canonical()));
 }
Ejemplo n.º 9
0
 public HashSet <GroundedPredicate> GetRelevantPredicates(GroundedPredicate gp)
 {
     if (m_dRelevantPredicates.ContainsKey(gp))
     {
         return(m_dRelevantPredicates[gp]);
     }
     return(new HashSet <GroundedPredicate>());
 }
        private GroundedPredicate GetGroundedNextPredicate(Constant num1, Constant num2)
        {
            GroundedPredicate groundedNext = new GroundedPredicate(nextPredicateName);

            groundedNext.AddConstant(num1);
            groundedNext.AddConstant(num2);
            return(groundedNext);
        }
Ejemplo n.º 11
0
        private GroundedPredicate GetGroundedGoingSoloPredicate(Agent agent)
        {
            GroundedPredicate groundedGoingSolo = new GroundedPredicate(goingSoloPredicateName);
            Constant          a = mapAgentToConstant[agent];

            groundedGoingSolo.AddConstant(a);
            return(groundedGoingSolo);
        }
        private GroundedPredicate GetGroundedRevealedNumberOfDependencies(Agent agent, Constant numConstant)
        {
            Constant          a = mapAgentToConstant[agent];
            GroundedPredicate groundedRevealedNumberOfDependencies = new GroundedPredicate(revealedNumberOfDependenciesPredicateName);

            groundedRevealedNumberOfDependencies.AddConstant(a);
            groundedRevealedNumberOfDependencies.AddConstant(numConstant);
            return(groundedRevealedNumberOfDependencies);
        }
Ejemplo n.º 13
0
 public int GetPredicateIndex(GroundedPredicate gp)
 {
     if (!m_dMapPredicateToIndex.ContainsKey(gp))
     {
         m_dMapPredicateToIndex[gp] = m_lIndexToPredicate.Count;
         m_lIndexToPredicate.Add(gp);
     }
     return(m_dMapPredicateToIndex[gp]);
 }
Ejemplo n.º 14
0
        private Tuple <GroundedPredicate, List <Predicate> > GetGoingSoloPredicatesForAgent(Agent agent, List <Agent> m_agents)
        {
            GroundedPredicate agentGoingSolo          = GetGroundedGoingSoloPredicate(agent);
            List <Predicate>  otherAgentsNotGoingSolo = GetNotGoingSoloAgents(agent, m_agents, false);

            Tuple <GroundedPredicate, List <Predicate> > tuple = new Tuple <GroundedPredicate, List <Predicate> >(agentGoingSolo, otherAgentsNotGoingSolo);

            return(tuple);
        }
Ejemplo n.º 15
0
        public override bool IsTrue(IEnumerable <Predicate> lKnown, bool bContainsNegations)
        {
            if (Predicate == Domain.TRUE_PREDICATE)
            {
                return(true);
            }
            if (Predicate == Domain.FALSE_PREDICATE)
            {
                return(false);
            }
            if (Predicate.Name == "=" && Predicate is GroundedPredicate)
            {
                GroundedPredicate gp = (GroundedPredicate)Predicate;
                bool bIsSame         = gp.Constants[0].Equals(gp.Constants[1]);
                if (gp.Negation)
                {
                    return(!bIsSame);
                }
                return(bIsSame);
            }
            if (lKnown != null)
            {
                if (bContainsNegations)
                {
                    return(lKnown.Contains(Predicate));
                }
                else
                {
                    Predicate pCheck = Predicate;
                    if (Predicate.Negation)
                    {
                        pCheck = Predicate.Negate();
                    }

                    bool bContained = lKnown.Contains(pCheck);
                    if (!bContained && Predicate.Negation)
                    {
                        return(true);
                    }

                    if (bContained && !Predicate.Negation)
                    {
                        return(true);
                    }

                    return(false);
                }
            }
            return(false);
        }
        private List <GroundedPredicate> GetRevealedSomethingGroundedPredicates()
        {
            List <GroundedPredicate> revealedSomethingPredicates = new List <GroundedPredicate>();

            foreach (Constant a in agentsConstants)
            {
                GroundedPredicate revealedSomething = new GroundedPredicate("revealed-something");
                revealedSomething.AddConstant(a);

                revealedSomethingPredicates.Add(revealedSomething);
            }

            return(revealedSomethingPredicates);
        }
Ejemplo n.º 17
0
 private void AddEffects(Formula fEffects)
 {
     if (fEffects is PredicateFormula)
     {
         AddEffect(((PredicateFormula)fEffects).Predicate);
     }
     else
     {
         CompoundFormula cf = (CompoundFormula)fEffects;
         if (cf.Operator == "oneof" || cf.Operator == "or")//BUGBUG - should treat or differently
         {
             int iRandomIdx = RandomGenerator.Next(cf.Operands.Count);
             AddEffects(cf.Operands[iRandomIdx]);
             GroundedPredicate pChoice = new GroundedPredicate("Choice");
             pChoice.AddConstant(new Constant("ActionIndex", "a" + (Time - 1)));//time - 1 because this is the action that generated the state, hence its index is i-1
             pChoice.AddConstant(new Constant("ChoiceIndex", "c" + iRandomIdx));
             State s = this;
             while (s != null)
             {
                 s.m_lPredicates.Add(pChoice);
                 s = s.m_sPredecessor;
             }
         }
         else if (cf.Operator == "and")
         {
             foreach (Formula f in cf.Operands)
             {
                 if (f is PredicateFormula)
                 {
                     AddEffect(((PredicateFormula)f).Predicate);
                 }
                 else
                 {
                     AddEffects(f);
                 }
             }
         }
         else if (cf.Operator == "when")
         {
             if (m_sPredecessor.Contains(cf.Operands[0]))
             {
                 AddEffects(cf.Operands[1]);
             }
         }
         else
         {
             throw new NotImplementedException();
         }
     }
 }
Ejemplo n.º 18
0
        private static GroundedPredicate ReadGroundedPredicate(CompoundExpression exp, Domain d)
        {
            GroundedPredicate gp = new GroundedPredicate(exp.Type);
            int      iExpression = 0;
            Constant c           = null;
            string   sName       = "";

            for (iExpression = 0; iExpression < exp.SubExpressions.Count; iExpression++)
            {
                sName = exp.SubExpressions[iExpression].ToString();
                c     = d.GetConstant(sName);
                gp.AddConstant(c);
            }
            return(gp);
        }
        /*
         * private List<GroundedPredicate> GetRevealedSomethingGroundedPredicates()
         * {
         *  List<GroundedPredicate> revealedSomethingPredicates = new List<GroundedPredicate>();
         *  foreach(Constant a in agentsConstants)
         *  {
         *      GroundedPredicate revealedSomething = new GroundedPredicate("revealed-something");
         *      revealedSomething.AddConstant(a);
         *
         *      revealedSomethingPredicates.Add(revealedSomething);
         *  }
         *
         *  return revealedSomethingPredicates;
         * }
         */

        private List <GroundedPredicate> GetBelongsToGroundedPredicates()
        {
            List <GroundedPredicate> belongsToPredicates = new List <GroundedPredicate>();

            foreach (Tuple <Dependency, Agent> tuple in belongsToList)
            {
                Constant          d         = mapDependencyToConstant[tuple.Item1];
                Constant          a         = mapAgentToConstant[tuple.Item2];
                GroundedPredicate belongsTo = new GroundedPredicate("belongs-to");
                belongsTo.AddConstant(d);
                belongsTo.AddConstant(a);

                belongsToPredicates.Add(belongsTo);
            }

            return(belongsToPredicates);
        }
Ejemplo n.º 20
0
        private List <Predicate> GetNotGoingSoloAgents(Agent agent, List <Agent> m_agents, bool allAgents)
        {
            //allAgents = True --> returns notGoingSolo for all agents in m_agents
            //allAgents = False --> returns notGoingSolo for all agents in m_agents but the specified agent
            List <Predicate> otherAgentsNotGoingSolo = new List <Predicate>();

            foreach (Agent otherAgent in m_agents)
            {
                if (allAgents || agent != otherAgent)
                {
                    GroundedPredicate otherAgentGoingSolo         = GetGroundedGoingSoloPredicate(otherAgent);
                    Predicate         negationOtherAgentGoingSolo = otherAgentGoingSolo.Negate();
                    otherAgentsNotGoingSolo.Add(negationOtherAgentGoingSolo);
                }
            }
            return(otherAgentsNotGoingSolo);
        }
Ejemplo n.º 21
0
        private void AddEffect(Predicate pEffect)
        {
            if (pEffect == Domain.FALSE_PREDICATE)
            {
                Debug.WriteLine("BUGBUG");
            }
            if (Problem.Domain.IsFunctionExpression(pEffect.Name))
            {
                GroundedPredicate gpIncreaseDecrease = (GroundedPredicate)pEffect;
                double            dPreviousValue     = m_sPredecessor.FunctionValues[gpIncreaseDecrease.Constants[0].Name];
                double            dDiff     = double.Parse(gpIncreaseDecrease.Constants[1].Name);
                double            dNewValue = double.NaN;
                if (gpIncreaseDecrease.Name.ToLower() == "increase")
                {
                    dNewValue = dPreviousValue + dDiff;
                }
                else if (gpIncreaseDecrease.Name.ToLower() == "decrease")
                {
                    dNewValue = dPreviousValue + dDiff;
                }
                else
                {
                    throw new NotImplementedException();
                }
                FunctionValues[gpIncreaseDecrease.Constants[0].Name] = dNewValue;
            }
            else if (!m_lPredicates.Contains(pEffect))
            {
                Predicate pNegateEffect = pEffect.Negate();
                if (m_lPredicates.Contains(pNegateEffect))
                {
                    //Debug.WriteLine("Removing " + pNegateEffect);
                    m_lPredicates.Remove(pNegateEffect);
                }

                /*
                 * if (!pEffect.Negation)
                 * {
                 *  //Debug.WriteLine("Adding " + pEffect);
                 *  m_lPredicates.Add(pEffect);
                 * }
                 * */
                m_lPredicates.Add(pEffect);//we are maintaining complete state information
            }
        }
Ejemplo n.º 22
0
 public override Formula Ground(Dictionary <string, Constant> dBindings)
 {
     if (Predicate is ParameterizedPredicate)
     {
         ParameterizedPredicate ppred = (ParameterizedPredicate)Predicate;
         GroundedPredicate      gpred = ppred.Ground(dBindings);
         return(new PredicateFormula(gpred));
     }
     if (Predicate is KnowPredicate)
     {
         KnowPredicate     kp    = (KnowPredicate)Predicate;
         GroundedPredicate gpred = kp.Ground(dBindings);
         return(new PredicateFormula(gpred));
     }
     if (Predicate is KnowGivenPredicate)
     {
         throw new NotImplementedException();
     }
     return(this);
 }
        private void InitializeAllNumberConstants()
        {
            Constant prevNum = null;

            for (int i = 0; i <= maxAmountOfDependencies; i++)
            {
                Constant currNum = new Constant(numberParameterType, numberParameterType + i);
                numberConstants.Add(currNum);
                if (i == 0)
                {
                    num0Constant = currNum;
                }
                else // i > 0
                {
                    //create a next predicate to indicate that we are bigger than the previous number
                    GroundedPredicate nextPredicate = GetGroundedNextPredicate(prevNum, currNum);
                    nextPredicates.Add(nextPredicate);
                }
                prevNum = currNum;
            }
        }
Ejemplo n.º 24
0
        private string GenerateKnowGivenLine(GroundedPredicate gp, string sTag, bool bKnowWhether)
        {
            string sKP = "";

            if (bKnowWhether)
            {
                sKP = "(KWGiven" + gp.Name;
            }
            else
            {
                if (SDRPlanner.Translation == SDRPlanner.Translations.SDR)
                {
                    sKP = "(KGiven" + gp.Name;
                }
                else
                {
                    sKP = "(Given" + gp.Name;
                }
            }
            foreach (Constant c in gp.Constants)
            {
                sKP += " " + c.Name;
            }

            sKP += " " + sTag;

            if (SDRPlanner.Translation == SDRPlanner.Translations.SDR)
            {
                if (gp.Negation)
                {
                    sKP += " " + Domain.FALSE_VALUE;
                }
                else
                {
                    sKP += " " + Domain.TRUE_VALUE;
                }
            }

            return(sKP + ")");
        }
Ejemplo n.º 25
0
        public void AddTime(int iMaxTimeLength)
        {
            GroundedPredicate gp;

            // add time adjucacny.. e.g. next-time t1 t2
            for (int i = 1; i < iMaxTimeLength; i++)
            {
                gp = new GroundedPredicate("next-time");
                gp.Constants.Add(new Constant("time", "t" + i));
                gp.Constants.Add(new Constant("time", "t" + (i + 1)));
                AddKnown(gp);
            }
            // Add infinite time.
            gp = new GroundedPredicate("next-time");
            gp.Constants.Add(new Constant("time", "t" + iMaxTimeLength));
            gp.Constants.Add(new Constant("time", "t" + iMaxTimeLength));
            AddKnown(gp);

            gp = new GroundedPredicate("current-time");
            gp.Constants.Add(new Constant("time", "t1"));
            AddKnown(gp);
        }
Ejemplo n.º 26
0
        private void ConvertToSingleAgentProblem()
        {
            /*foreach (var otherAgent in agents)
             * {
             *  if (otherAgent.Name != agent.Name)
             *  {
             *      RemoveAgentFromDomain(domain, otherAgent);
             *      //problem.RemoveConstant(otherAgent);
             *  }
             * }*/

            // Currently A1 plays
            GroundedPredicate activeAgentPredicate = new GroundedPredicate("active-agent");

            activeAgentPredicate.AddConstant(new Constant(m_AgentDomain.AgentCallsign, m_ActiveAgent.Name));
            m_AgentProblem.AddKnown(activeAgentPredicate);


            ParameterizedPredicate activeAgentParamPredicate = new ParameterizedPredicate("active-agent");
            Parameter pIsAgent = new Parameter(m_AgentDomain.AgentCallsign, "?a");

            activeAgentParamPredicate.AddParameter(pIsAgent);
            m_AgentDomain.AddPredicate(activeAgentParamPredicate);

            ParameterizedPredicate activeAgentParamPredicateJoint = new ParameterizedPredicate("active-agent");
            Parameter pIsAgentJoint = new Parameter(m_AgentDomain.AgentCallsign, "?a1");

            activeAgentParamPredicateJoint.AddParameter(pIsAgentJoint);


            foreach (var action in m_AgentDomain.Actions)
            {
                Action originalAction = action.Clone();

                if (action.Preconditions.ContainsParameter(pIsAgent) || action.Preconditions.ContainsParameter(pIsAgentJoint))
                {
                    if (action.Preconditions.CountAgents(m_AgentDomain.AgentCallsign) > 1)
                    {
                        // Joint Action
                        ParameterizedPredicate paramPredicateAgentAt = new ParameterizedPredicate("agent-at");
                        paramPredicateAgentAt.AddParameter(new Parameter(m_AgentDomain.AgentCallsign, "?a2"));
                        paramPredicateAgentAt.AddParameter(new Parameter("pos", "?start"));
                        action.Preconditions.RemovePredicate(paramPredicateAgentAt);


                        // Joint Action Disaster site
                        ParameterizedPredicate paramPredicateIn = new ParameterizedPredicate("in");
                        paramPredicateIn.AddParameter(new Parameter(m_AgentDomain.AgentCallsign, "?a2"));
                        paramPredicateIn.AddParameter(new Parameter("location", "?r1"));
                        action.Preconditions.RemovePredicate(paramPredicateIn);

                        action.Preconditions.AddPredicate(activeAgentParamPredicateJoint);
                    }
                    else
                    {
                        CompoundFormula newcf = new CompoundFormula("and");
                        newcf.SimpleAddOperand(action.Preconditions);
                        newcf.SimpleAddOperand(activeAgentParamPredicate);
                        action.Preconditions = newcf;
                    }
                }
                action.OriginalActionBeforeRemovingAgent = originalAction;
            }
        }
Ejemplo n.º 27
0
        private void AddCollabActionReq(out List <Action> exctractedActions)
        {
            exctractedActions = new List <Action>();
            if (m_ReqCollabActions == null || m_ReqCollabActions.Count == 0)
            {
                return;
            }

            // If there are collaborative constraints - remove the general action of join push.
            // TODO in future work - consider the case if you allow a general joint action push - the agent will be able to
            // activate new joint pushes before the constraint joint push from other agent - and by that he might create for
            //himself the ability to use the artifitial joint push by pushing earlier the big box
            //
            // For example - constraint joint push send to be activated at t4
            // +------------+
            // | B0, a0, a1 | B0 is an heavy box
            // +------------+
            //
            // Iteration 1:
            // a1 plan : 1. Observe big box -->(t) 2. No-op               --> 3. No-op --> 4. Joint-Push (with a1, new)
            //
            // Iteration 2:
            // a2 plan : 1. Observe big box -->(t) 2. Joint-Push t2 (new) --> 3. No-op --> 4. Art-Joint-Push
            //                                 (f) 2. No-op               --> 3. No-op --> 4. Art-Joint-Push

            // Until then -- > remove general collaborative action
            HashSet <string> JointActionsUsed = new HashSet <string>();

            foreach (var reqAction in m_ReqCollabActions)
            {
                JointActionsUsed.Add(reqAction.GetOperationName());
            }
            if (JointActionsUsed.Count > 1)
            {
                // Multiple joint actions type is not yet supported!
                throw new Exception();
            }
            else
            {
                if (JointActionsUsed.Count == 1)
                {
                    // Remove general joint action of the same name
                    string jointActionName       = JointActionsUsed.ElementAt(0);
                    Action generalActionToRemove = null;
                    foreach (var item in m_AgentDomain.Actions)
                    {
                        if (item.GetOperationName() == jointActionName)
                        {
                            generalActionToRemove = item;
                        }
                    }
                    if (generalActionToRemove != null)
                    {
                        m_AgentDomain.Actions.Remove(generalActionToRemove);
                        exctractedActions.Add(generalActionToRemove);
                    }
                }
            }


            // Add the notion of sub goals to the domain.
            m_AgentDomain.AddPredicate("sub-goal", "?g", "aGoal");

            // Count the number of artifitial goals.
            int artGoals = 0;

            // For each required action that needs attention:
            foreach (var reqAction in m_ReqCollabActions)
            {
                // Create sub-goal for this action
                string            predicateName = "sub-goal" + (artGoals++);
                GroundedPredicate gp            = new GroundedPredicate("sub-goal");
                gp.AddConstant(new Constant("aGoal", predicateName));
                m_AgentDomain.AddConstant("aGoal", predicateName);
                // Update this goal to the domain and problem;
                m_ActiveGoals.Add(gp);
                // Let it be known that this goal has not been achieved yet
                m_AgentProblem.AddKnown(gp.Negate());
                // This action now achieves this goal
                reqAction.AddEffect(gp);
                // OK, action is ready. add it to the set of actions
                m_AgentDomain.AddAction(reqAction);

                // We also need to create a counter-action that can be used in cases in which the previous action
                // cannot be used. - only when the agent observes that

                Action counterAction = new Action("art-" + reqAction.Name);

                Formula cgf = reqAction.Preconditions.GetUnknownPredicates(m_AgentDomain.m_lObservable);
                counterAction.Preconditions = cgf.Negate(true);
                //counterAction.Preconditions.AddTime
                //counterAction.Preconditions = counterAction.Preconditions.AddTime(reqAction.GetTime());
                counterAction.AddEffect(gp);
                //Formula cf = reqAction.Effects.Clone();
                //cf.RemoveTime();
                //counterAction.Effects = cf;
                //counterAction.AddEffect(reqAction.Effects);
                m_AgentDomain.AddAction(counterAction);
            }
        }
        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];

                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;
                     * }
                     */
                    if (!action.isPublic)
                    {
                        //if it is a private action, just use it as is...
                        allActions.Add(action);
                        continue;
                    }

                    List <Dependency> dependenciesInEffect = action2DependenciesInItsEffects[action];

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

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

            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.ToLower()))
                {
                    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;
        }
Ejemplo n.º 29
0
        private void GetApplicableEffects(Formula fEffects, HashSet <Predicate> lAdd, HashSet <Predicate> lDelete)
        {
            if (fEffects is PredicateFormula)
            {
                Predicate p = ((PredicateFormula)fEffects).Predicate;
                if (p.Negation)
                {
                    lDelete.Add(p);
                }
                else
                {
                    lAdd.Add(p);
                }
            }
            else if (fEffects is ProbabilisticFormula)
            {
                ProbabilisticFormula pf = (ProbabilisticFormula)fEffects;
                double dRand            = RandomGenerator.NextDouble();
                double dInitialRand     = dRand;
                int    iOption          = 0;
                while (iOption < pf.Options.Count && dRand > 0)
                {
                    dRand -= pf.Probabilities[iOption];
                    iOption++;
                }
                if (dRand < 0.01)
                {
                    iOption--;

                    GetApplicableEffects(pf.Options[iOption], lAdd, lDelete);
                }
                else //the no-op option was chosen
                {
                    iOption = -1;
                }
                GroundedPredicate pChoice = new GroundedPredicate("Choice");
                pChoice.AddConstant(new Constant("ActionIndex", "a" + Time));
                pChoice.AddConstant(new Constant("ChoiceIndex", "c" + ChoiceCount + "." + iOption));
                ChoiceCount++;
                State s = this;
                while (s != null)
                {
                    s.m_lPredicates.Add(pChoice);
                    s = s.m_sPredecessor;
                }
            }
            else
            {
                CompoundFormula cf = (CompoundFormula)fEffects;
                if (cf.Operator == "oneof" || cf.Operator == "or")//BUGBUG - should treat or differently
                {
                    int iRandomIdx = RandomGenerator.Next(cf.Operands.Count);
                    GetApplicableEffects(cf.Operands[iRandomIdx], lAdd, lDelete);
                    GroundedPredicate pChoice = new GroundedPredicate("Choice");
                    pChoice.AddConstant(new Constant("ActionIndex", "a" + Time));
                    pChoice.AddConstant(new Constant("ChoiceIndex", "c" + ChoiceCount + "." + iRandomIdx));
                    ChoiceCount++;
                    State s = this;
                    while (s != null)
                    {
                        s.m_lPredicates.Add(pChoice);
                        s = s.m_sPredecessor;
                    }
                }
                else if (cf.Operator == "and")
                {
                    foreach (Formula f in cf.Operands)
                    {
                        GetApplicableEffects(f, lAdd, lDelete);
                    }
                }
                else if (cf.Operator == "when")
                {
                    if (Contains(cf.Operands[0]))
                    {
                        GetApplicableEffects(cf.Operands[1], lAdd, lDelete);
                    }
                }
                else if (cf is ParametrizedFormula)
                {
                    ParametrizedFormula pf = (ParametrizedFormula)cf;
                    foreach (Formula fNew in pf.Ground(Problem.Domain.Constants))
                    {
                        GetApplicableEffects(fNew, lAdd, lDelete);
                    }
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
        }
Ejemplo n.º 30
0
        private static Formula ReadPredicate(CompoundExpression exp, Dictionary <string, string> dParameterNameToType, bool bParametrized, Domain d)
        {
            Predicate p           = null;
            int       iExpression = 0;
            string    sName       = "";

            if (bParametrized)
            {
                p = new ParameterizedPredicate(exp.Type);
            }
            else
            {
                p = new GroundedPredicate(exp.Type);
            }
            bool bAllConstants = true;

            for (iExpression = 0; iExpression < exp.SubExpressions.Count; iExpression++)
            {
                sName = exp.SubExpressions[iExpression].ToString();
                if (bParametrized)
                {
                    Argument a = null;
                    if (sName.StartsWith("?"))
                    {
                        // if (!dParameterNameToType.ContainsKey(sName))
                        //     dParameterNameToType.Add(sName,)
                        a             = new Parameter(dParameterNameToType[sName], sName);
                        bAllConstants = false;
                    }
                    else
                    {
                        if (!d.ConstantNameToType.ContainsKey(sName))
                        {
                            d.ConstantNameToType.Add(sName, dParameterNameToType[sName]);
                            //throw new Exception("Predicate " + sName + " undefined");// SAGI co
                        }
                        a = new Constant(d.ConstantNameToType[sName], sName);
                    }
                    ((ParameterizedPredicate)p).AddParameter(a);
                }
                else
                {
                    try
                    {
                        Constant c = new Constant(d.ConstantNameToType[sName], sName);
                        ((GroundedPredicate)p).AddConstant(c);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine();
                    }
                }
            }
            if (bParametrized)
            {
                if (!MatchParametersToPredicateDeclaration((ParameterizedPredicate)p, d))
                {
                    throw new NotImplementedException();
                }
            }

            if (bParametrized && bAllConstants)
            {
                GroundedPredicate gp = new GroundedPredicate(p.Name);
                foreach (Constant c in ((ParameterizedPredicate)p).Parameters)
                {
                    gp.AddConstant(c);
                }
                p = gp;
            }


            PredicateFormula vf = new PredicateFormula(p);

            return(vf);
        }