Пример #1
0
        public override float EvaluateTestCase(GAIndividual inIndividual, object inInput, object inOutput)
        {
            _effort++;
            _interpreter.ClearStacks();
            _currentInput = (float)inInput;
            FloatStack fstack = _interpreter.FloatStack();

            fstack.Push(_currentInput);
            // Must be included in order to use the input stack.
            _interpreter.InputStack().Push(_currentInput);
            _interpreter.Execute(((PushGPIndividual)inIndividual)._program, _executionLimit);
            float result = fstack.Top();

            // System.out.println( _interpreter + " " + result );
            //trh

            /*
             * System.out.println("\nevaluations according to interpreter " +
             * Interpreter.GetEvaluationExecutions());
             * System.out.println("evaluations according to effort " + _effort);
             */
            // Penalize individual if there is no result on the stack.
            if (fstack.Size() == 0)
            {
                return(_noResultPenalty);
            }
            return(result - ((float)inOutput));
        }
Пример #2
0
        public override float EvaluateTestCase(GAIndividual inIndividual, object inInput, object inOutput)
        {
            int        timeSteps       = 1000;
            float      timeDiscritized = 0.01f;
            float      maxTime         = timeSteps * timeDiscritized;
            float      captureRadius   = 0.01f;
            ObjectPair xv       = (ObjectPair)inInput;
            float      position = (float)xv._first;
            float      velocity = (float)xv._second;

            for (int step = 1; step <= timeSteps; step++)
            {
                _interpreter.ClearStacks();
                FloatStack   fStack = _interpreter.FloatStack();
                BooleanStack bStack = _interpreter.BoolStack();
                ObjectStack  iStack = _interpreter.InputStack();
                // Position will be on the top of the stack, and velocity will be
                // second.
                fStack.Push(position);
                fStack.Push(velocity);
                // Must be included in order to use the input stack. Uses same order
                // as inputs on Float stack.
                iStack.Push(position);
                iStack.Push(velocity);
                _interpreter.Execute(((PushGPIndividual)inIndividual)._program, _executionLimit);
                // If there is no boolean on the stack, the program has failed to
                // return a reasonable output. So, return a penalty fitness of
                // twice the maximum time.
                if (bStack.Size() == 0)
                {
                    return(2 * maxTime);
                }
                // If there is a boolean, use it to compute the next position and
                // velocity. Then, check for termination conditions.
                // NOTE: If result == True, we will apply the force in the positive
                // direction, and if result == False, we will apply the force in
                // the negative direction.
                bool  positiveForce = bStack.Top();
                float acceleration;
                if (positiveForce)
                {
                    acceleration = 0.5f;
                }
                else
                {
                    acceleration = -0.5f;
                }
                velocity = velocity + (timeDiscritized * acceleration);
                position = position + (timeDiscritized * velocity);
                // Check for termination conditions
                if (position <= captureRadius && position >= -captureRadius && velocity <= captureRadius && velocity >= -captureRadius)
                {
                    //Cart is centered, so return time it took.
                    return(step * timeDiscritized);
                }
            }
            // If here, the cart failed to come to rest in the allotted time. So,
            // return the failed error of maxTime.
            return(maxTime);
        }
Пример #3
0
    public GAIndividual best_ind;     // best individual of this evolution

    public GAEvolve(int generations, int pop_size, int nvert, int xrate, int mrate)
    {
        // xrate: cross-over rate, the initial value
        // mrate: mutation rate, the initial value
        // xrate and mrate may be adapted over generations
        // nvert: number of graph vertices

        best_fitness  = new float[generations];
        worst_fitness = new float[generations];
        avr_fitness   = new float[generations];

        GAPopulation gap = new GAPopulation(pop_size, nvert);

        best_fitness[0]  = gap.ind[gap.best_index].fitness;
        worst_fitness[0] = gap.ind[gap.worst_index].fitness;
        avr_fitness[0]   = gap.avr_fitness;

        for (int i = 1; i < generations; i++)
        {
            gap              = GAPopulation.generate(gap, xrate, mrate);
            best_fitness[i]  = gap.ind[gap.best_index].fitness;
            worst_fitness[i] = gap.ind[gap.worst_index].fitness;
            avr_fitness[i]   = gap.avr_fitness;
        }

        best_ind = gap.ind[gap.best_index];
    }
