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

📄 evorepair_1.java~

📁 Java遗传算法库
💻 JAVA~
字号:
package jaga.pj.circuits.control;

import jaga.control.*;import jaga.deploy.*;import jaga.evolve.*;import jaga.experiment.*;import jaga.*;
import jaga.pj.circuits.*;import jaga.pj.circuits.experiment.*;import jaga.pj.circuits.fpgaft.*;
import jaga.pj.gral.*;import islandev.IslandsEvolutionServer;import debug.DebugLib;
import java.util.Vector;import java.util.Random;import java.rmi.*;import java.io.*;import java.awt.Point;
import java.util.ArrayList;
import distrit.*;

public class EvoRepair implements InteractiveTaskServer
{
    // Simulation Config Constants
    protected final int CLOCK_SPEED_MHZ = 10;
    protected final int HOUSEWORK_CYCLES = 20;
    protected final int AVG_TP_LENGTH = 50; // This is for CM42 N1
    protected final int EVALS_PER_SEC = CLOCK_SPEED_MHZ * 1000000 / ( HOUSEWORK_CYCLES + AVG_TP_LENGTH );
    protected final int GENS_PER_SEC = EVALS_PER_SEC / 2;
    protected final int EVALS_PER_MIN = EVALS_PER_SEC * 60, GENS_PER_MIN = EVALS_PER_MIN / 2;
    protected final int EVALS_PER_HOUR = EVALS_PER_MIN * 60, GENS_PER_HOUR = EVALS_PER_HOUR / 2;
    
    //Other Constants
    protected final int SEQUENCE_LENGTH_S_MULT = 3;
    
    // Defaults Config Constants
    protected final int IX_FIT_FUN = 0;
    protected final int IX_SAMPLE = 1;
    protected final int IX_TPG = 2;
    protected final int IX_TIMEOUT = 3;
    protected final int IX_DELAY_MIN = 4;
    protected final int IX_DELAY_MAX = 5;
    protected final int IX_DELAY_VAR = 6;
    protected final int IX_H = 7;
    protected final int IX_EXTRA_BPV = 8;
    protected final int IX_EXTRA_DESCR = 9;
    protected final int IX_MUT_RATE = 10;
    
    // Configuration
    protected String[] config = new String[ 11 ];
    protected String[] configOption = new String[ 11 ];
    
    // Default setup configuration
    protected void setupConfig()
    {
        config[ IX_FIT_FUN ] = "C";     configOption[ IX_FIT_FUN ] = "ff";
        config[ IX_SAMPLE ] = "15";     configOption[ IX_SAMPLE ] = "s";
        config[ IX_TPG ] = "TP";        configOption[ IX_TPG ] = "tpg";
        config[ IX_TIMEOUT ] = "1";     configOption[ IX_TIMEOUT ] = "t";
        config[ IX_DELAY_MIN ] = "0";   configOption[ IX_DELAY_MIN ] = "dm";
        config[ IX_DELAY_MAX ] = "1";   configOption[ IX_DELAY_MAX ] = "dM";
        config[ IX_DELAY_VAR ] = "0.4"; configOption[ IX_DELAY_VAR ] = "dv";
        config[ IX_H ] = "32";          configOption[ IX_H ] = "h";
        config[ IX_EXTRA_BPV ] = "0";   configOption[ IX_EXTRA_BPV ] = "ebpv";
        config[ IX_EXTRA_DESCR ] = "";  configOption[ IX_EXTRA_DESCR ] = "edescr";
        config[ IX_MUT_RATE ] = "1";    configOption[ IX_MUT_RATE ] = "m";
    }
    
    protected void updateConfig( ArrayList args )
    {   for( int alp = 0; alp < args.size(); alp++ )
        {   
            String withoutFirst = ( ( String ) args.get( alp ) ).substring( 1 );
            int ix = ESLib.equalsIndexOf( withoutFirst, configOption );
            if( ix >= 0 ) config[ ix ] = args.get( ++alp ) + "";
    }   }
    
