StartCoroutine() public static method

public static StartCoroutine ( IEnumerator iterationResult ) : Coroutine
iterationResult IEnumerator
return Coroutine
Exemplo n.º 1
0
        internal static void MakeDownloadCall(string url, Action <string> resultCallback)
        {
            EdExLogger.LoggerInstance.LogWithTimeStamp("Downloading file: " + url);
            var www = UnityWebRequest.Get(url);

            AppCenterEditor.RaiseStateUpdate(AppCenterEditor.EdExStates.OnHttpReq, url, AppCenterEditorHelper.MSG_SPIN_BLOCK);
            Coroutiner.StartCoroutine(PostDownload(www, response =>
            {
                resultCallback(WriteResultFile(url, response));
            }, AppCenterEditorHelper.SharedErrorCallback));
        }
Exemplo n.º 2
0
        private IEnumerator CheckTouch()
        {
            yield return(new WaitForSeconds(1));

            if ((Time.time - matchTileGridModel.lastTouchedTimestamp) >= matchTileGridModel.secondsUntilHint)
            {
                matchTileGridModel.lastTouchedTimestamp = Time.time;
                DisplayHint();
            }

            Coroutiner.StartCoroutine(CheckTouch());
        }
Exemplo n.º 3
0
		public void Execute()
		{
			matchTileQueue.Add (removeTile);

			if (matchTileQueue.Count == 1)
			{
				matchTileGridModel.pauseTilesFalling = true;

				enumerator = Remove ();
				Coroutiner.StartCoroutine (enumerator);
			}
		}
Exemplo n.º 4
0
        public IEnumerator DoOneGeneration()
        {
            _currentGeneration++;
            yield return(Coroutiner.StartCoroutine(PerformOneGeneration()));

            if (UpdateTest())
            {
                _prevUpdateGeneration = _currentGeneration;
                _prevUpdateTimeTick   = DateTime.Now.Ticks;
                OnUpdateEvent();
            }
        }
Exemplo n.º 5
0
        internal static void MakeDownloadCall(IEnumerable <string> urls, Action <IEnumerable <string> > resultCallback)
        {
            EdExLogger.LoggerInstance.LogWithTimeStamp("Downloading files: " + string.Join(", ", urls.ToArray()));
            var wwws             = new List <UnityWebRequest>();
            var downloadRequests = new List <DownloadRequest>();

            foreach (var url in urls)
            {
                var www = UnityWebRequest.Get(url);
                wwws.Add(www);
                downloadRequests.Add(new DownloadRequest(url, www));
            }
            AppCenterEditor.RaiseStateUpdate(AppCenterEditor.EdExStates.OnHttpReq, "Downloading files", AppCenterEditorHelper.MSG_SPIN_BLOCK);
            Coroutiner.StartCoroutine(DownloadFiles(downloadRequests, resultCallback, AppCenterEditorHelper.SharedErrorCallback));
        }
Exemplo n.º 6
0
        // Use this for initialization
        public void BuildObjectPool()
        {
            ContainerObject = new GameObject("ObjectPoolContainer");

            //Loop through the object prefabs and make a new list for each one.
            //We do this because the pool can only support prefabs set to it in the editor,
            //so we can assume the lists of pooled objects are in the same order as object prefabs in the array
            Pool = new List <GameObject> [Entries.Count];

            for (int i = 0; i < Entries.Count; i++)
            {
                Build(i);
            }

            Coroutiner.StartCoroutine(CompleteObjectPool());
        }
        private IEnumerator AlgorithmThreadMethodMAP()
        {
            //print("AlgorithThreadMethod()");
            //try
            //{
            _prevUpdateGeneration = 0;
            _prevUpdateTimeTick   = DateTime.Now.Ticks;

            for (; ;)
            {
                _currentGeneration++;
                //  print("currentGeneration: " + _currentGeneration);
                yield return(Coroutiner.StartCoroutine(PerformOneGeneration()));

                //     print("Performed one generation");
//				OnUpdateEvent ();
                if (UpdateTest())
                {
                    _prevUpdateGeneration = _currentGeneration;
                    _prevUpdateTimeTick   = DateTime.Now.Ticks;
                    OnUpdateEvent();
                }

                // Check if a pause has been requested.
                // Access to the flag is not thread synchronized, but it doesn't really matter if
                // we miss it being set and perform one other generation before pausing.
                if (_pauseRequestFlag || _genomeListEvaluator.StopConditionSatisfied)
                {
                    // Signal to any waiting thread that we are pausing
                    // _awaitPauseEvent.Set();

                    // Reset the flag. Update RunState and notify any listeners of the state change.
                    //   _pauseRequestFlag = false;
                    //   _runState = RunState.Paused;
                    OnUpdateEvent();
                    OnPausedEvent();
                    break;
                    // Wait indefinitely for a signal to wake up and continue.
                    //   _awaitRestartEvent.WaitOne();
                }
            }
            //}
            //catch(ThreadAbortException)
            //{   // Quietly exit thread.
            //}
        }
    public void create(bool firstTime = false)
    {
        leftEyePos  = GameObject.Find("leftEye").transform.localPosition;
        rightEyePos = GameObject.Find("rightEye").transform.localPosition;
        leftEarPos  = GameObject.Find("leftEar").transform.localPosition;
        rightEarPos = GameObject.Find("rightEar").transform.localPosition;
        nosePos     = GameObject.Find("nose").transform.localPosition;
        mouthPos    = GameObject.Find("mouth").transform.localPosition;


        if (this.gameObject.name.Contains("LeftHand"))
        {
            this.location     = "left";
            initialPositionV3 = this.gameObject.transform.localPosition;
        }
        else if (this.gameObject.name.Contains("RightHand"))
        {
            this.location     = "right";
            initialPositionV3 = this.gameObject.transform.localPosition;
        }
        else if (this.gameObject.name.Contains("UpperHand"))
        {
            this.location     = "up";
            initialPositionV3 = this.gameObject.transform.localPosition;
        }
        else if (this.gameObject.name.Contains("DownHand"))
        {
            this.location     = "down";
            initialPositionV3 = this.gameObject.transform.localPosition;
        }

        mainScript = this.gameObject.GetComponentInParent <MainScript>();

        if (firstTime)
        {
            Coroutiner.StartCoroutine(StartAnimation(2f, 3f));
        }
        else
        {
            Coroutiner.StartCoroutine(StartAnimation(2f / mainScript.myGameDifficulty, 6f / mainScript.myGameDifficulty));
        }
    }