Пример #4
0
        /// <summary>
        /// Determines the predictor's fitness on a trainer, where the trainer is the
        /// inInput, and the trainer's actual fitness is inOutput.
        /// </summary>
        /// <remarks>
        /// Determines the predictor's fitness on a trainer, where the trainer is the
        /// inInput, and the trainer's actual fitness is inOutput. The fitness of
        /// the predictor is the absolute error between the prediction and the
        /// trainer's actual fitness.
        /// </remarks>
        /// <returns>Predictor's fitness (i.e. error) for the given trainer.</returns>
        /// <exception cref="System.Exception"></exception>
        public override float EvaluateTestCase(GAIndividual inIndividual, object inInput, object inOutput)
        {
            PushGPIndividual trainer                 = (PushGPIndividual)inInput;
            float            trainerFitness          = (float)inOutput;
            float            predictedTrainerFitness = ((PredictionGAIndividual)inIndividual).PredictSolutionFitness(trainer);

            return(Math.Abs(predictedTrainerFitness - trainerFitness));
        }
Пример #5
0
        /// <summary>Evaluates a solution individual using the best predictor so far.</summary>
        protected internal virtual void PredictIndividual(GAIndividual inIndividual, bool duringSimplify)
        {
            FloatRegFitPredictionIndividual predictor = (FloatRegFitPredictionIndividual)_predictorGA.GetBestPredictor();
            float fitness = predictor.PredictSolutionFitness((PushGPIndividual)inIndividual);

            inIndividual.SetFitness(fitness);
            inIndividual.SetErrors(new List <float>());
        }
Пример #6
0
        protected internal override void InitIndividual(GAIndividual inIndividual)
        {
            FloatRegFitPredictionIndividual i = (FloatRegFitPredictionIndividual)inIndividual;

            int[] samples = new int[FloatRegFitPredictionIndividual._sampleSize];
            for (int j = 0; j < samples.Length; j++)
            {
                samples[j] = Rng.Next(_solutionGA._testCases.Count);
            }
            i.SetSampleIndicesAndSolutionGA(_solutionGA, samples);
        }
Пример #7
0
    public static void main(string[] args)
    {
        GAIndividual.adj_matrix = GAUtils.readMatrix("graph.txt");
        int nvert = GAIndividual.adj_matrix.Length;         // number of vertices

        GAIndividual i1 = new GAIndividual(nvert);
        GAIndividual i2 = new GAIndividual(nvert);

        for (int i = 0; i < 1000; i++)
        {
            Console.WriteLine(new GAIndividual(nvert));
        }
    }
Пример #8
0
        public override float EvaluateTestCase(GAIndividual inIndividual, object inInput, object inOutput)
        {
            _interpreter.ClearStacks();
            _currentInput = (float)inInput;
            FloatStack stack = _interpreter.FloatStack();

            stack.Push(_currentInput);
            _interpreter.Execute(((PushGPIndividual)inIndividual)._program, _executionLimit);
            float result = stack.Top();

            // System.out.println( _interpreter + " " + result );
            return(result - ((float)inOutput));
        }
Пример #9
0
    public float avr_fitness;  // average fitness of this population
    // best_fitness = ind[best_index].fitness
    // worst_fitness = ind[worst_index].fitness

    public GAPopulation(int psize, int nvert)
    {
        // Create a random population of size pop_size
        // psize: population size
        // nvert: number of vertices
        pop_size = psize;
        ind      = new GAIndividual[pop_size];
        for (int i = 0; i < pop_size; i++)
        {
            ind[i] = new GAIndividual(nvert);
        }

        evaluate();
    }
Пример #10
0
        protected internal virtual PredictionGAIndividual GetBestPredictor()
        {
            float        bestFitness   = float.MaxValue;
            GAIndividual bestPredictor = _populations[_currentPopulation][0];

            foreach (GAIndividual ind in _populations[_currentPopulation])
            {
                if (ind.GetFitness() < bestFitness)
                {
                    bestPredictor = ind;
                    bestFitness   = ind.GetFitness();
                }
            }
            return((PredictionGAIndividual)bestPredictor);
        }
