Пример #1
0
    /// <summary>
    /// Loads the simulation from save file of format version 1.
    /// </summary>
    /// <param name="filename">The Filename has to end on .txt .</param>
    /// <param name="content">The Content of the save file.</param>
    private static void LoadSimulationFromSaveFileV1(string filename, string content, SplitOptions splitOptions, CreatureBuilder creatureBuilder, Evolution evolution)
    {
        var creatureName = filename.Split('-')[0].Replace(" ", "");

        var components = content.Split(splitOptions.SPLIT_ARRAY, System.StringSplitOptions.None);

        // extract the save data from the file contents.
        var taskType = EvolutionTaskUtil.TaskForNumber(int.Parse(components[0].Replace(Environment.NewLine, "")));

        var timePerGen = int.Parse(components[1].Replace(Environment.NewLine, ""));

        var creatureData = components[2];

        CreatureSaver.LoadCreatureFromContents(creatureData, creatureBuilder);

        var bestChromosomesData = new List <string>(components[3].Split(splitOptions.NEWLINE_SPLIT, StringSplitOptions.None));
        var bestChromosomes     = new List <ChromosomeStats>();

        foreach (var chromosomeData in bestChromosomesData)
        {
            if (chromosomeData != "")
            {
                var chromosomeInfo  = ChromosomeInfo.FromString(chromosomeData);
                var chromosomeStats = new ChromosomeStats(chromosomeInfo.chromosome, new CreatureStats());
                chromosomeStats.stats.fitness = chromosomeInfo.fitness;

                bestChromosomes.Add(chromosomeStats);
            }
        }

        var chromosomeComponents = components[4].Split(splitOptions.NEWLINE_SPLIT, StringSplitOptions.None);
        var currentChromosomes   = new List <string>();

        foreach (var chromosome in chromosomeComponents)
        {
            if (chromosome != "")
            {
                currentChromosomes.Add(chromosome);
            }
        }

        var currentGeneration = bestChromosomes.Count + 1;

        var settings = new EvolutionSettings();

        settings.task           = taskType;
        settings.simulationTime = timePerGen;
        settings.populationSize = currentChromosomes.Count;

        var networkSettings = new NeuralNetworkSettings();

        evolution.Settings = settings;

        creatureBuilder.ContinueEvolution(evolution, () => {
            CreatureSaver.SaveCurrentCreatureName(creatureName);
            evolution.ContinueEvolution(currentGeneration, settings, networkSettings, bestChromosomes, currentChromosomes);
        });
    }
Пример #2
0
    /// <summary>
    /// Continues the evolution from the save state.
    ///
    /// This function call has to replace calls to StartEvolution (and therefore also SetupEvolution) when a simulation would be started
    /// from the beginning.
    ///
    /// </summary>
    /// <param name="generationNum">The generation number that the simulation should continue at from.</param>
    /// <param name="timePerGen">The time for each generation simulation.</param>
    /// <param name="bestChromosomes">The list of best chromosomes of the already simluated generations.</param>
    /// <param name="currentChromosomes">A list of chromosomes of creatures of the last (current) generation.</param>
    //public void ContinueEvolution(int generationNum, int timePerGen, List<ChromosomeInfo> bestChromosomes, List<string> currentChromosomes) {
    public void ContinueEvolution(int generationNum, EvolutionSettings evolutionSettings, NeuralNetworkSettings networkSettings, List <ChromosomeStats> bestChromosomes, List <string> currentChromosomes)
    {
        this.settings      = evolutionSettings;
        this.brainSettings = networkSettings;

        viewController = GameObject.Find("ViewController").GetComponent <ViewController>();
        Assert.IsNotNull(viewController);

        this.currentGenerationNumber = generationNum;
        this.currentChromosomes      = currentChromosomes.ToArray();

        creature.RemoveMuscleColliders();
        creature.Alive = false;
        running        = true;

        viewController.UpdateGeneration(generationNum);

        autoSaver = new AutoSaver();

        // Setup Evolution call
        CalculateDropHeight();

        BCController            = GameObject.Find("Best Creature Controller").GetComponent <BestCreaturesController>();
        BCController.dropHeight = dropHeight;
        BCController.Creature   = creature;

        BCController.SetBestChromosomes(bestChromosomes);
        BCController.ShowBCThumbScreen();
        BCController.RunBestCreatures(generationNum - 1);

        currentGeneration = CreateGeneration();

        // Batch simulation
        currentlySimulatingBatch = 1;
        simulateInBatchesCached  = settings.simulateInBatches;
        batchSizeCached          = settings.simulateInBatches ? settings.batchSize : settings.populationSize;
        var currentBatchSize = Mathf.Min(batchSizeCached, settings.populationSize - ((currentlySimulatingBatch - 1) * batchSizeCached));

        currentCreatureBatch = new Creature[currentBatchSize];

        Array.Copy(currentGeneration, 0, currentCreatureBatch, 0, currentBatchSize);

        creature.gameObject.SetActive(false);

        SimulateGeneration();

        var cameraFollow = Camera.main.GetComponent <CameraFollowScript>();

        cameraFollow.toFollow = currentGeneration[0];
        cameraFollow.currentlyWatchingIndex = 0;

        RefreshVisibleCreatures();
    }