Exemplo n.º 9
0
        public IEnumerator EvaluateList(List <TGenome> genomeList)
        {
            UnityEngine.Debug.Log("TEasdasST!");

            //print("StartContinue");
            // RunState must be Ready or Paused.
//			if (RunState.Ready == _runState) {   // Create a new thread and start it running.
            //   print("RunState ready");
//			_runState = RunState.Running;
//
//			// FOREVER LOOP
//			_currentGeneration++;
//
//			UnityEngine.Debug.Log ("Genome List count " + _genomeList.Count);
            _genomeList.Clear();
//			UnityEngine.Debug.Log ("Genome List count " + _genomeList.Count);
            _genomeList.AddRange(genomeList);
//			UnityEngine.Debug.Log ("Genome List count " + _genomeList.Count);

            // Evaluate genomes.
            yield return(Coroutiner.StartCoroutine(_genomeListEvaluator.Evaluate(_genomeList)));
            //     print("Performed one generation");
//			if (UpdateTest ()) {
//				_prevUpdateGeneration = _currentGeneration;
//				_prevUpdateTimeTick = DateTime.Now.Ticks;
//				OnUpdateEvent ();
//			}
            // FOREVER


//			} else if (RunState.Paused == _runState) {   // Thread is paused. Resume execution.
//				_runState = RunState.Running;
//				OnUpdateEvent ();
//				_awaitRestartEvent.Set ();
//			} else if (RunState.Running == _runState) {   // Already running. Log a warning.
//				//__log.Warn("StartContinue() called but algorithm is already running.");
//			} else {
//				throw new SharpNeatException (string.Format ("StartContinue() call failed. Unexpected RunState [{0}]", _runState));
//			}
//			return null;
        }
Exemplo n.º 10
0
        private IEnumerator evaluateList(IList <TGenome> genomeList)
        {
            foreach (TGenome genome in genomeList)
            {
                TPhenome phenome = _genomeDecoder.Decode(genome);
                if (null == phenome)
                {   // Non-viable genome.
                    genome.EvaluationInfo.SetFitness(0.0);
                    genome.EvaluationInfo.AuxFitnessArr = null;
                }
                else
                {
                    yield return(Coroutiner.StartCoroutine(_phenomeEvaluator.Evaluate(phenome)));

                    FitnessInfo fitnessInfo = _phenomeEvaluator.GetLastFitness(phenome);

                    genome.EvaluationInfo.SetFitness(fitnessInfo._fitness);
                    genome.EvaluationInfo.AuxFitnessArr = fitnessInfo._auxFitnessArr;
                }
            }
        }
Exemplo n.º 11
0
        public IEnumerator Until_LateElementCreation_ElementFound()
        {
            // Arrange
            var       startTime = Time.time;
            const int TIMEOUT = 2, TEST_DELAY = 1;

            Coroutiner.StartCoroutine(DelayedSpawnGO(TEST_GO_NAME, TEST_DELAY));
            UiElement element = null;
            var       wait    = new UnityDriverWait(_driver, TimeSpan.FromSeconds(TIMEOUT));

            // Act
            yield return(wait.Until(d =>
                                    d.FindElement(By.Name(TEST_GO_NAME)),
                                    (e) => element = e
                                    ));

            // Assert
            Assert.IsNotNull(element);
            Assert.Less(Time.time, startTime + TIMEOUT);
            Assert.Greater(Time.time, startTime);
            Assert.GreaterOrEqual(Time.time, startTime + TEST_DELAY);
        }