Пример #11
0
        protected internal override void EvaluateIndividual(GAIndividual inIndividual)
        {
            FloatRegFitPredictionIndividual predictor = (FloatRegFitPredictionIndividual)inIndividual;
            List <float> errors = new List <float>();

            for (int i = 0; i < _trainerPopulationSize; i++)
            {
                float predictedError = predictor.PredictSolutionFitness(_trainerPopulation[i]);
                // Error is difference between predictedError and the actual fitness
                // of the trainer.
                float error = Math.Abs(predictedError) - Math.Abs(_trainerPopulation[i].GetFitness());
                errors.Add(error);
            }
            predictor.SetFitness(AbsoluteAverageOfErrors(errors));
            predictor.SetErrors(errors);
        }
 public virtual bool EqualPredictors(GAIndividual inB)
 {
     return(_sampleIndices.OrderBy(x => x).SequenceEqual(((Psh.Coevolution.FloatRegFitPredictionIndividual)inB)._sampleIndices.OrderBy(x => x)));
     // int[] a = CopyArray(_sampleIndices);
     // int[] b = CopyArray(((Psh.Coevolution.FloatRegFitPredictionIndividual)inB)._sampleIndices);
     // /*
     // a = Arrays.copyOf(_sampleIndices, _sampleSize);
     // b = Arrays.copyOf(((FloatRegFitPredictionIndividual)inB)._sampleIndices, _sampleSize);
     // */
     // Arrays.Sort(a);
     // Arrays.Sort(b);
     // if (Arrays.Equals(a, b))
     // {
     //   return true;
     // }
     // return false;
 }
Пример #13
0
    public static GAPopulation generate(GAPopulation p, int xrate, int mrate)
    {
        // Generate a new population from p, xrate percent of the induviduals
        // of new population are generated by cross-over, mrate percent of them are
        // generated by mutation, and others by reproduction.

        if (xrate < 0 || xrate > 100 || mrate < 0 || mrate > 100 || xrate + mrate > 100)
        {
            Console.Error.WriteLine("error: xrate and/or mrate are not properly set");
        }

        GAIndividual[] newg       = new GAIndividual[p.pop_size];
        int            newg_index = 0;

        int xn = xrate * p.pop_size / 100;         // xn: number of offsprings to be produced by xover
        int mn = mrate * p.pop_size / 100;         // mn: number of offsprings to be produced by mutation

        // xover:
        for (int i = 0; i < xn; i++)
        {
            // select two parents for cross-over:
            // we want two distinct parents (i.e. p1 != p2)
            int p1, p2;
            do
            {
                p1 = p.tr_select();
                p2 = p.tr_select();
            }while (p1 == p2);

            newg[newg_index++] = GAIndividual.xover1p(p.ind[p1], p.ind[p2]);
        }

        // mutation:
        for (int i = 0; i < mn; i++)
        {
            newg[newg_index++] = p.ind[p.tr_select()].mutate();
        }

        // reproduction:
        for (int i = newg_index; i < p.pop_size; i++)
        {
            newg[i] = p.ind[p.tr_select()];
        }

        return(new GAPopulation(newg));
    }
Пример #14
0
        protected internal override bool Success()
        {
            if (_success)
            {
                return(true);
            }
            GAIndividual best             = _populations[_currentPopulation][_bestIndividual];
            float        predictedFitness = best.GetFitness();

            _predictorGA.EvaluateSolutionIndividual((PushGPIndividual)best);
            _bestMeanFitness = best.GetFitness();
            if (_bestMeanFitness <= 0.1)
            {
                _success = true;
                return(true);
            }
            best.SetFitness(predictedFitness);
            return(false);
        }
