Esempio n. 1
0
        public NWSEGenome createOriginGenome(Session session)
        {
            NWSEGenome genome = new NWSEGenome();

            //生成感受器
            this.createReceptors(genome, session);


            //生成缺省推理节点
            int[] varids = { genome["d1"].Id, genome["d2"].Id,
                             genome["d3"].Id, genome["d4"].Id,
                             genome["d5"].Id, genome["d6"].Id,
                             genome["b"].Id,
                             genome["heading"].Id };
            for (int i = 0; i < varids.Length; i++)
            {
                List <int> conditions = new List <int>();
                conditions.Add(genome["_a2"].Id);
                List <int> variables = new List <int>();
                variables.Add(varids[i]);
                InferenceGene inferenceGene = new InferenceGene(genome, 1, conditions, variables);
                inferenceGene.Generation = session.Generation;
                inferenceGene.Id         = Session.idGenerator.getGeneId(inferenceGene);
                genome.inferenceGenes.Add(inferenceGene);
            }

            genome.id         = Session.idGenerator.getGenomeId();
            genome.generation = 1;
            genome.computeNodeDepth();
            return(genome);
        }
Esempio n. 2
0
        public static HandlerGene parse(NWSEGenome genome, String s)
        {
            int    t1   = s.IndexOf("info");
            int    t2   = s.IndexOf(":", t1 + 1);
            int    t3   = s.IndexOf(";", t2 + 1);
            String info = s.Substring(t2 + 1, t3 - t2 - 1);

            //解析param部分
            t1 = s.IndexOf("function");
            t2 = s.IndexOf("=", t1 + 1);
            t3 = s.IndexOf(";", t2 + 1);
            String function = s.Substring(t2 + 1, t3 - t2 - 1).Trim();

            t1 = s.IndexOf("inputs");
            t2 = s.IndexOf("=", t1 + 1);
            t3 = s.IndexOf(";", t2 + 1);
            String     inputstr = s.Substring(t2 + 1, t3 - t2 - 1).Trim();
            List <int> inputids = Utility.parse(inputstr).ConvertAll(v => (int)v);
            //解析info
            HandlerGene gene = new HandlerGene(genome, function, inputids, null);

            gene.parseInfo(info);
            //解析参数
            t1 = s.IndexOf("param");
            t2 = s.IndexOf("=", t1 + 1);
            String paramtext = s.Substring(t2 + 1, s.Length - t2 - 1).Trim();

            gene.param = Utility.parse(paramtext);

            return(gene);
        }
Esempio n. 3
0
        public NWSEGenome createSimpleGenome(Session session)
        {
            NWSEGenome genome = new NWSEGenome();

            //生成感受器
            this.createReceptors(genome, session);


            //生成缺省推理节点
            List <int> conditions = new List <int>();
            List <int> variables  = new List <int>();

            conditions.Add(genome["heading"].Id);
            conditions.Add(genome["_a2"].Id);
            variables.Add(genome["heading"].Id);
            InferenceGene inferenceGene = new InferenceGene(genome, 1, conditions, variables);

            inferenceGene.Generation = session.Generation;
            inferenceGene.Id         = Session.idGenerator.getGeneId(inferenceGene);
            genome.inferenceGenes.Add(inferenceGene);

            genome.id         = Session.idGenerator.getGenomeId();
            genome.generation = 1;
            genome.computeNodeDepth();
            return(genome);
        }
Esempio n. 4
0
        /// <summary>
        /// 交叉
        /// </summary>
        /// <param name="g1"></param>
        /// <param name="g2"></param>
        /// <returns></returns>
        public static NWSEGenome crossover(NWSEGenome g1, NWSEGenome g2, Session session)
        {
            NWSEGenome genome = g1.clone();

            genome.generation = session.Generation;

            List <InferenceGene> infGenes = new List <InferenceGene>(g2.inferenceGenes);
            int count = 0;

            for (int i = 0; i < 8; i++)
            {
                int           index     = rng.Next(0, infGenes.Count);
                InferenceGene g2InfGene = infGenes[index].clone <InferenceGene>();
                InferenceGene g1InfGene = (InferenceGene)genome[g2InfGene.Id];
                if (g1InfGene == null)
                {
                    continue;
                }
                int d = genome.inferenceGenes.IndexOf(g1InfGene);
                genome.inferenceGenes[d] = g2InfGene;
                count += 1;
                if (count >= 3)
                {
                    break;
                }
            }

            genome.computeNodeDepth();
            genome.id = Session.idGenerator.getGenomeId();
            return(genome);
        }