Exemplo n.º 12
0
        private void Build(int i)
        {
            var objectPrefab = Entries[i];

            //create the repository
            Pool[i] = new List <GameObject>();

            GameObject[] objects = new GameObject[objectPrefab.Count];

            //fill it
            int n = 0;

            for (n = 0; n < objectPrefab.Count; n++)
            {
                var newObj = GameObject.Instantiate(objectPrefab.Prefab) as GameObject;
                newObj.name = objectPrefab.name;
                objects[n]  = newObj;
                PoolObject(newObj, objectPrefab.name);
            }

            Coroutiner.StartCoroutine(PreloadObjectPoolTextures(objects));
        }
        /// <summary>
        /// Evaluates a list of genomes. Here we select the genomes to be evaluated before invoking
        /// _innerEvaluator to evaluate them.
        /// </summary>
        public IEnumerator Evaluate(IList <TGenome> genomeList)
        {
            // Select the genomes to be evaluated. Place them in a temporary list of genomes to be
            // evaluated after the genome selection loop. The selection is not performed in series
            // so that we can wrap parallel execution versions of IGenomeListEvaluator.
            List <TGenome> filteredList = new List <TGenome>(genomeList.Count);

            foreach (TGenome genome in genomeList)
            {
                if (_selectionPredicate.Invoke(genome))
                {   // Add the genome to the temp list for evaluation later.
                    filteredList.Add(genome);
                }
                else
                {   // Register that the genome skipped an evaluation.
                    genome.EvaluationInfo.EvaluationPassCount++;
                }
            }

            // Evaluate selected genomes.
            yield return(Coroutiner.StartCoroutine(_innerEvaluator.Evaluate(filteredList)));
        }
Exemplo n.º 14
0
        public IEnumerator Evaluate(IList <TGenome> genomeList)
        {
            yield return(Coroutiner.StartCoroutine(GameManagerController.inputManagerInstance.simInst.coEvaluator.SubmitGenomesAndWaitUntilTheyAreEvaluated((List <NeatGenome>)genomeList, player)));

            #region Log statistics and delete fitness
            float totalFitness    = 0;
            float mxFitness       = (float)genomeList[0].EvaluationInfo.Fitness;
            float totalComplexity = 0;
            float mxComplexity    = (float)genomeList[0].Complexity;
            foreach (var genome in genomeList)
            {
                totalFitness    += (float)genome.EvaluationInfo.Fitness;
                mxFitness        = Math.Max(mxFitness, (float)genome.EvaluationInfo.Fitness);
                totalComplexity += (float)genome.Complexity;
                mxComplexity     = Math.Max(mxComplexity, (float)genome.Complexity);
            }
            Debug.Log(String.Format("Max fitness is {0}; Mean fitnes is {1}; Max complexity is {2}; Mean complexity is {3}",
                                    mxFitness,
                                    totalFitness / genomeList.Count,
                                    mxComplexity,
                                    totalComplexity / genomeList.Count));
            #endregion
            Debug.Log($"Evaluation {++EvaluationCount} of team {player.Team} has finished");
        }
Exemplo n.º 15
0
 private void GetOAuthToken()
 {
     Coroutiner.StartCoroutine(SendRequest());
 }
    /// <summary>
    /// 下载协程;
    /// </summary>
    /// <returns>The base context.</returns>
    /// <param name="initCb">下载结束进度.</param>
    /// <param name="progressCb">下载进度.</param>
    private static IEnumerator _initlizeBaseContext(AssetBundleInitFinish initCb, AssetBundleProgress progressCb)
    {
        yield return(Coroutiner.StartCoroutine(_initlizeDependData(initCb, progressCb)));

        s_bInitlized = true;
    }
Exemplo n.º 17
0
 public void Query(string query, object variables = null, Action <GraphQLResponse> callback = null,
                   string sToken = "")
 {
     Coroutiner.StartCoroutine(SendRequest(query, variables, callback, sToken));
 }
Exemplo n.º 18
0
 public IEnumerator Evaluate(IList <TGenome> genomeList)
 {
     yield return(Coroutiner.StartCoroutine(evaluateList(genomeList)));
 }
