示例#1
0
    // Constructor
    public AgentGenome(int index)
    {
        this.index = index;

        bodyGenome  = new BodyGenome(); // empty constructors:
        brainGenome = new BrainGenome();
    }
    private void AgentCrossover(int playerIndex)
    {
        List <BrainGenome> newGenBrainGenomeList = new List <BrainGenome>(); // new population!

        FitnessManager          fitnessManager          = teamsConfig.playersList[playerIndex].fitnessManager;
        TrainingSettingsManager trainingSettingsManager = teamsConfig.playersList[playerIndex].trainingSettingsManager;

        // Keep top-half peformers + mutations:
        for (int x = 0; x < teamsConfig.playersList[playerIndex].agentGenomeList.Count; x++)
        {
            if (x == 0)
            {
                BrainGenome parentGenome = teamsConfig.playersList[playerIndex].agentGenomeList[fitnessManager.rankedIndicesList[x]].brainGenome;
                //parentGenome.index = 0;
                newGenBrainGenomeList.Add(parentGenome);
            }
            else
            {
                BrainGenome newBrainGenome = new BrainGenome();

                int parentIndex = fitnessManager.GetAgentIndexByLottery();

                BrainGenome parentGenome = teamsConfig.playersList[playerIndex].agentGenomeList[parentIndex].brainGenome;

                newBrainGenome.SetToMutatedCopyOfParentGenome(parentGenome, trainingSettingsManager);
                newGenBrainGenomeList.Add(newBrainGenome);
            }
        }

        for (int i = 0; i < teamsConfig.playersList[playerIndex].agentGenomeList.Count; i++)
        {
            teamsConfig.playersList[playerIndex].agentGenomeList[i].brainGenome = newGenBrainGenomeList[i];
        }
    }
示例#3
0
    public AgentGenome Mutate(AgentGenome parentGenome, bool bodySettings, bool brainSettings)
    {
        //AgentGenome parentGenome = leaderboardGenomesList[selectedIndex].candidateGenome;

        //***EAC Creature NAME mutation here???
        string parentName = parentGenome.name;
        int randIndex = Random.Range(0, parentName.Length - 1);
        string frontHalf = parentName.Substring(0, randIndex);
        string middleChar = parentName.Substring(randIndex, 1);
        string backHalf = parentName.Substring(randIndex + 1);
        if (RandomStatics.CoinToss(.05f)) {
            middleChar = RandomStatics.GetRandomLetter();
        }
        frontHalf += middleChar;
        string newName = RandomStatics.CoinToss(.025f) ? backHalf + frontHalf : frontHalf + backHalf;

        //--------------------------------------------------------------------------------------------------------------------

        tempMutationSettings = bodySettings ? mutationSettings : cachedNoneMutationSettings;
        BodyGenome newBodyGenome = new BodyGenome(parentGenome.bodyGenome, tempMutationSettings);

        tempMutationSettings = brainSettings ? mutationSettings : cachedNoneMutationSettings;
        BrainGenome newBrainGenome = new BrainGenome(parentGenome.brainGenome, newBodyGenome, tempMutationSettings);

        return new AgentGenome(newBodyGenome, newBrainGenome, parentGenome.generationCount + 1, newName);
    }
示例#4
0
 public AgentGenome(BodyGenome bodyGenome, BrainGenome brainGenome, int generationCount, string name)
 {
     this.bodyGenome      = bodyGenome;
     this.brainGenome     = brainGenome;
     this.generationCount = generationCount;
     this.name            = name;
     //Debug.Log("Constructing AgentGenome via mutation");
 }
示例#5
0
    public void Refresh()
    {
        genome = cand.candidateGenome;
        brain  = genome.brainGenome;
        core   = genome.bodyGenome.coreGenome;

        float lifespan = cand.performanceData.totalTicksAlive;

        textGeneration.text = "Gen: " + genome.generationCount;
        textBodySize.text   = "Size: " + (100f * core.creatureBaseLength).ToString("F0") + ", Aspect 1:" + (1f / core.creatureAspectRatio).ToString("F0");
        textBrainSize.text  = "Brain Size: " + brain.inOutNeurons.Count + "--" + brain.links.Count;
    }