    protected int getIntConfig( int ix ){   return Integer.parseInt( config[ ix ] );    }
    protected double getDoubleConfig( int ix ){   return Double.parseDouble( config[ ix ] );    }
    
    // Server Config Constants 
    protected final double MIGRATION_RATE = 0;
    
    // Other Constants
    protected final String FS = File.separator;
    
    // Working
    protected Vector taskQ = new Vector();
    protected Vector taskQNames = new Vector();
    protected IslandsEvolutionServer ies;
    protected String logFileName, logDir, benchmark;
    
    public EvoRepair( ArrayList extraArgs ) throws IOException
    {
        setupConfig();
        logFileName = ( String ) extraArgs.get( 1 );
        benchmark = ( String ) extraArgs.get( 2 );
        int M = Integer.parseInt( ( String ) extraArgs.get( 3 ) );
        int ixOffset = Integer.parseInt( ( String ) extraArgs.get( 4 ) );
        
        updateConfig( extraArgs );
                
        logDir = ( String ) extraArgs.get( 0 ) + "Repair" + FS + benchmark + FS + getDescription() + FS; new File( logDir ).mkdirs();
                
        addRepairComBenchMultipleNoLatch( M, ixOffset );

        ies = new IslandsEvolutionServer( taskQ, taskQNames, logDir, logFileName, MIGRATION_RATE );
    }
    
    
    public Object getID(Object initialParameters) throws RemoteException {
        return ies.getID( initialParameters );
    }    
    public InteractiveTask getTask(Object id) throws RemoteException {
        return ies.getTask( id );
    }    
    public Object interact(Object ID, Object clientTaskOutput) throws RemoteException {
        return ies.interact( ID, clientTaskOutput );
    }    
    
    public String getDescription()
    {
        String description = config[ IX_FIT_FUN ] + "_" + config[ IX_SAMPLE ] + "_" + config[ IX_TPG ];
        if( !config[ IX_EXTRA_DESCR ].equals( "" ) )
        {
            description += "_" + config[ IX_EXTRA_DESCR ];
        }
        return description;
    }
    
    public String toString()
    {
        String rv = "EvoRepair server description = " + getDescription();
        return rv;
    }
    
    
    // -------------- FROM HERE ON METHODS TO ADD TASKS TO THE QUEUE --------------
        
    private  int countBelow( Vector ints, int belowWhat )
    {
        int rv = 0;
        for( int el = 0; el < ints.size(); el++ )
        {
            int intVal = ( ( Integer ) ints.get( el ) ).intValue();
            if( intVal < belowWhat )
            {
                rv++;
            }
        }
        return rv;
    }    
        