Exemplo n.º 19
0
        private IEnumerator evaluateList(IList <TGenome> genomeList)
        {
            Dictionary <TGenome, TPhenome>      dict        = new Dictionary <TGenome, TPhenome>();
            Dictionary <TGenome, FitnessInfo[]> fitnessDict = new Dictionary <TGenome, FitnessInfo[]>();

            for (int i = 0; i < _optimizer.Trials; i++)
            {
                //Utility.Log("Iteration " + (i + 1));
                _phenomeEvaluator.Reset();
                dict = new Dictionary <TGenome, TPhenome>();
                foreach (TGenome genome in genomeList)
                {
                    TPhenome phenome = _genomeDecoder.Decode(genome);
                    if (null == phenome)
                    {   // Non-viable genome.
                        genome.EvaluationInfo.SetFitness(0.0);
                        genome.EvaluationInfo.AuxFitnessArr = null;
                    }
                    else
                    {
                        if (i == 0)
                        {
                            fitnessDict.Add(genome, new FitnessInfo[_optimizer.Trials]);
                        }

                        dict.Add(genome, phenome);
                        //if (!dict.ContainsKey(genome))
                        //{
                        //    dict.Add(genome, phenome);
                        //    fitnessDict.Add(phenome, new FitnessInfo[_optimizer.Trials]);
                        //}
                        Coroutiner.StartCoroutine(_phenomeEvaluator.Evaluate(phenome));
                    }
                }

                yield return(new WaitForSeconds(_optimizer.TrialDuration));

                foreach (TGenome genome in dict.Keys)
                {
                    TPhenome phenome = dict[genome];
                    if (phenome != null)
                    {
                        FitnessInfo fitnessInfo = _phenomeEvaluator.GetLastFitness(phenome);

                        fitnessDict[genome][i] = fitnessInfo;
                    }
                }
            }
            foreach (TGenome genome in dict.Keys)
            {
                TPhenome phenome = dict[genome];
                if (phenome != null)
                {
                    double fitness = 0;

                    for (int i = 0; i < _optimizer.Trials; i++)
                    {
                        fitness += fitnessDict[genome][i]._fitness;
                    }
                    var fit = fitness;
                    fitness /= _optimizer.Trials; // Averaged fitness

                    if (fit > _optimizer.StoppingFitness)
                    {
                        //  Utility.Log("Fitness is " + fit + ", stopping now because stopping fitness is " + _optimizer.StoppingFitness);
                        //  _phenomeEvaluator.StopConditionSatisfied = true;
                    }
                    if (_optimizer.SelectionHasBeenMade && _optimizer.SelectedGenomeId == genome.Id)
                    {
                        if (_optimizer.TimeSinceSelection < Optimizer.DecayTime)
                        {
                            fitness += (Optimizer.DecayTime - _optimizer.TimeSinceSelection) * Optimizer.SelectionBoost;
                        }
                    }
                    genome.EvaluationInfo.SetFitness(fitness);
                    genome.EvaluationInfo.AuxFitnessArr = fitnessDict[genome][0]._auxFitnessArr;
                }
            }
        }
Exemplo n.º 20
0
 public void Execute()
 {
     enumerator = Allow();
     Coroutiner.StartCoroutine(enumerator);
 }