Пример #3
0
    /// <summary>
    /// Loads the currently stored Evolution settings.
    /// </summary>
    /// <returns>The evolution settings.</returns>
    private EvolutionSettings LoadEvolutionSettings()
    {
        var settingsString = PlayerPrefs.GetString(EVOLUTION_SETTINGS_KEY, "");

        if (settingsString == "")
        {
            // Default settings
            return(new EvolutionSettings());
        }

        return(EvolutionSettings.Decode(settingsString));
    }
Пример #4
0
    public static EvolutionSettings Decode(string encoded)
    {
        var parts    = encoded.Split('#');
        var settings = new EvolutionSettings();

        settings.keepBestCreatures = bool.Parse(parts[1]);
        settings.simulationTime    = int.Parse(parts[2]);
        settings.populationSize    = int.Parse(parts[3]);
        settings.simulateInBatches = bool.Parse(parts[4]);
        settings.batchSize         = int.Parse(parts[5]);
        settings.task         = EvolutionTaskUtil.TaskFromString(parts[6]);
        settings.mutationRate = int.Parse(parts[7]);

        return(settings);
    }
Пример #5
0
    /// <summary>
    /// Loads the simulation from save file with the format version 2
    /// </summary>
    /// <param name="filename">The Filename has to end on .txt .</param>
    /// <param name="content">The Content of the save file.</param>
    private static void LoadSimulationFromSaveFileV2(string filename, string content, SplitOptions splitOptions, CreatureBuilder creatureBuilder, Evolution evolution)
    {
        var creatureName = filename.Split('-')[0].Replace(" ", "");

        var components = content.Split(splitOptions.SPLIT_ARRAY, System.StringSplitOptions.None);

        var evolutionSettings = EvolutionSettings.Decode(components[1]);
        var networkSettings   = NeuralNetworkSettings.Decode(components[2]);

        var creatureData = components[3];

        CreatureSaver.LoadCreatureFromContents(creatureData, creatureBuilder);

        var bestChromosomesData = new List <string>(components[4].Split(splitOptions.NEWLINE_SPLIT, StringSplitOptions.None));
        var bestChromosomes     = new List <ChromosomeStats>();

        foreach (var chromosomeData in bestChromosomesData)
        {
            if (chromosomeData != "")
            {
                bestChromosomes.Add(ChromosomeStats.FromString(chromosomeData));
            }
        }

        var chromosomeComponents = components[5].Split(splitOptions.NEWLINE_SPLIT, StringSplitOptions.None);
        var currentChromosomes   = new List <string>();

        foreach (var chromosome in chromosomeComponents)
        {
            if (chromosome != "")
            {
                currentChromosomes.Add(chromosome);
            }
        }

        var currentGeneration = bestChromosomes.Count + 1;

        evolution.Settings = evolutionSettings;

        creatureBuilder.ContinueEvolution(evolution, () => {
            CreatureSaver.SaveCurrentCreatureName(creatureName);
            evolution.ContinueEvolution(currentGeneration, evolutionSettings, networkSettings, bestChromosomes, currentChromosomes);
        });
    }
Пример #6
0
        private void LoadState(State curState)
        {
            tableLayoutPanel1.Controls.Remove(_currentControl);

            switch (curState)
            {
            case State.Start:
                break;

            case State.FeatureModel:
                if (_featureModelForm == null)
                {
                    _featureModelForm = new FeatureModel(_model, button2);
                }

                button2.Visible = true;
                _currentControl = _featureModelForm;
                label1.Text     = @"Feature Model Settings";
                button1.Enabled = false;
                break;

            case State.Features:
                button1.Visible = true;
                if (_featureForm == null)
                {
                    _featureForm = new Features(_model, button2);
                }
                _currentControl = _featureForm;
                button1.Enabled = true;
                label1.Text     = @"Feature Distribution";
                break;

            case State.Interaction:
                if (_interacForm == null)
                {
                    _interacForm = new InteractionControl(_model, button2);
                }
                _currentControl = _interacForm;
                label1.Text     = @"Interaction Distribution";
                break;

            case State.Variant:
                if (_variantForm == null)
                {
                    _variantForm = new TargetVariant(_model, button2);
                }
                _currentControl = _variantForm;
                label1.Text     = @"Variant Distribution";
                break;

            case State.Generate:
                if (_varGen == null)
                {
                    _varGen = new VariantGenerationControl(_model, button2);
                }
                _currentControl = _varGen;
                label1.Text     = @"Variant Generation Settings";
                break;

            case State.EvolutionSettings:
                if (_evoSetting == null)
                {
                    _evoSetting = new EvolutionSettings(_model, button2);
                }
                _currentControl = _evoSetting;
                label1.Text     = @"Evolutionary Algorithm Settings";
                break;

            case State.Evolution:
                if (_evolution == null)
                {
                    _evolution = new Evolution(_model, button2);
                }
                _currentControl = _evolution;
                label1.Text     = @"Evolutionary Algorithm";
                button2.Enabled = true;
                break;

            case State.Results:
                if (_solution == null)
                {
                    _solution = new SolutionVis(_model);
                }
                button2.Enabled = false;
                _currentControl = _solution;
                label1.Text     = @"Solutions";
                break;

            default:
                return;
            }
            var sml = _currentControl as IStateModelLoader;

            sml?.LoadSettings();
            _currentControl.Dock    = DockStyle.Fill;
            _currentControl.Padding = new Padding(10);
            tableLayoutPanel1.Controls.Add(_currentControl, 0, 1);
        }