示例#6
0
    public void RebuildBrain(BrainGenome genome, Agent agent)
    {
        // Create Neurons:
        neuronList = new List <Neuron>();
        IDs        = new Dictionary <NID, int>();
        // I need access to all of the Modules in order to link the neuron values to the module values!!!!
        for (int i = 0; i < genome.bodyNeuronList.Count; i++)
        {
            Neuron neuron = new Neuron();
            agent.MapNeuronToModule(genome.bodyNeuronList[i].nid, neuron);
            IDs.Add(genome.bodyNeuronList[i].nid, i);
            neuronList.Add(neuron);
        }
        for (int i = 0; i < genome.hiddenNeuronList.Count; i++)    // REVISIT
        {
            Neuron neuron = new Neuron();
            agent.MapNeuronToModule(genome.hiddenNeuronList[i].nid, neuron);
            IDs.Add(genome.hiddenNeuronList[i].nid, i);
            neuronList.Add(neuron);
        }
        //Debug.Log("RebuildBrain " + genome.bodyNeuronList.Count + ", " + neuronList.Count.ToString());

        // Create Axons:
        axonList = new List <Axon>();
        for (int i = 0; i < genome.linkList.Count; i++)
        {
            // find out neuronIDs:
            int fromID = -1;
            if (IDs.TryGetValue(new NID(genome.linkList[i].fromModuleID, genome.linkList[i].fromNeuronID), out fromID))
            {
            }
            else
            {
                Debug.LogError("fromNID NOT FOUND " + genome.linkList[i].fromModuleID.ToString() + ", " + genome.linkList[i].fromNeuronID.ToString());
            }
            int toID = -1;
            if (IDs.TryGetValue(new NID(genome.linkList[i].toModuleID, genome.linkList[i].toNeuronID), out toID))
            {
            }
            else
            {
                Debug.LogError("toNID NOT FOUND " + genome.linkList[i].fromModuleID.ToString() + ", " + genome.linkList[i].fromNeuronID.ToString());
            }

            //Debug.Log(fromID.ToString() + " --> " + toID.ToString() + ", " + genome.linkList[i].weight.ToString());
            //int fromID = IDs < new NID(genome.linkList[i].fromModuleID, genome.linkList[i].fromNeuronID) >;
            Axon axon = new Axon(fromID, toID, genome.linkList[i].weight);
            axonList.Add(axon);
        }

        //PrintBrain();
    }
示例#7
0
    /// Create Neurons and Axons
    public void RebuildBrain(BrainGenome genome, Agent agent)
    {
        //Debug.Log($"Rebuilding brain with {genome.inOutNeurons.Count} neurons in genome, " +
        //          $"and {genome.linkCount} links in genome");

        neurons = new List <Neuron>();

        RebuildNeurons(genome.inOutNeurons, agent);
        RebuildNeurons(genome.hiddenNeurons, agent);

        RebuildAxons(genome);
        //PrintBrain();
    }
示例#8
0
    public void SetToMutatedCopyOfParentGenome(BrainGenome parentGenome, BodyGenome bodyGenome, MutationSettingsInstance settings)
    {
        /*
         * //this.bodyNeuronList = parentGenome.bodyNeuronList; // UNSUSTAINABLE!!! might work now since all neuronLists are identical ******
         *
         * // Copy from parent brain or rebuild neurons from scratch based on the new mutated bodyGenome???? --- ******
         * for(int i = 0; i < parentGenome.bodyNeuronList.Count; i++) {
         *  NeuronGenome newBodyNeuronGenome = new NeuronGenome(parentGenome.bodyNeuronList[i]);
         *  this.bodyNeuronList.Add(newBodyNeuronGenome);
         * }
         * // Alternate: SetBodyNeuronsFromTemplate(BodyGenome templateBody);
         */

        // Rebuild BodyNeuronGenomeList from scratch based on bodyGenome
        InitializeBodyNeuronList();
        InitializeIONeurons(bodyGenome);

        hiddenNeurons = MutateHiddenNeurons(parentGenome.hiddenNeurons);
        links         = MutateLinks(parentGenome.links, settings);

        if (RandomStatics.CoinToss(settings.brainCreateNewLinkChance))
        {
            AddNewLink(settings);
        }

        if (RandomStatics.CoinToss(settings.brainCreateNewHiddenNodeChance))
        {
            AddNewHiddenNeuron();
        }

        var newNeurons = GetNewlyUnlockedNeurons(bodyGenome);

        //Debug.Log($"Initializing axons with {newNeurons.Count} new neurons from " +
        //          $"{bodyGenome.newlyUnlockedNeuronInfo.Count} new tech.");
        foreach (var neuron in newNeurons)
        {
            SortIONeuron(neuron);
            LinkNeuronToLayer(neuron);
        }
        //RemoveVestigialLinks();
    }
示例#9
0
    // * WPP: expose values in editor
    public void SetTexture(BrainGenome brain)
    {
        int width = Mathf.Min(WIDTH, brain.linkCount);

        texture.Resize(width, 1);

        for (int x = 0; x < width; x++)
        {
            Color testColor;

            if (brain.linkCount > x)
            {
                float weightVal = brain.links[x].weight;
                testColor = new Color(weightVal * 0.5f + 0.5f, weightVal * 0.5f + 0.5f, weightVal * 0.5f + 0.5f);

                if (weightVal < -0.25f)
                {
                    testColor = Color.Lerp(testColor, Color.black, 0.15f);
                }
                else if (weightVal > 0.25f)
                {
                    testColor = Color.Lerp(testColor, Color.white, 0.15f);
                }
                else
                {
                    testColor = Color.Lerp(testColor, Color.gray, 0.15f);
                }
            }
            else
            {
                testColor = Color.black; // CLEAR
            }

            texture.SetPixel(x, 0, testColor);
        }

        texture.Apply();
    }
示例#10
0
    void RebuildAxons(BrainGenome genome)
    {
        axons = new List <Axon>();

        if (genome.linkCount <= 0)
        {
            Debug.LogError("Cannot rebuild axons because genome has zero links");
            return;
        }

        foreach (var link in genome.links)
        {
            var from = GetMatchingNeuron(neurons, link.from);
            var to   = GetMatchingNeuron(neurons, link.to);

            if (from == null || to == null)
            {
                continue;
            }

            Axon axon = new Axon(from, to, link.weight);
            axons.Add(axon);
        }
    }
示例#11
0
 public BrainGenome(BrainGenome parentGenome, BodyGenome bodyGenome, MutationSettingsInstance mutationSettings)
 {
     SetToMutatedCopyOfParentGenome(parentGenome, bodyGenome, mutationSettings);
 }
示例#12
0
 void ConstructRandom(float initialConnectionDensity, int hiddenNeuronCount)
 {
     bodyGenome  = new BodyGenome();
     brainGenome = new BrainGenome(bodyGenome, initialConnectionDensity, hiddenNeuronCount);
 }
示例#13
0
 public Brain(BrainGenome genome, Agent agent)
 {
     RebuildBrain(genome, agent);
 }
示例#14
0
    //CritterModuleFoodSensorsGenome foodGenome;

    // * WPP: break code sections into methods, call from here
    private void UpdateUI()
    {
        if (!agent)
        {
            return;
        }

        agentIndex      = agent.index;
        candidate       = agent.candidateRef;
        coreModule      = agent.coreModule;
        brain           = agent.brain;
        candidateGenome = candidate.candidateGenome;
        brainGenome     = candidateGenome.brainGenome;
        bodyGenome      = candidateGenome.bodyGenome;
        coreGenome      = bodyGenome.coreGenome;
        foodModule      = agent.foodModule;
        movementModule  = agent.movementModule;
        //foodGenome = bodyGenome.foodGenome;

        if (!agent.isInert)
        {
            // DebugTxt1 : use this for selected creature stats:
            int curCount = 0;
            int maxCount = 1;
            if (agent.isEgg)
            {
                curCount = agent.lifeStageTransitionTimeStepCounter;
                maxCount = agent.gestationDurationTimeSteps;
            }
            if (agent.isMature)
            {
                curCount = agent.ageCounter;
                maxCount = agent.maxAgeTimeSteps;
            }
            if (agent.isDead)
            {
                curCount = agent.lifeStageTransitionTimeStepCounter;
                maxCount = curCount; // agentRef._DecayDurationTimeSteps;
            }
            int    progressPercent      = Mathf.RoundToInt((float)curCount / (float)maxCount * 100f);
            string lifeStageProgressTxt = " " + agent.curLifeStage + " " + curCount + "/" + maxCount + "  " + progressPercent + "% ";

            // &&&& INDIVIDUAL AGENT: &&&&
            string debugTxtAgent = "";
            debugTxtAgent += "CRITTER# [" + agentIndex + "]     SPECIES# [" + agent.speciesIndex + "]\n\n";
            // Init Attributes:
            // Body:
            debugTxtAgent += "Base Size: " + coreGenome.creatureBaseLength.ToString("F2") + ",  Aspect: " + coreGenome.creatureAspectRatio.ToString("F2") + "\n";
            debugTxtAgent += "Fullsize Dimensions: ( " + agent.fullSizeBoundingBox.x.ToString("F2") + ", " + agent.fullSizeBoundingBox.y.ToString("F2") + ", " + agent.fullSizeBoundingBox.z.ToString("F2") + " )\n";
            debugTxtAgent += "BONUS - Damage: " + coreModule.damageBonus.ToString("F2") + ", Speed: " + coreModule.speedBonus.ToString("F2") + ", Health: " + coreModule.healthBonus.ToString("F2") + ", Energy: " + coreModule.energyBonus.ToString("F2") + "\n";
            debugTxtAgent += "DIET - Decay: " + coreModule.digestEfficiencyDecay.ToString("F2") + ", Plant: " + coreModule.digestEfficiencyPlant.ToString("F2") + ", Meat: " + coreModule.digestEfficiencyMeat.ToString("F2") + "\n";
            //string mouthType = "Active";
            //if (agentRef.mouthRef.isPassive) { mouthType = "Passive"; }
            //debugTxtAgent += "Mouth: [" + mouthType + "]\n";
            debugTxtAgent += "# Neurons: " + brain.neurons.Count + ", # Axons: " + brain.axons.Count + "\n";
            debugTxtAgent += "# In/Out Nodes: " + brainGenome.inOutNeurons.Count + ", # Hidden Nodes: " + brainGenome.hiddenNeurons.Count + ", # Links: " + brainGenome.links.Count + "\n";

            debugTxtAgent += "\nSENSORS:\n";
            debugTxtAgent += "Comms= " + bodyGenome.data.hasComms + "\n";
            debugTxtAgent += "Enviro: WaterStats: " + bodyGenome.data.useWaterStats + ", Cardinals= " + bodyGenome.data.useCardinals + ", Diagonals= " + bodyGenome.data.useDiagonals + "\n";
            //debugTxtAgent += "Food: Nutrients= " + foodGenome.useNutrients + ", Pos= " + foodGenome.usePos + ",  Dir= " + foodGenome.useDir + ",  Stats= " + foodGenome.useStats + ", useEggs: " + foodGenome.useEggs + ", useCorpse: " + foodGenome.useCorpse + "\n";
            //debugTxtAgent += "Friend: Pos= " + bodyGenome.friendGenome.usePos + ",  Dir= " + bodyGenome.friendGenome.useDir + ",  Vel= " + bodyGenome.friendGenome.useVel + "\n";
            //debugTxtAgent += "Threat: Pos= " + bodyGenome.threatGenome.usePos + ",  Dir= " + bodyGenome.threatGenome.useDir + ",  Vel= " + bodyGenome.threatGenome.useVel + ",  Stats= " + bodyGenome.threatGenome.useStats + "\n";
            // Realtime Values:
            debugTxtAgent += "\nREALTIME DATA:";
            //debugTxtAgent += "\nExp: " + agentRef.totalExperience.ToString("F2") + ",  fitnessScore: " + agentRef.masterFitnessScore.ToString("F2") + ", LVL: " + agentRef.curLevel.ToString();
            debugTxtAgent += "\n(" + lifeStageProgressTxt + ") Growth: " + (agent.sizePercentage * 100f).ToString("F0") + "%, Age: " + agent.ageCounter + " Frames\n\n";

            debugTxtAgent += "Nearest Food: [" + foodModule.nearestFoodParticleIndex +
                             "] Amount: " + foodModule.nearestFoodParticleAmount.ToString("F4") +
                             "\nPos: ( " + foodModule.nearestFoodParticlePos.x.ToString("F2") +
                             ", " + foodModule.nearestFoodParticlePos.y.ToString("F2") +
                             " ), Dir: ( " + foodModule.foodPlantDirX[0].ToString("F2") +
                             ", " + foodModule.foodPlantDirY[0].ToString("F2") + " )" +
                             "\n";
            debugTxtAgent += "\nNutrients: " + foodModule.nutrientDensity[0].ToString("F4") + ", Stamina: " + coreModule.stamina[0].ToString("F3") + "\n";
            debugTxtAgent += "Gradient Dir: (" + foodModule.nutrientGradX[0].ToString("F2") + ", " + foodModule.nutrientGradY[0].ToString("F2") + ")\n";
            //debugTxtAgent += "Total Food Eaten -- Decay: n/a, Plant: " + agentRef.totalFoodEatenPlant.ToString("F2") + ", Meat: " + agentRef.totalFoodEatenZoop.ToString("F2") + "\nFood Stored: " + agentRef.coreModule.foodStored[0].ToString() + ", Corpse Food Amount: " + agentRef.currentBiomass.ToString("F3") + "\n";

            //debugTxtAgent += "\nFullSize: " + agentRef.fullSizeBoundingBox.ToString() + ", Volume: " + agentRef.fullSizeBodyVolume.ToString() + "\n";
            //debugTxtAgent += "( " + (agentRef.sizePercentage * 100f).ToString("F0") + "% )\n";

            debugTxtAgent += "\nCurVel: " + agent.curVel.ToString("F3") + ", CurAccel: " + agent.curAccel.ToString("F3") + ", AvgVel: " + agent.avgVel.ToString("F3") + "\n";

            debugTxtAgent += "\nWater Depth: " + agent.waterDepth.ToString("F3") + ", Vel: " + (agent.avgFluidVel * 10f).ToString("F3") + "\n";
            debugTxtAgent += "Throttle: [ " + movementModule.throttleX[0].ToString("F3") + ", " + movementModule.throttleY[0].ToString("F3") + " ]\n";
            debugTxtAgent += "FeedEffector: " + coreModule.mouthFeedEffector[0].ToString("F2") + "\n";
            debugTxtAgent += "AttackEffector: " + coreModule.mouthAttackEffector[0].ToString("F2") + "\n";
            debugTxtAgent += "DefendEffector: " + coreModule.defendEffector[0].ToString("F2") + "\n";
            debugTxtAgent += "DashEffector: " + coreModule.dashEffector[0].ToString("F2") + "\n";
            debugTxtAgent += "HealEffector: " + coreModule.healEffector[0].ToString("F2") + "\n";

            //+++++++++++++++++++++++++++++++++++++ CRITTER: ++++++++++++++++++++++++++++++++++++++++++++
            string debugTxtGlobalSim = "";
            debugTxtGlobalSim += "\n\nNumChildrenBorn: " + simulation.numAgentsBorn + ", numDied: " + simulation.numAgentsDied + ", ~Gen: " + ((float)simulation.numAgentsBorn / (float)simulation.numAgents);
            debugTxtGlobalSim += "\nSimulation Age: " + simulation.simAgeTimeSteps;
            debugTxtGlobalSim += "\nYear " + simulation.curSimYear + "\n\n";
            int numActiveSpecies = masterGenomePool.currentlyActiveSpeciesIDList.Count;
            debugTxtGlobalSim += numActiveSpecies + " Active Species:\n";

            for (int s = 0; s < numActiveSpecies; s++)
            {
                int speciesID = masterGenomePool.currentlyActiveSpeciesIDList[s];
                //int parentSpeciesID = simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].parentSpeciesID;
                int numCandidates = masterGenomePool.completeSpeciesPoolsList[speciesID].candidateGenomesList.Count;
                int numLeaders    = masterGenomePool.completeSpeciesPoolsList[speciesID].leaderboardGenomesList.Count;
                //int numBorn = simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].numAgentsEvaluated;
                int speciesPopSize = 0;
                //float avgFitness = simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgPerformanceData.totalTicksAlive;
                for (int a = 0; a < simulation.numAgents; a++)
                {
                    if (simulation.agents[a].speciesIndex == speciesID)
                    {
                        speciesPopSize++;
                    }
                }
                if (masterGenomePool.completeSpeciesPoolsList[speciesID].isFlaggedForExtinction)
                {
                    debugTxtGlobalSim += "xxx ";
                }

                /*debugTxtGlobalSim += "Species[" + speciesID.ToString() + "] p(" + parentSpeciesID.ToString() + "), size: " + speciesPopSize.ToString() + ", #cands: " + numCandidates.ToString() + ", numEvals: " + numBorn.ToString() +
                 *           ",   avgFitness: " + avgFitness.ToString("F2") +
                 *           ",   avgConsumption: (" + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgFoodEatenCorpse.ToString("F4") + ", " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgFoodEatenPlant.ToString("F4") + ", " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgFoodEatenZoop.ToString("F4") + ", " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgFoodEatenEgg.ToString("F4") + ", " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgFoodEatenCreature.ToString("F4") +
                 *           "),   avgBodySize: " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgBodySize.ToString("F3") +
                 *           ",   avgTalentSpec: (" + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgSpecAttack.ToString("F2") + ", " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgSpecDefend.ToString("F2") + ", " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgSpecSpeed.ToString("F2") + ", " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgSpecUtility.ToString("F2") +
                 *           "),   avgDiet: (" + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgFoodSpecDecay.ToString("F2") + ", " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgFoodSpecPlant.ToString("F2") + ", " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgFoodSpecMeat.ToString("F2") +
                 *           "),   avgNumNeurons: " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgNumNeurons.ToString("F1") +
                 *           ",   avgNumAxons: " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgNumAxons.ToString("F1") +
                 *           ", total: " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgFitnessScore.ToString("F2") +
                 *           ", avgExp: " + simManager.masterGenomePool.completeSpeciesPoolsList[speciesID].avgExperience.ToString() + "\n\n";*/
            }

            /*debugTxtGlobalSim += "\n\nAll-Time Species List:\n";
             * for (int p = 0; p < simManager.masterGenomePool.completeSpeciesPoolsList.Count; p++) {
             *  string extString = "Active!";
             *  if (simManager.masterGenomePool.completeSpeciesPoolsList[p].isExtinct) {
             *      extString = "Extinct!";
             *  }
             *  debugTxtGlobalSim += "Species[" + p.ToString() + "] p(" + simManager.masterGenomePool.completeSpeciesPoolsList[p].parentSpeciesID.ToString() + ") " + extString + "\n";
             * }*/

            textDebugTrainingInfo1.text = debugTxtAgent;
            textDebugTrainingInfo3.text = debugTxtGlobalSim;
        }

        string debugTxtResources = "";

        debugTxtResources += "GLOBAL RESOURCES:\n";
        debugTxtResources += "\nSunlight: " + environmentSettings._BaseSolarEnergy;
        debugTxtResources += "\nOxygen: " + simResourceManager.curGlobalOxygen;
        debugTxtResources += "\n     + " + simResourceManager.oxygenProducedByAlgaeReservoirLastFrame + " ( algae reservoir )";
        debugTxtResources += "\n     + " + simResourceManager.oxygenProducedByPlantParticlesLastFrame + " ( algae particles )";
        debugTxtResources += "\n     - " + simResourceManager.oxygenUsedByDecomposersLastFrame + " ( decomposers )";
        debugTxtResources += "\n     - " + simResourceManager.oxygenUsedByAnimalParticlesLastFrame + " ( zooplankton )";
        debugTxtResources += "\n     - " + simResourceManager.oxygenUsedByAgentsLastFrame + " ( agents )";
        debugTxtResources += "\nNutrients: " + simResourceManager.curGlobalNutrients;
        debugTxtResources += "\n     + " + simResourceManager.nutrientsProducedByDecomposersLastFrame + " ( decomposers )";
        debugTxtResources += "\n     - " + simResourceManager.nutrientsUsedByAlgaeReservoirLastFrame + " ( algae reservoir )";
        debugTxtResources += "\n     - " + simResourceManager.nutrientsUsedByPlantParticlesLastFrame + " ( algae particles )";
        debugTxtResources += "\nDetritus: " + simResourceManager.curGlobalDetritus;
        debugTxtResources += "\n     + " + simResourceManager.wasteProducedByAlgaeReservoirLastFrame + " ( algae reservoir )";
        debugTxtResources += "\n     + " + simResourceManager.wasteProducedByPlantParticlesLastFrame + " ( algae particles )";
        debugTxtResources += "\n     + " + simResourceManager.wasteProducedByAnimalParticlesLastFrame + " ( zooplankton )";
        debugTxtResources += "\n     + " + simResourceManager.wasteProducedByAgentsLastFrame + " ( agents )";
        debugTxtResources += "\n     - " + simResourceManager.detritusRemovedByDecomposersLastFrame + " ( decomposers )";
        debugTxtResources += "\nDecomposers: " + simResourceManager.curGlobalDecomposers;
        debugTxtResources += "\nAlgae (Reservoir): " + simResourceManager.curGlobalAlgaeReservoir;
        debugTxtResources += "\nAlgae (Particles): " + simResourceManager.curGlobalPlantParticles;
        debugTxtResources += "\nZooplankton: " + simResourceManager.curGlobalAnimalParticles;
        debugTxtResources += "\nLive Agents: " + simResourceManager.curGlobalAgentBiomass;
        debugTxtResources += "\nDead Agents: " + simResourceManager.curGlobalCarrionVolume;
        debugTxtResources += "\nEggSacks: " + simResourceManager.curGlobalEggSackVolume;
        debugTxtResources += "\nGlobal Mass: " + simResourceManager.curTotalMass;
        Vector4 resourceGridSample = simulation.SampleTexture(vegetationManager.resourceGridRT1, theCursorCzar.curMousePositionOnWaterPlane / SimulationManager._MapSize);
        Vector4 simTansferSample   = simulation.SampleTexture(vegetationManager.resourceSimTransferRT, theCursorCzar.curMousePositionOnWaterPlane / SimulationManager._MapSize) * 100f;

        //Debug.Log("curMousePositionOnWaterPlane: " + curMousePositionOnWaterPlane.ToString());
        debugTxtResources += "\nresourceGridSample: (" + resourceGridSample.x.ToString("F4") + ", " + resourceGridSample.y.ToString("F4") + ", " + resourceGridSample.z.ToString("F4") + ", " + resourceGridSample.w.ToString("F4") + ")";
        debugTxtResources += "\nsimTansferSample: (" + simTansferSample.x.ToString("F4") + ", " + simTansferSample.y.ToString("F4") + ", " + simTansferSample.z.ToString("F4") + ", " + simTansferSample.w.ToString("F4") + ")";

        textDebugTrainingInfo2.text = debugTxtResources;

        if (debugTextureViewerArray == null)
        {
            CreateDebugRenderViewerArray();
        }

        debugTextureViewerMat.SetPass(0);
        debugTextureViewerMat.SetVector("_Zoom", _Zoom);
        debugTextureViewerMat.SetFloat("_Amplitude", _Amplitude);
        debugTextureViewerMat.SetVector("_ChannelMask", _ChannelMask);
        debugTextureViewerMat.SetInt("_ChannelSoloIndex", _ChannelSoloIndex);
        debugTextureViewerMat.SetFloat("_IsChannelSolo", _IsChannelSolo);
        debugTextureViewerMat.SetFloat("_Gamma", _Gamma);
        //debugTextureViewerMat.
        if (debugTextureViewerArray[_DebugTextureIndex])
        {
            debugTextureViewerMat.SetTexture("_MainTex", debugTextureViewerArray[_DebugTextureIndex]);
            int      channelID       = 4;
            string[] channelLabelTxt = new string[5];
            channelLabelTxt[0] = " (X Solo)";
            channelLabelTxt[1] = " (Y Solo)";
            channelLabelTxt[2] = " (Z Solo)";
            channelLabelTxt[3] = " (W Solo)";
            channelLabelTxt[4] = " (Color)";
            if (_IsChannelSolo > 0.5f)
            {
                channelID = _ChannelSoloIndex;
            }
            textDebugTextureName.text = debugTextureViewerArray[_DebugTextureIndex].name + channelLabelTxt[channelID];
        }

        textDebugTextureZoomX.text            = _Zoom.x.ToString();
        textDebugTextureZoomY.text            = _Zoom.y.ToString();
        textDebugTextureAmplitude.text        = _Amplitude.ToString();
        textDebugTextureSoloChannelIndex.text = _ChannelSoloIndex.ToString();
        textDebugTextureGamma.text            = _Gamma.ToString();
    }