Esempio n. 5
0
        public NWSEGenome createFullGenome(Session session)
        {
            NWSEGenome genome = new NWSEGenome();

            //生成感受器
            this.createReceptors(genome, session);

            InferenceGene inferenceGene = null;
            //生成推理节点:1
            List <int> conditions = new List <int>();
            List <int> variables  = new List <int>();

            conditions.Add(genome["heading"].Id);
            conditions.Add(genome["_a2"].Id);
            variables.Add(genome["heading"].Id);
            inferenceGene            = new InferenceGene(genome, 1, conditions, variables);
            inferenceGene.Generation = session.Generation;
            inferenceGene.Id         = Session.idGenerator.getGeneId(inferenceGene);
            genome.inferenceGenes.Add(inferenceGene);

            conditions = new List <int>();
            conditions.Add(genome["d1"].Id);
            conditions.Add(genome["d2"].Id);
            conditions.Add(genome["d3"].Id);
            conditions.Add(genome["d4"].Id);
            conditions.Add(genome["d5"].Id);
            conditions.Add(genome["d6"].Id);
            conditions.Add(genome["heading"].Id);
            conditions.Add(genome["_a2"].Id);

            int[] varIds = { genome["d1"].Id, genome["d2"].Id,
                             genome["d3"].Id, genome["d4"].Id,
                             genome["d5"].Id, genome["d6"].Id,
                             //["g1"].Id, genome["gd"].Id,
                             //genome["g3"].Id, genome["g4"].Id,
                             //genome["b"].Id,genome["heading"].Id
            };

            //生成推理节点
            for (int i = 0; i < varIds.Length; i++)
            {
                inferenceGene            = new InferenceGene(genome, 1, new List <int>(conditions), new int[] { varIds[i] }.ToList());
                inferenceGene.Generation = session.Generation;
                inferenceGene.Id         = Session.idGenerator.getGeneId(inferenceGene);
                genome.inferenceGenes.Add(inferenceGene);
            }

            inferenceGene = new InferenceGene(genome, 1,
                                              new int[] { genome["d3"].Id, genome["heading"].Id, genome["_a2"].Id }.ToList(),
                                              new int[] { genome["b"].Id }.ToList());
            inferenceGene.Generation = session.Generation;
            inferenceGene.Id         = Session.idGenerator.getGeneId(inferenceGene);
            genome.inferenceGenes.Add(inferenceGene);


            genome.id         = Session.idGenerator.getGenomeId();
            genome.generation = 1;
            genome.computeNodeDepth();
            return(genome);
        }