Exemplo n.º 21
0
    // Use this for initialization
    void Start()
    {
        //PlayerPrefs.DeleteAll();
        minigames.Add("TaxMan");
        minigames.Add("Networking");
        minigames.Add("InvestToProgress");
        minigames.Add("GovermentWorkOut");
        minigames.Add("Censorship");
        minigames.Add("TheWorldBalance");
        minigames.Add("Bureaucracy");
        minigames.Add("JumpTheTradeBarriers");
        minigames.Add("Memory");


        FillRandomList();

        playedGamesList.Add("TaxManPlayed");
        playedGamesList.Add("NetworkingPlayed");
        playedGamesList.Add("InvestToProgressPlayed");
        playedGamesList.Add("GovermentWorkOutPlayed");
        playedGamesList.Add("CensorshipPlayed");
        playedGamesList.Add("TheWorldBalancePlayed");
        playedGamesList.Add("BureaucracyPlayed");
        playedGamesList.Add("JumpTheTradeBarriersPlayed");
        playedGamesList.Add("MemoryPlayed");

        var totalScore = PlayerPrefs.GetFloat("totalScore");
        var score      = PlayerPrefs.GetFloat("score");
        var sceneName  = PlayerPrefs.GetString("sceneName");
        var fail       = PlayerPrefs.GetInt("fail");


        Transform mylabel = transform.Find("Score");
        Text      t       = mylabel.GetComponent <Text>();

        totalScore += score;
        PlayerPrefs.SetFloat("totalScore", totalScore);
        t.text = totalScore.ToString();

        Transform levelComplete = transform.Find("LevelComplete");
        Text      lvlComplete   = levelComplete.GetComponent <Text>();

        lvlComplete.text = "LEVEL COMPLETE: " + score.ToString();

        PlayerPrefs.SetInt(sceneName + "Played", 1);    //last scene played
        foreach (var playedGameName in playedGamesList) //remove all used scenes
        {
            if (PlayerPrefs.GetInt(playedGameName) == 1)
            {
                var sceneNameTemp = playedGameName.Substring(0, playedGameName.Length - 6);
                minigamesRandomList.Remove(sceneNameTemp);
            }
        }

        if (minigamesRandomList.Count == 0)
        {
            FillRandomList();
            PlayerPrefs.SetInt("Lvl", PlayerPrefs.GetInt("Lvl") + 1);
        }
        minigamesRandomList.Shuffle();
        Debug.Log(fail + "GO LEVEL" + PlayerPrefs.GetInt("Lvl"));

        var lives    = PlayerPrefs.GetInt("Lives");
        var goHeart  = GameObject.Find("heart0");
        var goHeart1 = GameObject.Find("heart1");
        var goHeart2 = GameObject.Find("heart2");


        if (lives <= 0) //END GAME
        {
            Coroutiner.StartCoroutine(finishGame());
        }
        else
        {
            if (lives == 2)
            {
                DestroyImmediate(goHeart2.gameObject);
            }
            else if (lives == 1)
            {
                DestroyImmediate(goHeart2.gameObject);
                DestroyImmediate(goHeart1.gameObject);
            }

            if (fail == 1)
            {
                lives -= 1;
                Debug.Log("***Lives: " + lives);

                var heart = GameObject.Find("heart" + lives);
                PlayerPrefs.SetInt("Lives", lives);
                iTween.FadeTo(heart.gameObject, iTween.Hash(
                                  "alpha", 0,
                                  "time", 0.5f,
                                  "oncomplete", "OnCompleteHeartAnimation",
                                  "oncompletetarget", gameObject,
                                  "oncompleteparams", heart.gameObject,
                                  "islocal", true
                                  ));
            }
            Debug.Log("Lives: " + PlayerPrefs.GetInt("Lives"));
        }
    }
Exemplo n.º 22
0
        /*
         *      public IGenomeDecoder<TGenome, TPhenome> GenomeDecoder
         *      {
         *              get { return _genomeDecoder; }
         *      }
         */

        public IEnumerator Evaluate(IList <TGenome> genomeList)
        {
            // As a coroutine so we have good control of real-time waiting periods.
            yield return(Coroutiner.StartCoroutine(evaluateList(genomeList)));
        }
    /// <summary>
    /// 初始化资源管理器.
    /// </summary>
    /// <param name="strUrlDirectory">下载地址.</param>
    /// <param name="initCb">结束下载.</param>
    /// <param name="progressCb">进度.</param>
    public static void InitlizeAssetBundle(string strPreUrlDirectory, string strRealUrlDirectory, AssetBundleInitFinish initCb, AssetBundleProgress progressCb)
    {
        if (s_bInitlized)
        {
            DownLoadProgress downLoadProgress = new DownLoadProgress();
            downLoadProgress.bDownload       = false;
            downLoadProgress.bDownloadFinsih = true;
            progressCb(downLoadProgress);
            //progressCb(100, false);
            initCb(true, "");
            return;
        }

        s_strPreHttpDirectory  = strPreUrlDirectory;
        s_strRealHttpDirectory = strRealUrlDirectory;

                #if UNITY_STANDALONE_WIN
        s_strPreHttpDirectory  += "/StandaloneWindows/";
        s_strRealHttpDirectory += "/StandaloneWindows/";
        s_strStreamAssetDir    += "/StandaloneWindows/";
                #elif UNITY_ANDROID
        s_strPreHttpDirectory  += "/Android/";
        s_strRealHttpDirectory += "/Android/";
        s_strStreamAssetDir    += "/Android/";
                #elif UNITY_IPHONE
        s_strPreHttpDirectory  += "/iPhone/";
        s_strRealHttpDirectory += "/iPhone/";
        s_strStreamAssetDir     = "file://" + Application.dataPath + "/Raw/iPhone/";
                #elif UNITY_WP8
        s_strPreHttpDirectory  += "/WP8Player/";
        s_strRealHttpDirectory += "/WP8Player/";
        s_strStreamAssetDir    += "/WP8Player/";
                #elif UNITY_METRO
        s_strPreHttpDirectory  += "/MetroPlayer";
        s_strRealHttpDirectory += "/MetroPlayer";
        s_strStreamAssetDir    += "/MetroPlayer";
                #endif

                #if UNITY_EDITOR
        s_strStreamAssetDir = "file:///" + s_strStreamAssetDir;
        s_strPersistUrlPath = "file:///" + Application.dataPath;
        s_strPersistPath    = Application.dataPath;
                #endif

                #if UNITY_EDITOR
        // 标记已初始化;
        s_bInitlized = true;

        // bin文件加载;
        AddDirBinaryFilesToAsset("Assets/Artwork/Download/Bytes/", "bytes", false);
        AddDirBinaryFilesToAsset("Assets/Artwork/Download/Bytes/", "txt", false);

        // Texture文件加载;
        AddDirBinaryFilesToAsset("Assets/Artwork/Download/Texture/", "png", false);
        AddDirBinaryFilesToAsset("Assets/Artwork/Download/Texture/", "jpg", false);

        // Prefab文件加载;
        AddDirBinaryFilesToAsset("Assets/Artwork/Download/Prefab/", "prefab", false);

        // 场景文件加载;
        AddDirBinaryFilesToAsset("Assets/Artwork/Download/Scene/", "unity", false);

        // 声音文件加载;
        AddDirBinaryFilesToAsset("Assets/Artwork/Download/Sound/", "mp3", false);
        AddDirBinaryFilesToAsset("Assets/Artwork/Download/Sound/", "ogg", false);

        DownLoadProgress downLoadProgresst = new DownLoadProgress();
        downLoadProgresst.bDownload       = false;
        downLoadProgresst.bDownloadFinsih = true;
        progressCb(downLoadProgresst);
        // progressCb(100, false);
        initCb(true, "");
                #else
        //Debug.Log ("StreamAsset Path:" + s_strStreamAssetDir);
        //Debug.Log ("PersistPath:" + Application.persistentDataPath);

        Coroutiner.StartCoroutine(_initlizeBaseContext(initCb, progressCb));
                #endif
    }