    private void addRepairComBenchMultipleNoLatch( int M, int ixOffset ) throws IOException
    {
        String sisOutputFileName = "/home/mmg20/eh/benchmarks/" + benchmark + "L4.sout";
        int resQ = 0;    boolean fpga = false;    boolean voter = false;    int LUT_INPUTS = 4;  boolean varSized = false;
        
        SisOutputReader sor = new SisOutputReader( new File( sisOutputFileName ), resQ, LUT_INPUTS, fpga, voter, getIntConfig( IX_EXTRA_BPV ), varSized );
        int usedEls = sor.getTotalEls();
        int bitsPerVar = sor.getBitsPerVar();
        String blifFileName = "/home/mmg20/eh/benchmarks/" + benchmark + ".blif";
        ConfigurableRandomInputExperiment combexp = new CombinationalBLIFExperiment( blifFileName );
        int nrIns = combexp.getNumOfInputs();// no latch, no clock
        int totalCLBs = ( 1 << bitsPerVar ) - nrIns;
        int spareLUTs = totalCLBs - usedEls;
        int maxGens = GENS_PER_MIN * getIntConfig( IX_TIMEOUT );
        
        String narrator = "Repairing combinational benchmark: " + benchmark + " under multiple faults.";
        narrator += "\nBPV(CLB) = " + bitsPerVar + ".  Total CLBs = " + totalCLBs + ".  Used LUTs = " + usedEls;
        narrator += "\nSpares: " + spareLUTs + " LUTs. ";
        narrator += "\nSequences totally random ending when only " + usedEls + " LUTs left (assume minimal design)";
        narrator += "\nMax Gens per repair = (" + getIntConfig( IX_TIMEOUT ) + "m) = " + maxGens;
        narrator += "\nOrderings:\n";
        
        int[] faultPos = new int[ totalCLBs ]; // in FPGALUTAbsMapping it skips inputs
        for( int flp = 0; flp < totalCLBs; flp++ )
        {
            faultPos[ flp ] = flp;
        }
        Vector[] orders = new Vector[ M ];
        Random rnd = new Random();
        for( int ml = 0; ml < M; ml++ )
        {
            orders[ ml ] = new Vector();
            Vector allFaults = new Vector();
            for( int flp = 0; flp < faultPos.length; flp++ )
            {
                allFaults.add( new Integer( faultPos[ flp ] ) ); // Extra level of inderection maintained just in case mapping changes
            }
            while( orders[ ml ].size() < ( spareLUTs * SEQUENCE_LENGTH_S_MULT ) )
            {
                int ix = rnd.nextInt( allFaults.size() );
                //Integer currFPos = ( Integer ) allFaults.remove( ix ); // Remove comment for unique fault positions each time
                Integer currFPos = ( Integer ) allFaults.get( ix );
                int currFVal = rnd.nextInt( 2 ); // SSA0 or 1
                orders[ ml ].add( new Point( currFPos.intValue(), currFVal ) );
            }
            narrator += ml+": " + orders[ ml ] + "\n";
        }
        
        File orderFile = new File( logDir + "orders" + ixOffset + ".txt" );
        BufferedWriter multipleBW = new BufferedWriter( new FileWriter( orderFile ) );
        multipleBW.write( narrator );
        multipleBW.flush();        
        multipleBW.close();
        
        for( int ml = 0; ml < M; ml++ )
        {
            addRepairComBlifSequenceNoLatch( ml + ixOffset * M, orders[ ml ] );
        }
    }    
    
