Exemplo n.º 1
0
        /// <summary>
        /// Ajoute un prédicat au corps de la règle et lui octroie des arguments aléatoires entres constantes, variables libres ou liées.
        /// Si une constante est à ajouter, la règle finale doit correspondre à un ou plusieurs états de l'environnement.
        /// </summary>
        /// <param name="index">Index dans l'ensemble d'action.</param>
        /// <param name="actionSet">Ensemble d'action à traiter.</param>
        /// <param name="env">Environnement à prendre en compte.</param>
        /// <returns>Le classifieur fils muté, null si la mutation échoue.</returns>
        private Classifier AddAtom(int index, List <Classifier> actionSet, PerceivedEnvironnement env)
        {
            bool retry = false;

            Attribute newHead = ObjectCopier.Clone(actionSet)[index].rule.head;

            Attribute[] newBody = ObjectCopier.Clone(actionSet)[index].rule.body;
            Classifier  newCl   = null;

            List <string> availablePredicates = new List <string>();

            foreach (Attribute state in env.states)
            {
                if (!availablePredicates.Contains(state.name))
                {
                    availablePredicates.Add(state.name);
                }
            }


            Random rand         = new Random();
            string randAtomName = availablePredicates[rand.Next(availablePredicates.Count)];

            string[] randValues = new string[fo.statePredicateOptions[randAtomName].argsOptions.Count()];
            Dictionary <int, List <string> > constList = new Dictionary <int, List <string> >();

            int atomCount = 0;

            foreach (Attribute predicate in actionSet[index].rule.body)
            {
                if (predicate.name.Equals(randAtomName))
                {
                    atomCount++;
                }
            }

            if (atomCount <= fo.statePredicateOptions[randAtomName].max && actionSet[index].rule.body.Length < fo.maxPredicate)
            {
                for (int i = 0; i < randValues.Count(); i++)
                {
                    int accRand;
                    do
                    {
                        retry = false;
                        switch (fo.statePredicateOptions[randAtomName].argsOptions[i].argsMode[accRand = rand.Next(fo.statePredicateOptions[randAtomName].argsOptions[i].argsMode.Count())])
                        {
                        case ArgMode.CONST:
                            if (fo.statePredicateOptions[randAtomName].argsOptions[i].argType is ArgType.TOKEN)
                            {
                                if (!constList.ContainsKey(i))
                                {
                                    constList.Add(i, env.tokenOnBoard);
                                }
                            }
                            else
                            {
                                if (!constList.ContainsKey(i))
                                {
                                    constList.Add(i, boundVarList[fo.statePredicateOptions[randAtomName].argsOptions[i].argType].Keys.ToList());
                                }
                            }
                            break;

                        case ArgMode.VAR:
                            randValues[i] = fo.statePredicateOptions[randAtomName].argsOptions[i].argType.ToString() + varCount[fo.statePredicateOptions[randAtomName].argsOptions[i].argType];
                            varCount[fo.statePredicateOptions[randAtomName].argsOptions[i].argType]++;
                            break;

                        case ArgMode.BOUND:
                            Dictionary <ArgType, Dictionary <string, List <int[]> > > boundList = GetAllValues(ArgMode.BOUND, actionSet, index);
                            if (!boundList.ContainsKey(fo.statePredicateOptions[randAtomName].argsOptions[i].argType) ||
                                boundList[fo.statePredicateOptions[randAtomName].argsOptions[i].argType].Count == 0)
                            {
                                return(null);
                            }
                            string randBound = new List <string>(boundList[fo.statePredicateOptions[randAtomName].argsOptions[i].argType].Keys)[rand.Next(boundList[fo.statePredicateOptions[randAtomName].argsOptions[i].argType].Keys.Count)];
                            randValues[i] = randBound;
                            break;

                        default:
                            retry = true;
                            break;
                        }
                    } while (retry);
                }

                if (constList.Count != 0)
                {
                    AppDomainSetup ads = new AppDomainSetup();
                    ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
                    AppDomain             appDomain = AppDomain.CreateDomain("PrologScript", null, ads);
                    string                assembly  = Assembly.GetEntryAssembly().FullName;
                    MatchMarshalRefByType mmrbt     =
                        (MatchMarshalRefByType)appDomain.CreateInstanceAndUnwrap(assembly,
                                                                                 typeof(MatchMarshalRefByType).FullName);

                    List <HornClause> knowBase             = fo.knowledgeBase.ToList();
                    var assertResult                       = mmrbt.AssertEnvironnement(env, knowBase, boundVarList, fo);
                    Dictionary <string, int> usedPredicate = assertResult.Value.Value;
                    Dictionary <Classifier, List <Attribute> > usedClassifiers = new Dictionary <Classifier, List <Attribute> >();

                    Dictionary <Attribute, List <HornClause> > accMatchSet = new Dictionary <Attribute, List <HornClause> >();
                    List <Classifier> matchSetCount = new List <Classifier>();

                    List <Attribute> accMatchList = new List <Attribute>();

                    Dictionary <int, int> accIterators = new Dictionary <int, int>();
                    foreach (int i in constList.Keys)
                    {
                        accIterators.Add(i, 0);
                    }
                    bool endIterators = false;

                    int accIndex = fo.statePredicateOptions[randAtomName].argsOptions.Count();

                    while (!endIterators)
                    {
                        newHead = ObjectCopier.Clone(actionSet)[index].rule.head;
                        newBody = ObjectCopier.Clone(actionSet)[index].rule.body;

                        foreach (int i in constList.Keys)
                        {
                            randValues[i] = constList[i][accIterators[i]];
                        }

                        var acc = ObjectCopier.Clone(newBody).ToList();
                        acc.Add(new Attribute(randAtomName, randValues.ToArray(), fo.statePredicateOptions[randAtomName]));
                        newBody = acc.ToArray();
                        newCl   = new Classifier(currentTime, new HornClause(newHead, newBody.ToArray()), fo);

                        if ((accMatchList = mmrbt.GetClassifierMatchList(newCl, env)).Count != 0)
                        {
                            matchSetCount.Add(newCl);
                        }

                        for (int i = 0; i <= constList.Last().Key; i++)
                        {
                            if (constList.Keys.Contains(i))
                            {
                                accIterators[i]++;
                                while (i <= constList.Last().Key&& (!constList.Keys.Contains(i) || accIterators[i] >= constList[i].Count))
                                {
                                    if (constList.Keys.Contains(i))
                                    {
                                        accIterators[i] = 0;
                                    }
                                    i++;
                                }

                                if (accIterators.Values.Sum() == 0 || accIterators[i] < constList[i].Count())
                                {
                                    if (accIterators.Values.Sum() == 0)
                                    {
                                        endIterators = true;
                                    }
                                    break;
                                }
                            }
                        }
                    }

                    mmrbt.AbolishEnvironnement(usedPredicate);
                    AppDomain.Unload(appDomain);
                    if (matchSetCount.Count == 0)
                    {
                        return(null);
                    }
                    else
                    {
                        return(matchSetCount[rand.Next(matchSetCount.Count)]);
                    }
                }

                List <Attribute> predicateList = new List <Attribute>(actionSet[index].rule.body.ToArray());
                predicateList.Add(new Attribute(randAtomName, randValues, fo.statePredicateOptions[randAtomName]));
                Attribute[] newRule = predicateList.ToArray();
                return(new Classifier(currentTime, new HornClause(actionSet[index].rule.head, newRule), fo));
            }
            return(null);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Remplace chaque occurence d'une variable aléatoirement choisi par une constante, tel que la règle final correspond à un ou plusieurs états de l'environnement.
        /// Echoue si une variable ne peut être remplacé en constante ou que la règle ne correspond à un ou plusieurs états.
        /// </summary>
        /// <param name="index">Index dans l'ensemble d'action.</param>
        /// <param name="actionSet">Ensemble d'action à traiter.</param>
        /// <param name="env">Environnement à prendre en compte.</param>
        /// <returns>Le classifieur fils muté, null si la mutation échoue.</returns>
        private Classifier VarToConst(int index, List <Classifier> actionSet, PerceivedEnvironnement env)
        {
            AppDomainSetup ads = new AppDomainSetup();

            ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
            AppDomain             appDomain = AppDomain.CreateDomain("PrologScript", null, ads);
            string                assembly  = Assembly.GetEntryAssembly().FullName;
            MatchMarshalRefByType mmrbt     =
                (MatchMarshalRefByType)appDomain.CreateInstanceAndUnwrap(assembly,
                                                                         typeof(MatchMarshalRefByType).FullName);

            List <HornClause> knowBase             = fo.knowledgeBase.ToList();
            var assertResult                       = mmrbt.AssertEnvironnement(env, knowBase, boundVarList, fo);
            Dictionary <string, int> usedPredicate = assertResult.Value.Value;
            Dictionary <Classifier, List <Attribute> > usedClassifiers = new Dictionary <Classifier, List <Attribute> >();

            Dictionary <Attribute, List <HornClause> > accMatchSet = new Dictionary <Attribute, List <HornClause> >();
            List <Classifier> matchSetCount = new List <Classifier>();

            bool isMatching = false;

            List <Classifier> actSet = ObjectCopier.Clone(actionSet);
            Random            rand   = new Random();
            Dictionary <ArgType, Dictionary <string, List <int[]> > > varList = GetAllValues(ArgMode.VAR, actionSet, index);

            if (varList.Count != 0)
            {
                ArgType randArgType = varList.Keys.ToArray()[rand.Next(varList.Keys.Count)];;
                string  randVar     = varList[randArgType].Keys.ToArray()[rand.Next(varList[randArgType].Count)];
                if (varList[randArgType][randVar].Count != 0)
                {
                    Attribute   newHead = actSet[index].rule.head;
                    Attribute[] newBody = actSet[index].rule.body;

                    if (randArgType is ArgType.TOKEN)
                    {
                        foreach (string constVar in env.tokenOnBoard)
                        {
                            foreach (int[] argIndex in varList[randArgType][randVar])
                            {
                                if (argIndex[0] == -1)
                                {
                                    if (newHead.predOp.argsOptions[argIndex[1]].argsMode.Contains(ArgMode.CONST))
                                    {
                                        newHead.values[argIndex[1]] = constVar;
                                    }
                                }
                                else
                                {
                                    if (newBody[argIndex[0]].predOp.argsOptions[argIndex[1]].argsMode.Contains(ArgMode.CONST))
                                    {
                                        newBody[argIndex[0]].values[argIndex[1]] = constVar;
                                    }
                                }
                            }

                            Classifier newCl     = new Classifier(currentTime, new HornClause(ObjectCopier.Clone(newHead), ObjectCopier.Clone(newBody)), fo);
                            string[]   accValues = newHead.values.ToArray() as string[];

                            List <Attribute> actionMatchList = mmrbt.GetClassifierMatchList(newCl, env);
                            if (actionMatchList.Count != 0)
                            {
                                matchSetCount.Add(newCl);
                            }
                        }
                    }

                    else
                    {
                        foreach (string constVar in boundVarList[randArgType].Keys)
                        {
                            foreach (int[] argIndex in varList[randArgType][randVar])
                            {
                                if (argIndex[0] == -1)
                                {
                                    if (newHead.predOp.argsOptions[argIndex[1]].argsMode.Contains(ArgMode.CONST))
                                    {
                                        newHead.values[argIndex[1]] = constVar;
                                    }
                                }
                                else
                                {
                                    if (newBody[argIndex[0]].predOp.argsOptions[argIndex[1]].argsMode.Contains(ArgMode.CONST))
                                    {
                                        newBody[argIndex[0]].values[argIndex[1]] = constVar;
                                    }
                                }
                            }

                            Classifier newCl     = new Classifier(currentTime, new HornClause(ObjectCopier.Clone(newHead), ObjectCopier.Clone(newBody)), fo);
                            string[]   accValues = newHead.values.ToArray() as string[];

                            List <Attribute> actionMatchList = mmrbt.GetClassifierMatchList(newCl, env);
                            if (actionMatchList.Count != 0)
                            {
                                matchSetCount.Add(newCl);
                            }
                        }
                    }

                    mmrbt.AbolishEnvironnement(usedPredicate);
                    AppDomain.Unload(appDomain);

                    if (matchSetCount.Count != 0)
                    {
                        return(matchSetCount[rand.Next(matchSetCount.Count)]);
                    }
                }
            }
            return(null);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Récupère tous les classifieurs correspondant à la situation actuelle de l'environnement.
        /// Si il n'y a pas assez classifieurs répondant à ce critère, en génère à partir de l'environnement.
        /// </summary>
        public void GetMatchSet()
        {
            AppDomainSetup ads = new AppDomainSetup();

            ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
            AppDomain             appDomain = AppDomain.CreateDomain("PrologScript", null, ads);
            string                assembly  = Assembly.GetEntryAssembly().FullName;
            MatchMarshalRefByType mmrbt     =
                (MatchMarshalRefByType)appDomain.CreateInstanceAndUnwrap(assembly,
                                                                         typeof(MatchMarshalRefByType).FullName);

            List <HornClause> knowBase             = fo.knowledgeBase.ToList();
            var assertResult                       = mmrbt.AssertEnvironnement(env, knowBase, boundVarList, fo);
            Dictionary <string, int> usedPredicate = assertResult.Value.Value;
            Dictionary <Classifier, List <Attribute> > usedClassifiers = new Dictionary <Classifier, List <Attribute> >();

            List <MatchingThread> matList = new List <MatchingThread>();
            List <Task>           threads = new List <Task>();

            Dictionary <Attribute, List <HornClause> > accMatchSet = new Dictionary <Attribute, List <HornClause> >();
            List <Classifier> matchSetCount = new List <Classifier>();

            bool isMatching = false;

            foreach (Attribute delState in assertResult.Value.Key)
            {
                if (env.states.Contains(delState))
                {
                    env.states.Remove(delState);
                }
            }

            foreach (Attribute newState in assertResult.Key)
            {
                if (!env.states.Contains(newState))
                {
                    env.states.Add(newState);
                }
            }

            this.matchSet.Clear();
            while (MatchSetActionCount() < AvailableActionCount() + 1)
            {
                List <Classifier> checkSet = disjointList(popSet, matchSet);
                foreach (Classifier cl in checkSet)
                {
                    matList.Insert(0, new MatchingThread(cl, env, usedPredicate.Keys.ToArray(), mmrbt));
                    threads.Insert(0, new Task(matList[0].MatchingProcess));
                    threads[0].Start();

                    /*
                     * foreach (Attribute actionMatch in mmrbt.GetClassifierMatchList(cl, env))
                     * {
                     *  isMatching = true;
                     *  if (!this.matchSet.ContainsKey(actionMatch))
                     *      this.matchSet.Add(actionMatch, new List<Classifier>());
                     *  if(!this.matchSet[actionMatch].Contains(cl))
                     *      this.matchSet[actionMatch].Add(cl);
                     *
                     * }
                     * if (!isMatching)
                     *  this.matchSet[new Attribute("", new string[0], null)].Add(cl);
                     * isMatching = false;
                     */
                }

                foreach (Task thread in threads)
                {
                    try
                    {
                        thread.Wait();
                        thread.Dispose();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Erreur provenant de YieldProlog, relancement du thread YPThread.");
                        Console.WriteLine(e);
                        thread.Dispose();
                        Console.ReadKey();
                    }
                }


                foreach (MatchingThread mat in matList)
                {
                    foreach (KeyValuePair <Attribute, List <Classifier> > actionClassifiers in mat.matchSet)
                    {
                        if (!this.matchSet.ContainsKey(actionClassifiers.Key))
                        {
                            this.matchSet.Add(actionClassifiers.Key, new List <Classifier>());
                            if (!accMatchSet.ContainsKey(actionClassifiers.Key))
                            {
                                accMatchSet.Add(actionClassifiers.Key, new List <HornClause>());
                            }
                        }

                        foreach (Classifier cl in actionClassifiers.Value)
                        {
                            if (!accMatchSet[actionClassifiers.Key].Contains(cl.rule))
                            {
                                if (!matchSetCount.Contains(cl))
                                {
                                    matchSetCount.Add(cl);
                                }
                                if (!matchSet[actionClassifiers.Key].Contains(cl))
                                {
                                    this.matchSet[actionClassifiers.Key].Add(cl);
                                }
                                if (!accMatchSet[actionClassifiers.Key].Contains(cl.rule))
                                {
                                    accMatchSet[actionClassifiers.Key].Add(cl.rule);
                                }
                            }
                        }
                    }
                }

                if (MatchSetActionCount() < AvailableActionCount() + 1)
                {
                    HornClause newRule;
                    if ((newRule = GenerateCoveringRule()) != null)
                    {
                        popSet.Add(new Classifier(currentTime, newRule, fo));
                    }
                    DeleteFromPopulation();
                }
                else
                {
                    break;
                }
            }

            foreach (Attribute key in matchSet.Keys.ToList())
            {
                if (matchSet[key].Count == 0)
                {
                    matchSet.Remove(key);
                }
            }
            matchSet.Remove(new Attribute("", new string[0], null));
            mmrbt.AbolishEnvironnement(usedPredicate);
            AppDomain.Unload(appDomain);
            Console.WriteLine("Current popSet count : " + popSet.Count);
            Console.WriteLine("Current matchSet count : " + matchSetCount.Count + "for" + matchSet.Keys.Count + "actions");
            Console.WriteLine("Current actions count : " + matchSet.Keys.Count);
        }