⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 circuittestpatternim.java

📁 Java遗传算法库
💻 JAVA
字号:
/*
 * CircuitTestPatternIM.java
 *
 * Created on 08 December 2001, 03:59
 */

package jaga.pj.circuits.control;

import jaga.control.InteractionModel;
import jaga.Genotype;
import jaga.SampleData;
import jaga.evolve.Evolver;
import jaga.evolve.Population;
import jaga.deploy.Deployment;
import jaga.experiment.Experiment;
import jaga.pj.circuits.experiment.TestPattern4EvolvingExperiment;

import islandev.SnapshotPainter;


/**
 *
 * @author  Michael Garvie
 * @version 
 */
public class CircuitTestPatternIM implements InteractionModel
{
    static final int CIRCUIT = 0;
    static final int TEST_PATTERN = 1;
    static final int POPS = 2;
        
    int currentIndividual = 0;
    int inputSampleSeparation;
    int tpPopSize;
    double currentTotalFitness[] = { 0, 0 };
    
    Evolver[] evolvers;
    Deployment deployment;
    Experiment[] experiments;
    TestPattern4EvolvingExperiment tp4ee;
    protected SnapshotPainter painter = new islandev.EmptySnapshotPainter();
    
    int[] evolutionFrequency;
    
    int currentGeneration = 0;
    int rndOffset = 0;
    
    Genotype[] fittestIndividuals = { new Genotype(), new Genotype() };
    
    Genotype fittestPossible = new Genotype();
    
    /** Creates new CircuitTestPatternIM */
    public CircuitTestPatternIM( Evolver[] evos, Deployment dep, Experiment[] exps, int[] evolutionFrequency )
    {
        evolvers = evos;
        deployment = dep;
        experiments = exps;
        tp4ee = ( TestPattern4EvolvingExperiment ) experiments[ TEST_PATTERN ];
        inputSampleSeparation = deployment.getRecommendedInputSampleSeparation();
        evolvers[ CIRCUIT ].poolOfMud();
        evolvers[ TEST_PATTERN ].poolOfMud();
        tpPopSize = evolvers[ TEST_PATTERN ].getPopulationSize();
        this.evolutionFrequency = evolutionFrequency;
        fittestPossible.setFitness( 1 );
    }

    /** Returns the number of evaluations per generation to be performed
     */
    public int evaluationsPerGeneration()
    {
        return evolvers[ CIRCUIT ].getPopulationSize();
    }
    /** Picks a number of individuals to be evaluated next.
     * These individuals can be from any of the populations as long as there
     * is a standard interface between the caller and this method implementation
     * as to where each come from.
     * Example: may be first element a pac-man, and five others all ghosts..
     *
     * Test Patterns are evaluated just after a generational step and are
     * selected in sequence. For next generations of circuits where pattern's 
     * aren't evolved they are selected using the pattern evolver's selector.
     */
    public Genotype[] getNextIndividuals()
    {
        Genotype[] rv = new Genotype [ POPS ];
        
        rv[ CIRCUIT ] = evolvers[ CIRCUIT ].getGenotype( currentIndividual );
        
        if( currentGeneration % evolutionFrequency[ TEST_PATTERN ] == 1 || currentGeneration == 0 )
        {
            rv[ TEST_PATTERN ] = evolvers[ TEST_PATTERN ].getGenotype( ( rndOffset + currentIndividual ) % tpPopSize );
        }else
        {
            rv[ TEST_PATTERN ] = evolvers[ TEST_PATTERN ].pickGenotype(); // note there must already be a previous generation here!
        }
        
        currentIndividual++;
        
        return rv;        
        
    }
    
    /** Evaluates these individuals using the deployment and experiments and
     * procedure of this model.
     * Returns an array of the fitnesses of the individuals.
     */
    synchronized public double[] evaluate(Genotype[] inds)
    {
        double fitness[] = new double[ POPS ];
        deployment.program( inds[ CIRCUIT ] );
        SampleData[] input = tp4ee.generateInput( inds[ TEST_PATTERN ], inputSampleSeparation );
        SampleData[] output = deployment.run( input );
        fitness[ CIRCUIT ] = experiments[ CIRCUIT ].getFitness( input, output );
        inds[ CIRCUIT ].setFitness( fitness[ CIRCUIT ] );
                
        // This will allow multiple evaluation of test pattern fitness
        // to result in highest fitness being kept, we want to focus on those
        // good at testing the highest fitness circuits.
        // 1. So if circuit bad, then don't reevaluate test pattern fitness
        // because it can only decrease.
        if( fitness[ CIRCUIT ] > inds[ TEST_PATTERN ].getFitness() )
        {
            tp4ee.setNextCircuitFitness( fitness[ CIRCUIT ] ); // OPTIMIZES fitness eval
            fitness[ TEST_PATTERN ] = tp4ee.getFitness( input, output );
            // 2. Now check if this improves fitness.
            if( fitness[ TEST_PATTERN ] > inds[ TEST_PATTERN ].getFitness() )
            {
                inds[ TEST_PATTERN ].setFitness( fitness[ TEST_PATTERN ] );
            }else
            {
                fitness[ TEST_PATTERN ] = inds[ TEST_PATTERN ].getFitness();
            }
        }else
        {
            fitness[ TEST_PATTERN ] = inds[ TEST_PATTERN ].getFitness();
        }
        
        for( int pl = 0; pl < POPS; pl++ )
        {
            currentTotalFitness[ pl ] += fitness[ pl ]; //*! Reevaluates fitnesses.. might find match for best..
            if( fitness[ pl ] > fittestIndividuals[ pl ].getFitness() )
            {
                fittestIndividuals[ pl ] = ( Genotype ) ( inds[ pl ].clone() );
            }
        }
        
        double[] rv = { fitness[ CIRCUIT ], fitness[ TEST_PATTERN ] };
        return rv;

    }
    