Exemplo n.º 24
0
 private void BeginTokenUpdater()
 {
     Coroutiner.StartCoroutine(UpdateToken());
 }
Exemplo n.º 25
0
        private IEnumerator evaluateList(IList <TGenome> genomeList)
        {
            Debug.Log("Starting new trial");

            // ui
            //IECManager.SetUIToSelectionState();

            Dictionary <TGenome, TPhenome>      dict        = new Dictionary <TGenome, TPhenome>();
            Dictionary <TGenome, FitnessInfo[]> fitnessDict = new Dictionary <TGenome, FitnessInfo[]>();

            for (int i = 0; i < _optimizer.Trials; i++)
            {
                Utility.Log("Iteration " + (i + 1));
                Debug.Log("Creating Genomes...");
                _phenomeEvaluator.Reset();
                dict = new Dictionary <TGenome, TPhenome>();
                foreach (TGenome genome in genomeList)
                {
                    TPhenome phenome = _genomeDecoder.Decode(genome);
                    if (null == phenome)
                    {   // Non-viable genome.
                        genome.EvaluationInfo.SetFitness(0.0);
                        genome.EvaluationInfo.AuxFitnessArr = null;
                    }
                    else
                    {
                        if (i == 0)
                        {
                            fitnessDict.Add(genome, new FitnessInfo[_optimizer.Trials]);
                        }
                        dict.Add(genome, phenome);
                        //if (!dict.ContainsKey(genome))
                        //{
                        //    dict.Add(genome, phenome);
                        //    fitnessDict.Add(phenome, new FitnessInfo[_optimizer.Trials]);
                        //}
                        //Debug.Log("In simpleEvaluator");
                        Coroutiner.StartCoroutine(_phenomeEvaluator.Evaluate(phenome));
                    }
                }

                yield return(new WaitForSeconds(_optimizer.TrialDuration));

                Debug.Log("End of trial");
                Debug.Log("Getting fitness values...");
                foreach (TGenome genome in dict.Keys)
                {
                    TPhenome phenome = dict[genome];
                    if (phenome != null)
                    {
                        FitnessInfo fitnessInfo = _phenomeEvaluator.GetLastFitness(phenome);

                        fitnessDict[genome][i] = fitnessInfo;
                    }
                }
                Debug.Log("Done getting fitness values...");
            }
            foreach (TGenome genome in dict.Keys)
            {
                TPhenome phenome = dict[genome];
                if (phenome != null)
                {
                    double fitness = 0;

                    for (int i = 0; i < _optimizer.Trials; i++)
                    {
                        fitness += fitnessDict[genome][i]._fitness;
                    }
                    var fit = fitness;
                    fitness /= _optimizer.Trials; // Averaged fitness

                    if (fit > _optimizer.StoppingFitness)
                    {
                        //  Utility.Log("Fitness is " + fit + ", stopping now because stopping fitness is " + _optimizer.StoppingFitness);
                        //  _phenomeEvaluator.StopConditionSatisfied = true;
                    }
                    genome.EvaluationInfo.SetFitness(fitness);
                    genome.EvaluationInfo.AuxFitnessArr = fitnessDict[genome][0]._auxFitnessArr;
                }
            }

            Debug.Log("End of Evaluation of Genome list");
        }
        private IEnumerator evaluateList(IList <TGenome> genomeList)
        {
            Dictionary <TGenome, TPhenome>      dict        = new Dictionary <TGenome, TPhenome>();
            Dictionary <TGenome, FitnessInfo[]> fitnessDict = new Dictionary <TGenome, FitnessInfo[]>();

            for (int i = 0; i < controller.Trials; i++)
            {
                Utility.Log("Iteration " + (i + 1));
                _phenomeEvaluator.Reset();
                dict = new Dictionary <TGenome, TPhenome>();
                foreach (TGenome genome in genomeList)
                {
                    TPhenome phenome = _genomeDecoder.Decode(genome);
                    if (null == phenome)
                    {   //Bad genome
                        genome.EvaluationInfo.SetFitness(0.0);
                        genome.EvaluationInfo.AuxFitnessArr = null;
                    }
                    else
                    {
                        if (i == 0)
                        {
                            fitnessDict.Add(genome, new FitnessInfo[controller.Trials]);
                        }
                        dict.Add(genome, phenome);
                        //if (!dict.ContainsKey(genome))
                        //{
                        //    dict.Add(genome, phenome);
                        //    fitnessDict.Add(phenome, new FitnessInfo[_optimizer.Trials]);
                        //}
                        Coroutiner.StartCoroutine(_phenomeEvaluator.Evaluate(phenome));
                    }
                    yield return(new WaitForSeconds(controller.TrialDuration / 4));
                }
                yield return(new WaitForSeconds(controller.TrialDuration));

                foreach (TGenome genome in dict.Keys)
                {
                    TPhenome phenome = dict[genome];
                    if (phenome != null)
                    {
                        FitnessInfo fitnessInfo = _phenomeEvaluator.GetLastFitness(phenome);

                        fitnessDict[genome][i] = fitnessInfo;
                    }
                }
            }
            foreach (TGenome genome in dict.Keys)
            {
                TPhenome phenome = dict[genome];
                if (phenome != null)
                {
                    double fitness = 0;

                    for (int i = 0; i < controller.Trials; i++)
                    {
                        fitness += fitnessDict[genome][i]._fitness;
                    }
                    var fit = fitness;
                    fitness /= controller.Trials; //Average fitness


                    genome.EvaluationInfo.SetFitness(fitness);
                    genome.EvaluationInfo.AuxFitnessArr = fitnessDict[genome][0]._auxFitnessArr;
                }
            }
        }