示例#15
0
 public Brain(BrainGenome genome, Agent agent)
 {
     //Debug.Log("Brain() genome: " + genome.bodyNeuronList.Count.ToString());
     RebuildBrain(genome, agent);
 }
示例#16
0
    private void NextGeneration()
    {
        string fitTxt       = "Fitness Scores:\n";
        float  totalFitness = 0f;
        float  minScore     = float.PositiveInfinity;
        float  maxScore     = float.NegativeInfinity;

        for (int f = 0; f < trainingPopulationSize; f++)
        {
            fitTxt       += f.ToString() + ": " + rawFitnessScoresArray[f].ToString() + "\n";
            totalFitness += rawFitnessScoresArray[f];
            minScore      = Mathf.Min(minScore, rawFitnessScoresArray[f]);
            maxScore      = Mathf.Max(maxScore, rawFitnessScoresArray[f]);
        }
        Debug.Log(fitTxt);
        avgFitnessLastGen = totalFitness / (float)trainingPopulationSize;

        // Process Fitness (bigger is better so lottery works)
        float scoreRange = maxScore - minScore;

        if (scoreRange == 0f)
        {
            scoreRange = 1f;  // avoid divide by zero
        }
        for (int f = 0; f < trainingPopulationSize; f++)
        {
            rawFitnessScoresArray[f] = 1f - ((rawFitnessScoresArray[f] - minScore) / scoreRange); // normalize and invert scores for fitness lottery
        }

        // Sort Fitness Scores
        int[]   rankedIndicesList = new int[rawFitnessScoresArray.Length];
        float[] rankedFitnessList = new float[rawFitnessScoresArray.Length];

        // populate arrays:
        for (int i = 0; i < rawFitnessScoresArray.Length; i++)
        {
            rankedIndicesList[i] = i;
            rankedFitnessList[i] = rawFitnessScoresArray[i];
        }
        for (int i = 0; i < rawFitnessScoresArray.Length - 1; i++)
        {
            for (int j = 0; j < rawFitnessScoresArray.Length - 1; j++)
            {
                float swapFitA = rankedFitnessList[j];
                float swapFitB = rankedFitnessList[j + 1];
                int   swapIdA  = rankedIndicesList[j];
                int   swapIdB  = rankedIndicesList[j + 1];

                if (swapFitA < swapFitB)    // bigger is better now after inversion
                {
                    rankedFitnessList[j]     = swapFitB;
                    rankedFitnessList[j + 1] = swapFitA;
                    rankedIndicesList[j]     = swapIdB;
                    rankedIndicesList[j + 1] = swapIdA;
                }
            }
        }
        string fitnessRankText = "";

        for (int i = 0; i < rawFitnessScoresArray.Length; i++)
        {
            fitnessRankText += "[" + rankedIndicesList[i].ToString() + "]: " + rankedFitnessList[i].ToString() + "\n";
        }

        // CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER CROSSOVER
        List <BrainGenome> newGenBrainGenomeList = new List <BrainGenome>(); // new population!

        //FitnessManager fitnessManager = teamsConfig.playersList[playerIndex].fitnessManager;
        //TrainingSettingsManager trainingSettingsManager = teamsConfig.playersList[playerIndex].trainingSettingsManager;

        // Keep top-half peformers + mutations:
        for (int x = 0; x < agentGenomeList.Count; x++)
        {
            if (x == 0)
            {
                BrainGenome parentGenome = agentGenomeList[rankedIndicesList[x]].brainGenome;  // keep top performer as-is
                newGenBrainGenomeList.Add(parentGenome);
            }
            else
            {
                BrainGenome newBrainGenome = new BrainGenome();
                int         parentIndex    = GetAgentIndexByLottery(rankedFitnessList, rankedIndicesList);
                BrainGenome parentGenome   = agentGenomeList[parentIndex].brainGenome;
                newBrainGenome.SetToMutatedCopyOfParentGenome(parentGenome, trainingSettingsManager);
                newGenBrainGenomeList.Add(newBrainGenome);
            }
        }

        for (int i = 0; i < agentGenomeList.Count; i++)
        {
            agentGenomeList[i].brainGenome = newGenBrainGenomeList[i];
        }

        // Reset
        ResetTrainingForNewGen();

        trainingSettingsManager.mutationChance   *= 0.996f;
        trainingSettingsManager.mutationStepSize *= 0.998f;

        curTrainingGen++;
    }