Пример #7
0
    /// <summary>
    /// Saves the given information about an evolution simulation of a creature in a file, so that
    /// it can be loaded and continued at the same generation again.
    /// The filename cannot contain dots (.)
    /// Throws: IllegalFilenameException
    ///
    /// Returns: The filename of the saved file.
    /// </summary>
    //public static string WriteSaveFile(string creatureName, Evolution.Task task, int timePerGen, int generationNumber, string creatureSaveData, List<ChromosomeInfo> bestChromosomes, List<string> currentChromosomes) {
    public static string WriteSaveFile(string creatureName, EvolutionSettings settings, NeuralNetworkSettings networkSettings, int generationNumber, string creatureSaveData, List <ChromosomeStats> bestChromosomes, List <string> currentChromosomes)
    {
        var splitOptions = new SplitOptions();

        var date = System.DateTime.Now.ToString("yyyy-MM-dd");
        //var taskName = Evolution.TaskToString(task);

        var filename = string.Format("{0} - {1} - {2} - Gen({3}).txt", creatureName, settings.task, date, generationNumber);            // MAYBE IMPORTANT FOR THE FUTURE: Changed from Gen:i to Gen(i)

        var stringBuilder = new StringBuilder();

        // Add the task type
        //stringBuilder.AppendLine(((int)task).ToString());

        // Add the version number
        stringBuilder.AppendLine(string.Format("v {0}", version.ToString()));
        stringBuilder.Append(splitOptions.COMPONENT_SEPARATOR);

        // Add the time per generation
        //stringBuilder.AppendLine(settings.simulationTime.ToString());
        //stringBuilder.Append(COMPONENT_SEPARATOR);

        // Add the encoded evolution settings
        stringBuilder.AppendLine(settings.Encode());
        stringBuilder.Append(splitOptions.COMPONENT_SEPARATOR);

        // Add the encoded neural network settings
        stringBuilder.AppendLine(networkSettings.Encode());
        stringBuilder.Append(splitOptions.COMPONENT_SEPARATOR);

        // Add the creature save data
        stringBuilder.AppendLine(creatureSaveData);
        stringBuilder.Append(splitOptions.COMPONENT_SEPARATOR);

        // Add the list of best chromosomes
        foreach (var chromosome in bestChromosomes)
        {
            stringBuilder.AppendLine(chromosome.ToString());
        }
        stringBuilder.Append(splitOptions.COMPONENT_SEPARATOR);

        // Add the list of current chromosomes
        foreach (var chromosome in currentChromosomes)
        {
            stringBuilder.AppendLine(chromosome);
        }
        stringBuilder.Append(splitOptions.COMPONENT_SEPARATOR);

        var path = RESOURCE_PATH;         //Path.Combine(RESOURCE_PATH, SAVE_FOLDER);

        path = Path.Combine(path, filename);

        int counter = 2;

        while (System.IO.File.Exists(path))
        {
            //var pattern = new Regex(@"( \d+)?.txt");
            var pattern = @"( \d+)?.txt";

            filename = Regex.Replace(filename, pattern, string.Format(" {0}.txt", counter));
            path     = Path.Combine(RESOURCE_PATH, filename);
            //path = path.Replace(".txt", string.Format(" ({0}).txt", counter));
            //filename = filename.Replace(".txt", string.Format(" ({0}).txt", counter));
            counter++;
        }

        CreateSaveFolder();
        File.WriteAllText(path, stringBuilder.ToString());

        return(filename);
    }
Пример #8
0
 private void SaveEvolutionSettings(EvolutionSettings settings)
 {
     PlayerPrefs.SetString(EVOLUTION_SETTINGS_KEY, settings.Encode());
 }