    private void addRepairComBlifSequenceNoLatch( int ix, Vector seq ) throws IOException
    {
        Point[] faultSequence = new Point[ seq.size() ];
        for( int flp = 0; flp < faultSequence.length; flp++ )
        {
            faultSequence[ flp ] = ( Point ) seq.get( flp );
        }
        
        int ISS = 30; double tSetup = 0.84;
        //int[] samLen = { 5 }; int[] samPos = { 45 };
        boolean sameRndPerGen = false; boolean alwaysResetBeforeRun = false; // Noise 2, 3
        
        FitnessFunction inFF;
        if( config[ IX_FIT_FUN ].indexOf( 'C' ) >= 0  )
        {
            inFF = new SimpleCorrelationFitnessFunction();
            
        }else
        {
            // Assume is sum
            inFF = new SumFitnessFunction();
        }
        inFF = new PessimisticFitnessFunction( inFF );
        if( config[ IX_FIT_FUN ].indexOf( 'L' ) >= 0 )
        {
            inFF = new PerRowFitnessFunction( inFF );
        }
        
        FitnessFunction samFF = inFF;
        if( config[ IX_SAMPLE ].indexOf( "Avg" ) >= 0 )
        {
            samFF = new AverageSampleFitnessFunction( inFF );
        }
        
        FitnessFunction fitnessFunction;
        if( config[ IX_SAMPLE ].indexOf( "NoisyAvg5" ) >= 0  )
        {
            fitnessFunction = new NoisySampleWindowFitnessFunction( inFF, 25, 30, 0.7, 0 );
        }else
        {
            int start = 25;
            if( !config[ IX_SAMPLE ].equals( "Avg" ) )
            {
                start = Integer.parseInt( config[ IX_SAMPLE ] );
            }
            fitnessFunction = new SampleWindowFitnessFunction( samFF, start );
        }

        TestPatternGenerator tpg;
        if( config[ IX_TPG ].indexOf( "TP" ) >=0 )
        {
            tpg = new CompleteShuffledTPG();
        }else
        {
            // Assume N1
            int repeats = 1;    
            tpg = new NRepeatsTPG( repeats );
        }
        
        String blifFileName = "/home/mmg20/eh/benchmarks/" + benchmark + ".blif";
        ConfigurableRandomInputExperiment experiment = new CombinationalBLIFExperiment( blifFileName, fitnessFunction, tpg );
        String sisOutputFileName = "/home/mmg20/eh/benchmarks/" + benchmark + "L4.sout";
        int resQ = 0;        boolean fpga = false;        boolean voter = false;     boolean varSized = false;
        int LUT_INPUTS = 4;    int DUMP_POP_EVERY = Integer.MAX_VALUE;
        SisOutputReader sor = new SisOutputReader( new File( sisOutputFileName ), resQ, LUT_INPUTS, fpga, voter, getIntConfig( IX_EXTRA_BPV ), varSized );
        Genotype seed = new Genotype( sor.getVassilevGenotype() );
        int bitsPerVar = sor.getBitsPerVar();        int usedEls = sor.getTotalEls();
        int addEls = ( 1 << bitsPerVar ) - experiment.getNumOfInputs();
        int MU_D = 3 * GENS_PER_MIN;   int MU_S = 1 * GENS_PER_MIN;
        MU_D *= 2 * addEls; MU_S *= 2 * addEls;// must multiply these by number of elements in circuit and popsize
        ElementDelayModel delayModel = new DriftingGaussianDelayModel( getIntConfig( IX_DELAY_MIN ),getIntConfig( IX_DELAY_MAX ),getDoubleConfig( IX_DELAY_VAR ),MU_D,MU_S ); // Noise 1
        //ElementDelayModel delayModel = new GaussianDelayModel( MIN_MU, SIGMA ); // mu,s        
        CircuitMapping inMap = new LUTAbsoluteMapping( experiment.getNumOfInputs(), experiment.getNumOfOutputs(), bitsPerVar, LUT_INPUTS, delayModel );
        CircuitMapping circuitMapping = new VassilevMapping( inMap, experiment.getNumOfOutputs(), bitsPerVar );
        SimulatorFaultyCircuit circuit = new SimulatorFaultyCircuit( circuitMapping );
        SimulatorDeployment deployment = new SimulatorDeployment( circuit, alwaysResetBeforeRun );
        int POP_SIZE = 2;  int NUM_OF_ELITES = 1;  double[] RANK_PROBS = { 1,0 };
        int genotypeLength = seed.length(); final Genotype[] SEEDS = { seed };
        GeneticOperator m = new ExactGenotypeMutator( getIntConfig( IX_MUT_RATE ) );   GeneticOperator[] geneticOps = { m };  double[] opsProbs = { 1 };        
        Selector selector = new RankSelector( RANK_PROBS );
        Evolver evolver = new StandardEvolver( POP_SIZE, genotypeLength, geneticOps, opsProbs, selector, NUM_OF_ELITES, SEEDS );
        InteractionModel inIM = new StandardInteractionModel( evolver, deployment, experiment,ISS );
        InteractionModel nIM = new NoisyIM( inIM, deployment, experiment, 1, NoisyIM.MINIMUM, sameRndPerGen );
        InteractionModel hIM = new HistoryWindowIM( getIntConfig( IX_H ), nIM );        
        String subDirName = "" + ix;  new File( logDir + subDirName ).mkdirs();
        int maxGensPerFault = GENS_PER_MIN * getIntConfig( IX_TIMEOUT );
        InteractionModel interactionModel = new RepairFaultSequenceIM( hIM, circuit, faultSequence, maxGensPerFault, getIntConfig( IX_H ) + 1 ); // to fill up history window with solutions
        Monica monica = new Monica( interactionModel, DUMP_POP_EVERY, java.lang.Integer.MAX_VALUE );
        monica.setName( subDirName );
        taskQ.add( monica );
        taskQNames.add( subDirName );
    }
}

⌨️ 快捷键说明

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