示例#17
0
    public void SetToMutatedCopyOfParentGenome(BrainGenome parentGenome, TrainingSettingsManager settings)
    {
        this.bodyNeuronList = parentGenome.bodyNeuronList; // UNSUSTAINABLE!!! might work now since all neuronLists are identical
        // Alternate: SetBodyNeuronsFromTemplate(BodyGenome templateBody);

        // Existing Hidden Neurons!!
        hiddenNeuronList = new List <NeuronGenome>();
        for (int i = 0; i < parentGenome.hiddenNeuronList.Count; i++)
        {
            NeuronGenome newHiddenNeuronGenome = new NeuronGenome(parentGenome.hiddenNeuronList[i]);  // create new neuron as a copy of parent neuron
            // Might be able to simply copy hiddenNeuronList or individual hiddenNeuronGenomes from parent if they are functionally identical...
            // for now going with the thorough approach of a reference-less copy
            hiddenNeuronList.Add(newHiddenNeuronGenome);
        }

        // Existing Links!!
        linkList = new List <LinkGenome>();
        for (int i = 0; i < parentGenome.linkList.Count; i++)
        {
            LinkGenome newLinkGenome = new LinkGenome(parentGenome.linkList[i].fromModuleID, parentGenome.linkList[i].fromNeuronID, parentGenome.linkList[i].toModuleID, parentGenome.linkList[i].toNeuronID, parentGenome.linkList[i].weight, true);
            float      randChance    = UnityEngine.Random.Range(0f, 1f);
            if (randChance < settings.mutationChance)
            {
                float randomWeight = Gaussian.GetRandomGaussian();
                newLinkGenome.weight = Mathf.Lerp(newLinkGenome.weight, randomWeight, settings.mutationStepSize);
            }
            linkList.Add(newLinkGenome);
        }

        // Add Brand New Link:
        //
        float randLink = UnityEngine.Random.Range(0f, 1f);

        if (randLink < settings.newLinkChance)
        {
            List <NeuronGenome> inputNeuronList = new List <NeuronGenome>();
            //List<NeuronGenome> hiddenNeuronList = new List<NeuronGenome>();
            List <NeuronGenome> outputNeuronList = new List <NeuronGenome>();
            for (int j = 0; j < bodyNeuronList.Count; j++)
            {
                if (bodyNeuronList[j].neuronType == NeuronGenome.NeuronType.In)
                {
                    inputNeuronList.Add(bodyNeuronList[j]);
                }
                if (bodyNeuronList[j].neuronType == NeuronGenome.NeuronType.Out)
                {
                    outputNeuronList.Add(bodyNeuronList[j]);
                }
            }
            for (int j = 0; j < hiddenNeuronList.Count; j++)
            {
                inputNeuronList.Add(hiddenNeuronList[j]);
                outputNeuronList.Add(hiddenNeuronList[j]);
            }

            // Try x times to find new connection -- random scattershot approach at first:
            // other methods:
            //      -- make sure all bodyNeurons are fully-connected when modifying body
            int maxChecks = 8;
            for (int k = 0; k < maxChecks; k++)
            {
                int randID  = UnityEngine.Random.Range(0, inputNeuronList.Count);
                NID fromNID = inputNeuronList[randID].nid;

                randID = UnityEngine.Random.Range(0, outputNeuronList.Count);
                NID toNID = outputNeuronList[randID].nid;

                // check if it exists:
                bool linkExists = false;
                for (int l = 0; l < linkList.Count; l++)
                {
                    if (linkList[l].fromModuleID == fromNID.moduleID && linkList[l].fromNeuronID == fromNID.neuronID && linkList[l].toModuleID == toNID.moduleID && linkList[l].toNeuronID == toNID.neuronID)
                    {
                        linkExists = true;
                        break;
                    }
                }

                if (linkExists)
                {
                }
                else
                {
                    float      randomWeight = Gaussian.GetRandomGaussian() * 0f;
                    LinkGenome linkGenome   = new LinkGenome(fromNID.moduleID, fromNID.neuronID, toNID.moduleID, toNID.neuronID, randomWeight, true);
                    //Debug.Log("New Link! from: [" + fromNID.moduleID.ToString() + ", " + fromNID.neuronID.ToString() + "], to: [" + toNID.moduleID.ToString() + ", " + toNID.neuronID.ToString() + "]");
                    linkList.Add(linkGenome);
                    break;
                }
            }
        }

        // Add Brand New Hidden Neuron:
        float randNeuronChance = UnityEngine.Random.Range(0f, 1f);

        if (randNeuronChance < settings.newHiddenNodeChance)
        {
            // find a link and expand it:
            int randLinkID = UnityEngine.Random.Range(0, linkList.Count);
            // create new neuron
            NeuronGenome newNeuronGenome = new NeuronGenome(NeuronGenome.NeuronType.Hid, -1, hiddenNeuronList.Count);
            hiddenNeuronList.Add(newNeuronGenome);
            // create 2 new links
            LinkGenome linkGenome1 = new LinkGenome(linkList[randLinkID].fromModuleID, linkList[randLinkID].fromNeuronID, newNeuronGenome.nid.moduleID, newNeuronGenome.nid.neuronID, 1f, true);
            LinkGenome linkGenome2 = new LinkGenome(newNeuronGenome.nid.moduleID, newNeuronGenome.nid.neuronID, linkList[randLinkID].toModuleID, linkList[randLinkID].toNeuronID, linkList[randLinkID].weight, true);

            // delete old link
            linkList.RemoveAt(randLinkID);
            // add new links
            linkList.Add(linkGenome1);
            linkList.Add(linkGenome2);

            //Debug.Log("New Neuron! " + newNeuronGenome.nid.neuronID.ToString() + " - from: [" + linkGenome1.fromModuleID.ToString() + ", " + linkGenome1.fromNeuronID.ToString() + "], to: [" + linkGenome2.toModuleID.ToString() + ", " + linkGenome2.toNeuronID.ToString() + "]");
        }
    }
示例#18
0
 public Brain(BrainGenome genome, Agent agent)
 {
     // Debug.Log("Brain constructed with " + genome.inOutNeurons.Count + " neurons.");
     RebuildBrain(genome, agent);
 }