Esempio n. 6
0
        public static NWSEGenome Parse(String str)
        {
            if (str == null || str.Trim() == "")
            {
                return(null);
            }
            List <String> s1 = str.Split(new String[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

            if (s1 == null || s1.Count <= 0)
            {
                return(null);
            }

            NWSEGenome genome = new NWSEGenome();

            genome.id = int.Parse(s1[0]);
            s1.RemoveAt(0);

            if (int.TryParse(s1[0], out genome.generation))
            {
                s1.RemoveAt(0);
            }

            foreach (String s in s1)
            {
                if (s == null || s.Trim() == "")
                {
                    continue;
                }
                if (s.StartsWith("ReceptorGene"))
                {
                    genome.receptorGenes.Add(ReceptorGene.parse(genome, s));
                }
                else if (s.StartsWith("HandlerGene"))
                {
                    genome.handlerGenes.Add(HandlerGene.parse(genome, s));
                }
                else if (s.StartsWith("InferenceGene"))
                {
                    genome.inferenceGenes.Add(InferenceGene.parse(genome, s));
                }
                else if (s.StartsWith("handlerSelectionProb"))
                {
                    int s2 = s.IndexOf("handlerSelectionProb");
                    s2 = s.IndexOf("=", s2 + 1);
                    String s3 = s.Substring(s2 + 1).Trim();
                    genome.handlerSelectionProb.Clear();
                    genome.handlerSelectionProb.AddRange(Utility.parse(s3));
                }
                else if (s.StartsWith("vaild"))
                {
                    String s2 = s.Substring(s.IndexOf("="));
                    genome.validInferenceGenes.Add(NodeGene.parseGene(genome, s2));
                }
            }

            genome.computeNodeDepth();
            return(genome);
        }
Esempio n. 7
0
 public HandlerGene(NWSEGenome genome, String function, List <int> inputs, params double[] ps) : base(genome)
 {
     this.function = function;
     this.inputs.AddRange(inputs);
     if (ps != null && ps.Length > 0)
     {
         param.AddRange(ps);
     }
 }
Esempio n. 8
0
        /// <summary>
        /// 判断两个染色体是否等价:如果处理器基因和推理基因完全一样的话(不包括可变异参数在内)
        /// </summary>
        /// <param name="genome"></param>
        /// <returns></returns>
        public bool equiv(NWSEGenome genome)
        {
            if (handlerGenes.Count != genome.handlerGenes.Count)
            {
                return(false);
            }

            for (int i = 0; i < handlerGenes.Count; i++)
            {
                for (int j = 0; j < genome.handlerGenes.Count; j++)
                {
                    if (!handlerGenes[i].equiv(genome.handlerGenes[j]))
                    {
                        return(false);
                    }
                }
            }

            if (genome.handlerGenes.Count != handlerGenes.Count)
            {
                return(false);
            }
            for (int i = 0; i < genome.handlerGenes.Count; i++)
            {
                if (handlerGenes.Exists(g => g.Id == genome.handlerGenes[i].Id))
                {
                    continue;
                }
                for (int j = 0; j < handlerGenes.Count; j++)
                {
                    if (!genome.handlerGenes[i].equiv(handlerGenes[j]))
                    {
                        return(false);
                    }
                }
            }

            if (inferenceGenes.Count != genome.inferenceGenes.Count)
            {
                return(false);
            }
            for (int i = 0; i < inferenceGenes.Count; i++)
            {
                for (int j = 0; j < genome.inferenceGenes.Count; j++)
                {
                    if (!inferenceGenes[i].equiv(genome.inferenceGenes[j]))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Esempio n. 9
0
        /// <summary>
        /// 克隆
        /// </summary>
        /// <returns></returns>
        public NWSEGenome clone()
        {
            NWSEGenome genome = new NWSEGenome();

            receptorGenes.ForEach(r => genome.receptorGenes.Add(r.clone <ReceptorGene>()));
            genome.handlerSelectionProb.Clear();
            genome.handlerSelectionProb.AddRange(handlerSelectionProb);
            handlerGenes.ForEach(h => genome.handlerGenes.Add(h.clone <HandlerGene>()));
            inferenceGenes.ForEach(i => genome.inferenceGenes.Add(i.clone <InferenceGene>()));

            validInferenceGenes.ForEach(vf => genome.validInferenceGenes.Add(vf.clone <NodeGene>()));

            return(genome);
        }
Esempio n. 10
0
        private List <ReceptorGene> createReceptors(NWSEGenome genome, Session session)
        {
            List <Configuration.Sensor> sensors = Session.GetConfiguration().agent.receptors.GetAllSensor();

            for (int i = 0; i < sensors.Count; i++)
            {
                ReceptorGene receptorGene = new ReceptorGene(genome);
                receptorGene.Cataory     = sensors[i].cataory;
                receptorGene.Generation  = session.Generation;
                receptorGene.Group       = sensors[i].group;
                receptorGene.Name        = sensors[i].name;
                receptorGene.Description = sensors[i].desc;
                receptorGene.Id          = session.GetIdGenerator().getGeneId(receptorGene);
                genome.receptorGenes.Add(receptorGene);
            }
            return(genome.receptorGenes);
        }
Esempio n. 11
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="genome">染色体</param>
 public EffectorGene(NWSEGenome genome) : base(genome)
 {
 }
Esempio n. 12
0
        public NWSEGenome createReabilityGenome(Session session)
        {
            NWSEGenome genome = new NWSEGenome();

            //生成感受器
            this.createReceptors(genome, session);

            InferenceGene inferenceGene = null;
            //生成推理节点:1
            List <int> conditions = new List <int>();
            List <int> variables  = new List <int>();

            conditions.Add(genome["heading"].Id);
            conditions.Add(genome["_a2"].Id);
            variables.Add(genome["heading"].Id);
            inferenceGene            = new InferenceGene(genome, 1, conditions, variables);
            inferenceGene.Generation = session.Generation;
            inferenceGene.Id         = Session.idGenerator.getGeneId(inferenceGene);
            genome.inferenceGenes.Add(inferenceGene);



            //生成推理节点:4
            int[] ids = new int[] { genome["d1"].Id, genome["d2"].Id,
                                    genome["d3"].Id, genome["d4"].Id,
                                    genome["d5"].Id, genome["d6"].Id };
            foreach (int did in ids)
            {
                conditions = new List <int>();
                variables  = new List <int>();
                conditions.Add(did);
                // conditions.Add(genome["heading"].Id);
                conditions.Add(genome["_a2"].Id);
                variables.Add(did);
                inferenceGene            = new InferenceGene(genome, 1, conditions, variables);
                inferenceGene.Generation = session.Generation;
                inferenceGene.Id         = Session.idGenerator.getGeneId(inferenceGene);
                genome.inferenceGenes.Add(inferenceGene);
            }

            inferenceGene = new InferenceGene(genome, 1,
                                              new int[] { genome["d3"].Id, genome["_a2"].Id }.ToList(),
                                              new int[] { genome["b"].Id }.ToList());
            inferenceGene.Generation = session.Generation;
            inferenceGene.Id         = Session.idGenerator.getGeneId(inferenceGene);
            genome.inferenceGenes.Add(inferenceGene);

            //生成推理节点:4

            /*ids = new int[] { genome["g1"].Id, genome["gd"].Id};
             * foreach (int did in ids)
             * {
             *  conditions = new List<int>();
             *  variables = new List<int>();
             *  conditions.Add(genome["g1"].Id);
             *  conditions.Add(genome["gd"].Id);
             *  conditions.Add(genome["heading"].Id);
             *  conditions.Add(genome["_a2"].Id);
             *  variables.Add(did);
             *  inferenceGene = new InferenceGene(genome,1,conditions,variables);
             *  inferenceGene.Generation = session.Generation;
             *  inferenceGene.Id = Session.idGenerator.getGeneId(inferenceGene);
             *  genome.inferenceGenes.Add(inferenceGene);
             * }*/

            genome.id         = Session.idGenerator.getGenomeId();
            genome.generation = 1;
            genome.computeNodeDepth();
            return(genome);
        }
Esempio n. 13
0
        /// <summary>
        /// 变异
        /// </summary>
        /// <param name="session"></param>
        /// <returns></returns>
        public NWSEGenome mutate(Session session)
        {
            NWSEGenome genome = this.clone();

            genome.generation = session.Generation;

            //若有效基因库不空,生成有效基因
            List <NodeGene> vaildGenes = genome.validInferenceGenes;

            if (vaildGenes != null && vaildGenes.Count > 0)
            {
                foreach (NodeGene g in vaildGenes)
                {
                    if (genome.exist(g.Id))
                    {
                        continue;
                    }
                    genome.put(g.clone <NodeGene>());
                }
            }

            //添加一个处理器
            List <NodeGene> inputGenes    = null;
            HandlerGene     newHandleGene = null;
            int             maxcount      = 8;

            if (rng.NextDouble() < Session.config.evolution.mutate.newHandleGeneProb)
            {
                int num = 0;
                while (++num <= maxcount)
                {
                    //随机选择处理器
                    double[] handler_selection_prob = Session.GetConfiguration().evolution.mutate.Handlerprob.ToArray();
                    Configuration.Handler cHandler  = Session.GetConfiguration().random_handler(handler_selection_prob);
                    //选择感知组
                    List <String> cataories = genome.GetAllCataory("rotate");
                    String        cataory   = cataories[rng.Next(0, cataories.Count)];
                    inputGenes = genome.GetAllInputGenes(cataory);
                    inputGenes.shuffle();
                    //确定输入数
                    int inputcount = rng.Next(cHandler.mininputcount, cHandler.maxinputcount + 1);
                    if (inputGenes.Count < inputcount)
                    {
                        continue;
                    }

                    //确定输入
                    List <int> inputids = new List <int>();
                    for (int i = 0; i < inputcount; i++)
                    {
                        inputids.Add(inputGenes[i].Id);
                    }

                    //生成
                    double[]    ps = cHandler.randomParam();
                    HandlerGene g  = new HandlerGene(genome, cHandler.name, inputids, ps);
                    g.Generation = session.Generation;
                    g.Cataory    = inputGenes[0].Cataory;
                    g.Group      = inputGenes[0].Group;
                    g.sortInput();

                    g.Id = session.GetIdGenerator().getGeneId(g);
                    if (genome.exist(g.Id))
                    {
                        continue;
                    }
                    newHandleGene = g;
                    genome.handlerGenes.Add(newHandleGene);
                    session.triggerEvent(Session.EVT_LOG, "A new handler gene is produced in " + genome.id.ToString() + ":" + newHandleGene.Text);
                    break;
                }
            }

            //如果生成了新hanler,生成后置变量
            InferenceGene inf = null;

            if (newHandleGene != null)
            {
                List <int> conditions = new List <int>();
                List <int> variables  = new List <int>();
                int        timediff   = 1;
                variables.Add(newHandleGene.Id);
                List <ReceptorGene> actionSensorGenes = genome.getActionSensorGenes();
                for (int i = 0; i < actionSensorGenes.Count; i++)
                {
                    conditions.Add(actionSensorGenes[i].Id);
                }

                inf            = new InferenceGene(genome, timediff, conditions, variables);
                inf.Cataory    = newHandleGene.Cataory;
                inf.Generation = session.Generation;
                inf.Id         = Session.idGenerator.getGeneId(inf);
                genome.inferenceGenes.Add(inf);
                session.triggerEvent(Session.EVT_LOG, "A inference gene is added in " + genome.id.ToString() + ":" + inf.Text);
            }

            //选择需要变异的推理节点(按照可靠度排序,可靠度越小变异概率越大)
            List <InferenceGene> infGenes = genome.inferenceGenes.FindAll(g => g.reability <= 0.5);

            if (infGenes == null || infGenes.Count <= 0)
            {
                infGenes = genome.inferenceGenes.FindAll(g => g.reability <= 0.98);
            }
            //没有需要变异的推理节点
            inputGenes = genome.GetAllInputGenes(null);
            int    mutateinfcount      = 0;
            double infMutateProb       = Session.config.evolution.mutate.infMutateProb;
            double infMutateAddProb    = Session.config.evolution.mutate.infMutateAddProb;
            double infMutateRemoveProb = Session.config.evolution.mutate.infMutateRemoveProb;

            for (int i = 0; i < infGenes.Count; i++)
            {
                if (rng.NextDouble() >= infMutateProb)
                {
                    continue;
                }
                inf       = infGenes[i].clone <InferenceGene>();
                inf.owner = genome;
                int        oldinfid = inf.Id;
                String     prevText = inf.Text;
                List <int> condIds  = inf.conditions;


                int num = 0;
                maxcount = 5;
                while (++num <= maxcount)
                {
                    //删除
                    if (condIds.Count > 2 && (condIds.Count == inputGenes.Count || rng.NextDouble() <= infMutateRemoveProb))
                    {
                        condIds = inf.conditions.FindAll(c => !genome[c].IsActionSensor());
                        int index = rng.Next(0, condIds.Count);
                        inf.conditions.RemoveAt(index);
                        if (Session.IsInvaildGene(inf))
                        {
                            inf = infGenes[i].clone <InferenceGene>(); inf.owner = genome; continue;
                        }
                        inf.Id = Session.idGenerator.getGeneId(inf);
                        genome.replaceGene(oldinfid, inf);
                        mutateinfcount += 1;
                        session.triggerEvent(Session.EVT_LOG, "conditions of inference gene is removed(" + genome.id.ToString() + "):" + prevText + "--->" + inf.Text);
                        break;
                    }
                    //添加
                    else if (condIds.Count < inputGenes.Count && rng.NextDouble() <= infMutateAddProb)
                    {
                        List <NodeGene> temp  = inputGenes.FindAll(g => !condIds.Contains(g.Id));
                        int             index = rng.Next(0, temp.Count);
                        inf.conditions.Add(temp[index].Id);
                        inf.Sortdimension();
                        if (Session.IsInvaildGene(inf))
                        {
                            inf = infGenes[i].clone <InferenceGene>(); inf.owner = genome; continue;
                        }
                        inf.Id = Session.idGenerator.getGeneId(inf);
                        genome.replaceGene(oldinfid, inf);
                        mutateinfcount += 1;
                        session.triggerEvent(Session.EVT_LOG, "conditions of inference gene is added(" + genome.id.ToString() + "):" + prevText + "--->" + inf.Text);
                        break;
                    }
                    else  //修改
                    {
                        condIds = inf.conditions.FindAll(c => !genome[c].IsActionSensor());
                        if (condIds.Count <= 0)
                        {
                            continue;
                        }
                        int             index1 = rng.Next(0, condIds.Count);
                        List <NodeGene> temp   = inputGenes.FindAll(g => !condIds.Contains(g.Id) || g.Id != condIds[index1]);
                        int             index2 = rng.Next(0, temp.Count);
                        inf.conditions[index1] = temp[index2].Id;
                        inf.Sortdimension();
                        if (Session.IsInvaildGene(inf))
                        {
                            inf = infGenes[i].clone <InferenceGene>(); inf.owner = genome; continue;
                        }
                        inf.Id = Session.idGenerator.getGeneId(inf);
                        genome.replaceGene(oldinfid, inf);
                        mutateinfcount += 1;
                        session.triggerEvent(Session.EVT_LOG, "conditions of inference gene is modified(" + genome.id.ToString() + "):" + prevText + "--->" + inf.Text);
                        break;
                    }
                }
            }

            genome.computeNodeDepth();
            genome.id = Session.idGenerator.getGenomeId();
            return(genome);
        }