Пример #15
0
        public override float EvaluateTestCase(GAIndividual inIndividual, object inInput, object inOutput)
        {
            _interpreter.ClearStacks();
            float      currentInput = (float)inInput;
            FloatStack stack        = _interpreter.FloatStack();

            stack.Push(currentInput);
            // Must be included in order to use the input stack.
            _interpreter.InputStack().Push(currentInput);
            _interpreter.Execute(((PushGPIndividual)inIndividual)._program, _executionLimit);
            float result = stack.Top();

            // Penalize individual if there is no result on the stack.
            if (stack.Size() == 0)
            {
                return(_noResultPenalty);
            }
            return(result - ((float)inOutput));
        }
Пример #16
0
        public virtual float GetIndividualTestCaseResult(GAIndividual inIndividual, GATestCase inTestCase)
        {
            _interpreter.ClearStacks();
            float      currentInput = (float)inTestCase._input;
            FloatStack stack        = _interpreter.FloatStack();

            stack.Push(currentInput);
            // Must be included in order to use the input stack.
            _interpreter.InputStack().Push(currentInput);
            _interpreter.Execute(((PushGPIndividual)inIndividual)._program, _executionLimit);
            float result = stack.Top();

            // If no result, return 0
            if (stack.Size() == 0)
            {
                return(0);
            }
            return(result);
        }
Пример #17
0
        /// <summary>
        /// NOTE: This is entirely copied from PushGP, except EvaluateIndividual
        /// was changed to PredictIndividual, as noted below.
        /// </summary>
        protected internal override void Evaluate()
        {
            float totalFitness = 0;

            _bestMeanFitness = float.MaxValue;
            for (int n = 0; n < _populations[_currentPopulation].Length; n++)
            {
                GAIndividual i = _populations[_currentPopulation][n];
                PredictIndividual(i, false);
                totalFitness += i.GetFitness();
                if (i.GetFitness() < _bestMeanFitness)
                {
                    _bestMeanFitness = i.GetFitness();
                    _bestIndividual  = n;
                    _bestSize        = ((PushGPIndividual)i)._program.ProgramSize();
                    _bestErrors      = i.GetErrors();
                }
            }
            _populationMeanFitness = totalFitness / _populations[_currentPopulation].Length;
        }
Пример #18
0
    public static GAIndividual xover1p(GAIndividual f, GAIndividual m)
    {
        // 1-point cross over
        int xpoint = 1 + randg.Next(f.nvert - 1);

        int[] child_picklist = new int[f.nvert];
        for (int i = 0; i < xpoint; i++)
        {
            child_picklist[i] = f.picklist[i];
        }

        for (int i = xpoint; i < f.nvert; i++)
        {
            child_picklist[i] = m.picklist[i];
        }

        int[] tmp = GAUtils.picklist2perm(child_picklist);
        int[] l, r;

        if (nextBoolean() == true)
        {
            l = new int[f.left.Length]; // WHY?
            r = new int[tmp.Length - f.left.Length];
        }
        else
        {
            l = new int[m.left.Length]; // WHY?
            r = new int[tmp.Length - m.left.Length];
        }

        for (int i = 0; i < l.Length; i++)
        {
            l[i] = tmp[i];
        }
        for (int i = 0; i < r.Length; i++)
        {
            r[i] = tmp[l.Length + i];
        }

        return(new GAIndividual(l, r));
    }
Пример #19
0
 /// <summary>
 /// Determines the predictor's fitness on a trainer, where the trainer is the
 /// inInput, and the trainer's actual fitness (or rank, whatever is to be
 /// predicted) is inOutput.
 /// </summary>
 /// <returns>Predictor's fitness (or rank, etc.) for the given trainer.</returns>
 public abstract override float EvaluateTestCase(GAIndividual inIndividual, object inInput, object inOutput);
Пример #20
0
 /// <summary>
 /// Evaluates a PredictionGAIndividual's fitness, based on the difference
 /// between the predictions of the fitnesses of the trainers and the actual
 /// fitnesses of the trainers.
 /// </summary>
 protected internal abstract override void EvaluateIndividual(GAIndividual inIndividual);
Пример #21
0
 /// <summary>Initiates inIndividual as a random predictor individual.</summary>
 protected internal abstract override void InitIndividual(GAIndividual inIndividual);