Exemplo n.º 27
0
 public void Execute()
 {
     enumerator = CheckTouch();
     Coroutiner.StartCoroutine(enumerator);
 }
Exemplo n.º 28
0
        /// <summary>
        /// This is the main function in this class. It translates every genome
        /// (neural network description) into a phenome (functional description
        /// of the genome which gets input values and returns output values).
        /// Then it instantiates units with this phenomes as controllers and
        /// allows them a time to do whatever they must. Finally fitness values
        /// are assigned for each genome and units are destroyed.
        /// </summary>
        private IEnumerator evaluateList(IList <TGenome> genomeList)
        {
            // We do not want to lose track of which phenome corresponds to each
            // genome!
            Dictionary <TGenome, TPhenome> dict = new Dictionary <TGenome, TPhenome>();
            // If there is more than one trial we need to write down the fitness
            // value obtained by units in each case.
            Dictionary <TGenome, FitnessInfo[]> fitnessDict =
                new Dictionary <TGenome, FitnessInfo[]>();

            // Units can be tested in several trials to get an average evaluation
            for (int i = 0; i < _optimizer.Trials; i++)
            {
                Utility.Log("Iteration " + (i + 1));
                _phenomeEvaluator.Reset();
                dict = new Dictionary <TGenome, TPhenome>();
                foreach (TGenome genome in genomeList)
                {
                    // Makes a phenome from each genome. In some cases non-viable
                    // genomes are allowed. Those get fitness = 0.
                    TPhenome phenome = _genomeDecoder.Decode(genome);
                    if (null == phenome)
                    {   // Non-viable genome.
                        genome.EvaluationInfo.SetFitness(0.0);
                        genome.EvaluationInfo.AuxFitnessArr = null;
                    }
                    else
                    {
                        // There may be more than one trial. Every genome needs
                        // a fitness result for each. So we allocate enough space
                        // in the dictionary for this (this is why the value in
                        // the dictionary is an array). Allocation needs only
                        // happen once, thus if (i == 0).
                        if (i == 0)
                        {
                            fitnessDict.Add(genome, new FitnessInfo[_optimizer.Trials]);
                        }
                        dict.Add(genome, phenome);
                        //if (!dict.ContainsKey(genome))
                        //{
                        //    dict.Add(genome, phenome);
                        //    fitnessDict.Add(phenome, new FitnessInfo[_optimizer.Trials]);
                        //}
                        // This is where the unit is actually instantiated and
                        // where its fitness is evaluated
                        Coroutiner.StartCoroutine(_phenomeEvaluator.Evaluate(phenome));
                    }
                }

                // The previous coroutine will wait this period of time before
                // calculating the fitness values.
                yield return(new WaitForSeconds(_optimizer.TrialDuration));

                // Now we can store the fitness values.
                foreach (TGenome genome in dict.Keys)
                {
                    TPhenome phenome = dict[genome];
                    if (phenome != null)
                    {
                        FitnessInfo fitnessInfo = _phenomeEvaluator.GetLastFitness(phenome);
                        fitnessDict[genome][i] = fitnessInfo;
                    }
                }
            }
            // Every genome has now a fitness value for each trial. Here we
            // process that information and get an average result.
            foreach (TGenome genome in dict.Keys)
            {
                TPhenome phenome = dict[genome];
                if (phenome != null)
                {
                    double fitness = 0;
                    for (int i = 0; i < _optimizer.Trials; i++)
                    {
                        fitness += fitnessDict[genome][i]._fitness;
                    }
                    var fit = fitness;
                    fitness /= _optimizer.Trials; // Averaged fitness
                    // Is any average fitness greated than the fitness target?
                    if (fit >= _optimizer.StoppingFitness)
                    {
                        //  Utility.Log("Fitness is " + fit + ",
                        //  stopping now because stopping fitness is " +
                        //  _optimizer.StoppingFitness);
                        _phenomeEvaluator.StopConditionSatisfied = true;
                    }
                    genome.EvaluationInfo.SetFitness(fitness);
                    genome.EvaluationInfo.AuxFitnessArr = fitnessDict[genome][0]._auxFitnessArr;
                }
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Progress forward by one generation. Perform one generation/iteration of the evolution algorithm.
        /// </summary>
        protected override IEnumerator PerformOneGeneration()
        {
            // Calculate statistics for each specie (mean fitness, target size, number of offspring to produce etc.)
            int offspringCount;

            SpecieStats[] specieStatsArr = CalcSpecieStats(out offspringCount);

            // Create offspring.
            List <TGenome> offspringList = CreateOffspring(specieStatsArr, offspringCount);

            // Trim species back to their elite genomes.
            bool emptySpeciesFlag = TrimSpeciesBackToElite(specieStatsArr);

            // Rebuild _genomeList. It will now contain just the elite genomes.
            RebuildGenomeList();

            // Append offspring genomes to the elite genomes in _genomeList. We do this before calling the
            // _genomeListEvaluator.Evaluate because some evaluation schemes re-evaluate the elite genomes
            // (otherwise we could just evaluate offspringList).
            _genomeList.AddRange(offspringList);

            // Evaluate genomes.
            yield return(Coroutiner.StartCoroutine(_genomeListEvaluator.Evaluate(_genomeList)));

            // Integrate offspring into species.
            if (emptySpeciesFlag)
            {
                // We have one or more terminated species. Therefore we need to fully re-speciate all genomes to divide them
                // evenly between the required number of species.

                // Clear all genomes from species (we still have the elite genomes in _genomeList).
                ClearAllSpecies();

                // Speciate genomeList.
                _speciationStrategy.SpeciateGenomes(_genomeList, _specieList);
            }
            else
            {
                // Integrate offspring into the existing species.
                _speciationStrategy.SpeciateOffspring(offspringList, _specieList);
            }
            //Debug.Assert(!TestForEmptySpecies(_specieList), "Speciation resulted in one or more empty species.");

            // Sort the genomes in each specie. Fittest first (secondary sort - youngest first).
            SortSpecieGenomes();

            // Update stats and store reference to best genome.
            UpdateBestGenome();
            UpdateStats();

            // Determine the complexity regulation mode and switch over to the appropriate set of evolution
            // algorithm parameters. Also notify the genome factory to allow it to modify how it creates genomes
            // (e.g. reduce or disable additive mutations).
            _complexityRegulationMode = _complexityRegulationStrategy.DetermineMode(_stats);
            _genomeFactory.SearchMode = (int)_complexityRegulationMode;
            switch (_complexityRegulationMode)
            {
            case ComplexityRegulationMode.Complexifying:
                _eaParams = _eaParamsComplexifying;
                break;

            case ComplexityRegulationMode.Simplifying:
                _eaParams = _eaParamsSimplifying;
                break;
            }

            // TODO: More checks.
            //Debug.Assert(_genomeList.Count == _populationSize);
        }
Exemplo n.º 30
0
        internal static void MakeGitHubApiCall(string url, Action <string> resultCallback)
        {
            var www = UnityWebRequest.Get(url);

            Coroutiner.StartCoroutine(Post(www, response => { OnGitHubSuccess(resultCallback, response); }, AppCenterEditorHelper.SharedErrorCallback));
        }