    /** Should be same as calling evaluate( pickIndividuals() );
     * Returns an array of the fitnesses of the individuals.
     */
    public double[] evaluateNext()
    {
        return evaluate( getNextIndividuals() );
    }
    /** Evolves to the next generation of all/some of the populations involved.
     */
    public void evolve()
    {
        currentIndividual = 0;
        rndOffset = ( int ) Math.random() * tpPopSize;
        for( int pl = 0; pl < POPS; pl++ )
        {
            if( currentGeneration % evolutionFrequency[ pl ] == 0 )
            {
                evolvers[ pl ].evolve();
                fittestIndividuals[ pl ].setFitness( -1 ); // reset so no lucky ones.
                fittestIndividuals[ pl ] = new Genotype();
            }
            currentTotalFitness[ pl ] = 0; //*! Reevaluates fitnesses.. might find match for best..
        }
        currentGeneration++;
        deployment.setEnvironment( null ); // signal end of generation
    }
    /** Returns an array with the average fitnesses of each evolver
     */
    public double[] getAvgFitness()
    {
        double[] rv = new double[ POPS ];
        for( int pl = 0; pl < POPS; pl++ )
        {
            // use circuit popSize because this is amount of times tp added as well
            rv[ pl ] = currentTotalFitness[ pl ] / evolvers[ CIRCUIT ].getPopulationSize();
        }
        return rv;
    }
    /** Returns the number of evolvers acting in this model
     */
    public int getNumEvolvers()
    {
        return POPS;
    }
    /** Returns randomly picked individuals from the evolvers.
     */
    public Genotype[] pickIndividuals()
    {
        Genotype[] rv = new Genotype[ POPS ];
        for( int pl = 0; pl < POPS; pl++ )
        {
            rv[ pl ] =  evolvers[ pl ].pickGenotype();
        }
        return rv;
    }
    /** Returns the current populations of the evolvers
     */
    public Population[] getPopulations()
    {
        Population[] rv = new Population[ POPS ];
        for( int pl = 0; pl < POPS; pl++ )
        {
            rv[ pl ] =  evolvers[ pl ].getPopulation();
        }
        return rv;
    }
    /** Returns fittest individuals in same array order as evolvers
     * Clone them so receive snapshot.
     */
    public Genotype[] getFittest()
    {
        Genotype[] rv = new Genotype[ POPS ];
        for( int pl = 0; pl < POPS; pl++ )
        {
            rv[ pl ] =  ( Genotype ) fittestIndividuals[ pl ].clone();
        }
        return rv;
    }
    
    public String toString()
    {
        String narrator = "Circuit / Test Pattern Co-Evolution Interaction Model with:";
        narrator += "\n\nDeployment: " + deployment;
        narrator += "\n\nExperiment 0 : " + experiments[ 0 ];
        narrator += "\n\nEvolver 0 : " + evolvers[ 0 ];
        narrator += "\n\nExperiment 1 : " + experiments[ 1 ];
        narrator += "\n\nEvolver 1 : " + evolvers[ 1 ];
        narrator += "\n";
        return narrator;
    }

    /** Returns the generation numbers of each of the evolvers
     */
    public int[] getGenerations()
    {
        int[] rv = new int[ POPS ];
        for( int pl = 0; pl < POPS; pl++ )
        {
            rv[ pl ] =  evolvers[ pl ].getGenerations();
        }
        return rv;       
    }
    
    /** @return String displaying performance of fittest individual at given task.
     */
    synchronized public String getFittestSnapshot()
    {
        deployment.program( fittestIndividuals[ CIRCUIT ] );
        SampleData[] input = tp4ee.generateInput( fittestIndividuals[ TEST_PATTERN ], inputSampleSeparation );
        SampleData[] output = deployment.run( input );
        return jaga.ESLib.sampleDatasToString( input, output ) + "\nFitness: " + experiments[ CIRCUIT ].getFitness( input, output );
    }
    /** @return The maximum fitness a genotype can achieve. ie. when evolution will stop
     */
    public Genotype getMaxFitness () {
        return fittestPossible;
    }
    /** Sets the populations of the evolvers to be these
     */
    public void setPopulations (Population[] pops)
    {
        for( int pl = 0; pl < evolvers.length; pl++ )
        {
            evolvers[ pl ].setPopulation( pops[ pl ] );
        }
    }
    
    
    
    /** @return String displaying performance of fittest individual.
     */
    public SnapshotPainter getSnapshotPainter() {
        return painter;
    }    
    
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -