Beispiel #1
0
        public OSEnvironment(NetworkGenerator generator, int sensorNum)
        {
            //事実
            TheFact = new TheFact(BlackWhiteSubject.White);

            //ネットワークをつくる
            this.Network = GenerateNetwork(generator);

            //センサーをもつエージェントをつくる
            PrepareSensor(sensorNum);
        }
Beispiel #2
0
        public OSEnvironment(NetworkGenerator generator, int sensorNum)
        {
            //事実
            TheFact = new TheFact(BlackWhiteSubject.White);

            //ネットワークをつくる
            this.Network = GenerateNetwork(generator);

            //センサーをもつエージェントをつくる
            PrepareSensor(sensorNum);
        }
        protected override void Execute()
        {
            INetwork fcffNetwork = NetworkGenerator.GenerateFullyConnectedFeedForwardNetwork(
                new SigmoidFunction(),
                5,
                10,
                2, 3
                );

            fcffNetwork.Calculate(new double[] { .5, 2, .4, -.3, 0 });

            Console.ReadLine();
        }
Beispiel #4
0
        private async Task OnGenerateNetwork(double density)
        {
            try
            {
                IsBusy = true;
                Graph.Clear();
                var          nwg = new NetworkGenerator(NumOfNodes, density);
                Location[]   lc  = null;
                Connection[] cn  = null;
                Stopwatch    sw  = new Stopwatch();
                sw.Start();
                ShowGraph = false;
                lc        = await Task.Run(() => nwg.GetLocationArray());

                cn = await Task.Run(() => nwg.GetConnectionArray(lc));

                sw.Stop();
                Debug.WriteLine(string.Format("Network Generated: {0}", sw.ElapsedMilliseconds.ToString()));
                Debug.WriteLine($"Adding to UI Layer");
                sw.Reset();
                for (int i = 0; i < lc.Length; i++)
                {
                    Graph.Add(lc[i]);
                }
                for (int i = 0; i < cn.Length; i++)
                {
                    Graph.Add(cn[i]);
                }
                NumOfArcs = cn.Length;
                RaisePropertyChanged(() => Graph.Arcs);
                RaisePropertyChanged(() => Graph);
                sw.Stop();
                Debug.WriteLine($"Updated: {sw.ElapsedMilliseconds.ToString()} ms");
                ShowGraph = true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
            }
            finally
            {
                IsBusy = false;
            }
        }
        /// <summary>
        /// This method is called when the <see cref="IHostedService"/> starts. The implementation should return a task that represents
        /// the lifetime of the long running operation(s) being performed.
        /// </summary>
        /// <param name="stoppingToken">Triggered when <see cref="IHostedService.StopAsync(CancellationToken)"/> is called.</param>
        /// <returns>A <see cref="Task"/> that represents the long running operations.</returns>
        public async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                Console.Out.WriteLine("GameService task is starting.");

                NetworkGenerator.SeedInternet();

                stoppingToken.Register(() => Console.Out.WriteLine("GameService task is stopping."));

                while (!stoppingToken.IsCancellationRequested)
                {
                    Game.Update();
                    Game.Time.Update();
                    await Task.Delay(30, stoppingToken);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #6
0
 private Network GenerateNetwork(NetworkGenerator generator)
 {
     //中身:ネットワークとセンサー
     return(generator.create());
 }
Beispiel #7
0
        static void DoExperiment(
            int EXP_ID,
            string algoStr,
            string netStr,
            int size,
            double h_trg,
            int expd,
            int envSeed,    //環境のシード
            int linkNum,
            double cluster, //クラスタ係数
            string dirname
            )
        {
            //ディレクトリを作成
            L.gDirectory(dirname);

            //出力するファイルを宣言
            L.gDefine("roundacc,aveacc");

            //条件を表示
            {
                L.g("all").WriteLine("");
                L.g("all").Write("envSeed: " + envSeed);
                L.g("all").Write(" EXP_ID: " + EXP_ID); //実験IDを
                L.g("all").Write(" Algo: " + algoStr);  //アルゴリズムの名前を表示
                L.g("all").Write(" agentnum: " + size);
                L.g("all").Write(" linkNum: " + linkNum);
                L.g("all").Write(" cluster: " + cluster);//クラスタ係数
                L.g("all").Write(" h_trg: " + h_trg);
                L.g("all").Write(" expd: " + expd);

                L.g("roundacc").WriteLine("");
            }


            {                                               //実験一回し
                Experiment exp = new Experiment(150, 2000); //150ラウンド,2000ステップの実験

                exp.SetEnvsetSeed(envSeed);
                exp.SetFactSeed(0);

                NetworkGenerator generator = null;
                //環境を作る
                if (netStr == "WS")
                {
                    generator = new WSmodelNetworkGenerator(size, expd, 0.12);
                }
                else if (netStr == "BA")
                {
                    generator = new BAModelNetworkGenerator(size, 4, 2);
                }
                else if (netStr == "Random")
                {
                    generator = new RandomNetworkGenerator(size, 16);
                }
                //リーダーネットワークの導入 2014_0707追加
                else if (netStr == "Leader")
                {
                    generator = new LeaderNetworkGenerator(size, expd, 0.12, linkNum);
                }


                //シェルを作る
                generator.NodeCreate += () => new AgentIO();

                //generateしてくれる。
                OSEnvironment env = new OSEnvironment(generator, (int)(size * 0.05));

                //エージェントに脳みそをいれてやる
                foreach (AgentIO agentIO in env.Network.Nodes)
                {
                    agentIO.Algorithm = (AlgorithmFactory.CreateAlgorithm(algoStr, h_trg));
                }


                //ファイルにネットワークの情報を表示
                L.g("env").WriteLine("" + env);
                L.g("env").Flush();

                exp.Environment = env;

                //実験を実行
                var expResult = exp.Run();
            }



            //ファイルに書き込み
            L.Flush();
        }
    public void Init()
    {
        m_inhabitants = new List <Npc>();
        int     count   = (int)m_category;
        Vector3 extents = GetComponent <Collider>().bounds.extents;

        ///No time to make this look pretty....
        for (int i = 0; i < count; i++)
        {
            int     tryCount = 25;
            Vector3 nPOs     = Vector3.zero;
            bool    found    = false;
            while (tryCount > 0)
            {
                if (m_inhabitants.Count == 0)
                {
                    nPOs  = GeneratePoint(extents);
                    found = true;
                    break;
                }
                for (int j = 0; j < m_inhabitants.Count; j++)
                {
                    nPOs = GeneratePoint(extents);
                    if (!m_inhabitants[j].GetComponentInChildren <Collider>().bounds.Contains(nPOs))
                    {
                        found = true;
                        break;
                    }
                }
                if (found)
                {
                    break;
                }
                tryCount--;
            }

            if (!found)
            {
                continue;
            }
            m_inhabitants.Add(((GameObject)Instantiate(npcPrefab, nPOs, Quaternion.identity)).GetComponent <Npc>());
            m_inhabitants[m_inhabitants.Count - 1].transform.SetParent(gameObject.transform.GetChild(0));
            m_inhabitants[m_inhabitants.Count - 1]
            .GenerateSelf(m_populations[Random.Range(0, m_populations.Count)], (Morality)Random.Range(1, 10));
        }
        AssignFaction();
        //create generator and load condition
        NetworkGenerator <Npc> generator = new NetworkGenerator <Npc>();

        generator.LoadNodeLinkCondition((Npc first, Npc second) =>
        {
            //if they are in the same faction there is a chance they met
            if (first.faction == second.faction && Random.value <= SAME_FACTION_LINK_RATE)
            {
                return(true);
            }
            //if they are close enough and have the chance to meet create link
            else if (Random.value <= NPC_PROXIMITY_LINK_RATE &&
                     Vector3.Distance(first.transform.position, second.transform.position) <= MAX_NPC_DISTANCE)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        });
        //create npc network
        Npc[] ninhabitants = new Npc[m_inhabitants.Count - 2];
        // take out the first two inhabitants as they are used
        //in the startup step
        m_inhabitants.CopyTo(2, ninhabitants, 0, ninhabitants.Length);
        m_npcNetwork = generator.Startup(NetworkModel.Barabasi_Albert, m_inhabitants[0], m_inhabitants[1])
                       .MultipleStepNetwork(ninhabitants);

        ///Set Npc relationships
        for (int i = 0; i < m_npcNetwork.Connections.Count; i++)
        {
            int rep = m_npcNetwork.Connections[i].First.data.CreateRelationshipTowards(m_npcNetwork.Connections[i].Second.data);
            rep += m_npcNetwork.Connections[i].First.data.faction.GetReputationAsInt(m_npcNetwork.Connections[i].Second.data.faction);
            rep  = Mathf.Clamp(rep, -1, 1);
            m_npcNetwork.Connections[i].First.data.SetRelationshipWithNpc(m_npcNetwork.Connections[i].Second.data, (Relationship)rep);
            m_npcNetwork.Connections[i].Second.data.SetRelationshipWithNpc(m_npcNetwork.Connections[i].First.data, (Relationship)rep);
        }
    }
    // Use this for initialization
    void Awake()
    {
        //Ruberband singleton
        if (m_instance != null)
        {
            Destroy(gameObject);
            return;
        }
        else
        {
            m_instance = this;
        }

        for (int i = 0; i < m_allFactions.Count; i++)
        {
            for (int j = 0; j < m_allFactions.Count; j++)
            {
                if (i == j || m_allFactions[i].HasRep(m_allFactions[j]))
                {
                    continue;
                }
                int rep = 0;
                rep += m_allFactions[i].CreateReputationTowards(m_allFactions[j]);
                rep += m_allFactions[j].CreateReputationTowards(m_allFactions[i]);
                rep  = Mathf.Clamp(rep, -1, 1); // clamp so that value is 1 , 0 , -1
                m_allFactions[i].SetRelationship(m_allFactions[j], (Relationship)rep);
                m_allFactions[j].SetRelationship(m_allFactions[i], (Relationship)rep);
            }
        }

        NetworkGenerator <Settlement> settlementGen     = new NetworkGenerator <Settlement>();
        NetworkGenerator <Npc>        npcFactionNetwork = new NetworkGenerator <Npc>();

        ///Settlements link only if they have the same faction
        settlementGen.LoadNodeLinkCondition((Settlement first, Settlement second) =>
        {
            if (first.controllingfaction == second.controllingfaction)
            {
                return(true);
            }
            else if (first.controllingfaction == m_allFactions[m_independentID] || second.controllingfaction == m_allFactions[m_independentID])
            {
                return(true);
            }
            else
            {
                return(false);
            }
        });
        List <Settlement> settlements = new List <Settlement>(FindObjectsOfType <Settlement>());

        //init settlements - work around to circumvent the need of a faction serialized class
        for (int i = 0; i < settlements.Count; i++)
        {
            settlements[i].Init();
        }


        Settlement[] nsettlements = new Settlement[2];
        nsettlements[0] = settlements[0];
        nsettlements[1] = settlements[1];
        settlements.RemoveAt(0);
        settlements.RemoveAt(0);
        m_settlementNetwork = settlementGen.Startup(NetworkModel.Barabasi_Albert, nsettlements[0], nsettlements[1])
                              .MultipleStepNetwork(settlements.ToArray());

        ///Create faction networks
        m_factionsNetwork = new Dictionary <Faction, Network <Npc> >();
        for (int i = 0; i < m_allFactions.Count; i++)
        {
            Npc[]         npcs    = null;
            Network <Npc> network = null;
            if (m_allFactions[i].members.Count == 0)
            {
                npcs = new Npc[m_allFactions[i].members.Count];
                m_factionsNetwork.Add(m_allFactions[i], network);
                continue;
            }

            npcs = new Npc[m_allFactions[i].members.Count - 2];
            m_allFactions[i].members.CopyTo(2, npcs, 0, npcs.Length);
            network = npcFactionNetwork
                      .Startup(NetworkModel.Barabasi_Albert, m_allFactions[i].members[0], m_allFactions[i].members[1])
                      .MultipleStepNetwork(npcs);
            m_factionsNetwork.Add(m_allFactions[i], network);
        }

        //Set npc relationships within each faction
        for (int i = 0; i < m_allFactions.Count; i++)
        {
            if (m_factionsNetwork[m_allFactions[i]] == null)
            {
                continue;
            }
            var conn = m_factionsNetwork[m_allFactions[i]].Connections;

            for (int j = 0; j < conn.Count; j++)
            {
                if (conn[j].First.data.GetRelationship(conn[j].Second.data) != Relationship.None)
                {
                    continue;
                }

                int rep = conn[i].First.data.CreateRelationshipTowards(conn[i].Second.data) + 1; //since they are both the same faction +1 rep
                rep = Mathf.Clamp(rep, -1, 1);
                conn[i].First.data.SetRelationshipWithNpc(conn[i].Second.data, (Relationship)rep);
                conn[i].Second.data.SetRelationshipWithNpc(conn[i].First.data, (Relationship)rep);
            }
        }

        //Generate Quests based on settlements
        m_quests = new QuestManager();

        for (int i = 0; i < settlements.Count; i++)
        {
            var conn = settlements[i].localNPCNetwork.Connections;
            for (int j = 0; j < conn.Count; j++)
            {
                if (Random.value <= QuestManager.QUEST_GENERATION_RATE)
                {
                    var rel = conn[j].First.data.GetRelationship(conn[j].Second.data);
                    switch (rel)
                    {
                    case Relationship.Friendly:
                        int ch = Random.Range(0, 2);
                        switch (ch)
                        {
                        case 0:          //make deliver quest
                            m_quests.GenerateDeliverQuest(conn[j]);
                            break;

                        case 1:         // make collect quest
                            m_quests.GenerateCollectQuest(conn[j]);
                            break;
                        }
                        break;

                    case Relationship.Hostile:
                        m_quests.GenerateKillQuest(conn[j]);
                        break;

                    case Relationship.Neutral:
                        ch = Random.Range(0, 3);

                        switch (ch)
                        {
                        case 0:         //deliver
                            m_quests.GenerateDeliverQuest(conn[j]);
                            break;

                        case 1:         //collect
                            m_quests.GenerateCollectQuest(conn[j]);
                            break;

                        case 2:         //kill
                            m_quests.GenerateKillQuest(conn[j]);
                            break;
                        }

                        break;
                    }
                }
            }
        }
    }
Beispiel #10
0
 private Network GenerateNetwork(NetworkGenerator generator)
 {
     //中身:ネットワークとセンサー
     return generator.create();
 }