Example #1
0
        /// <summary>
        /// Performs a single throw onto a roulette wheel where the wheel's space is unevenly divided between outcomes.
        /// The probabilty that a segment will be selected is given by that segment's value in the 'probabilities'
        /// array within the specified RouletteWheelLayout. The probabilities within a RouletteWheelLayout have already
        /// been normalised so that their total is always equal to 1.0.
        /// </summary>
        /// <param name="layout">The roulette wheel layout.</param>
        /// <param name="rng">Random number generator.</param>
        public static int SingleThrow(RouletteWheelLayout layout, FastRandom rng)
        {
            // Throw the ball and return an integer indicating the outcome.
            double throwValue  = layout.ProbabilitiesTotal * rng.NextDouble();
            double accumulator = 0.0;

            for (int i = 0; i < layout.Probabilities.Length; i++)
            {
                accumulator += layout.Probabilities[i];
                if (throwValue < accumulator)
                {
                    return(layout.Labels[i]);
                }
            }

            // We might get here through floating point arithmetic rounding issues.
            // e.g. accumulator == throwValue.

            // Find a nearby non-zero probability to select.
            // Wrap around to start of array.
            for (int i = 0; i < layout.Probabilities.Length; i++)
            {
                if (layout.Probabilities[i] != 0.0)
                {
                    return(layout.Labels[i]);
                }
            }

            // If we get here then we have an array of zero probabilities.
            throw new SharpNeatException("Invalid operation. No non-zero probabilities to select.");
        }
        /// <summary>
        /// Performs a single throw onto a roulette wheel where the wheel's space is unevenly divided between outcomes.
        /// The probabilty that a segment will be selected is given by that segment's value in the 'probabilities'
        /// array within the specified RouletteWheelLayout. The probabilities within a RouletteWheelLayout have already 
        /// been normalised so that their total is always equal to 1.0.
        /// </summary>
        /// <param name="layout">The roulette wheel layout.</param>
        /// <param name="rng">Random number generator.</param>
        public static int SingleThrow(RouletteWheelLayout layout, FastRandom rng)
        {
            // Throw the ball and return an integer indicating the outcome.
            double throwValue = layout.ProbabilitiesTotal * rng.NextDouble();
            double accumulator = 0.0;
            for(int i=0; i<layout.Probabilities.Length; i++)
            {
                accumulator += layout.Probabilities[i];
                if(throwValue < accumulator) {
                    return layout.Labels[i];
                }
            }

            // We might get here through floating point arithmetic rounding issues. 
            // e.g. accumulator == throwValue. 

            // Find a nearby non-zero probability to select.
            // Wrap around to start of array.
            for(int i=0; i<layout.Probabilities.Length; i++)
            {
                if(layout.Probabilities[i] != 0.0) {
                    return layout.Labels[i];
                }
            }

            // If we get here then we have an array of zero probabilities.
            throw new SharpNeatException("Invalid operation. No non-zero probabilities to select.");
        }
        /// <summary>
        ///     Constructor which takes an existing maze genome parameters configuration and copies all of the parameters from it.
        /// </summary>
        /// <param name="copyFrom">The existing maze genome parameters configuration to copy.</param>
        public MazeGenomeParameters(MazeGenomeParameters copyFrom)
        {
            MutateWallStartLocationProbability = copyFrom.MutateWallStartLocationProbability;
            MutatePassageStartLocationProbability = copyFrom.MutatePassageStartLocationProbability;
            MutateAddWallProbability = copyFrom.MutateAddWallProbability;
            PerturbanceMagnitude = copyFrom.PerturbanceMagnitude;

            RouletteWheelLayout = new RouletteWheelLayout(copyFrom.RouletteWheelLayout);
        }
        /// <summary>
        ///     Default constructor, setting all maze genome parameters to their default and creating the roulette wheel layout.
        /// </summary>
        public MazeGenomeParameters()
        {
            MutateWallStartLocationProbability = DefaultMutateWallStartLocationProbability;
            MutatePassageStartLocationProbability = DefaultMutatePassageStartLocationProbability;
            MutateAddWallProbability = DefaultMutateAddWallProbability;
            PerturbanceMagnitude = DefaultPerturbanceMagnitude;

            // Create a new roulette wheel layout with the default probabilities
            RouletteWheelLayout = CreateRouletteWheelLayout();
        }
Example #5
0
        public MarkovChain(MarkovChainNode[] nodes, int stepsPerActivation, FastRandom random)
        {
            _nodes = nodes;
            _stepsPerActivation = stepsPerActivation;
            _random = random;

            _rouletteWheels = new RouletteWheelLayout[nodes.Length];
            for (int i = 0; i < nodes.Length; i++)
                _rouletteWheels[i] = new RouletteWheelLayout(nodes[i].TransitionProbabilities);
        }
        /// <summary>
        /// Constructs an activation function library with a default set of activation functions.
        /// </summary>
        public DefaultCppnActivationFunctionLibrary()
        {
            _functionList = new List<ActivationFunctionInfo>(4);
            double[] probabilities = {0.25, 0.25, 0.25, 0.25};
            _functionList.Add(new ActivationFunctionInfo(0, probabilities[0], Linear.__DefaultInstance));
            _functionList.Add(new ActivationFunctionInfo(1, probabilities[1], BipolarSigmoid.__DefaultInstance));
            _functionList.Add(new ActivationFunctionInfo(2, probabilities[2], Gaussian.__DefaultInstance));
            _functionList.Add(new ActivationFunctionInfo(3, probabilities[3], Sine.__DefaultInstance));
            _rwl = new RouletteWheelLayout(probabilities);

            _functionDict = CreateFunctionDictionary(_functionList);
        }
        /// <summary>
        /// Constructs an activation function library with the provided list of activation functions.
        /// </summary>
        public DefaultActivationFunctionLibrary(IList<ActivationFunctionInfo> fnList)
        {
            // Build a RouletteWheelLayout based on the selection probability on each item.
            int count = fnList.Count;
            double[] probabilities = new double[count];
            for(int i=0; i<count; i++) {
                probabilities[i] = fnList[i].SelectionProbability;
            }
            _rwl = new RouletteWheelLayout(probabilities);
            _functionList = fnList;

            // Build a dictionary of functions keyed on integer ID.
            _functionDict = CreateFunctionDictionary(_functionList);
        }
        static Dictionary<string, double> morphEnglish(Dictionary<string, double> english, double[] digitProbs, double[] posProbs, int minLength = 0)
        {
            Dictionary<string, double> results = new Dictionary<string, double>();

            FastRandom random = new FastRandom();
            
            Console.WriteLine("Probs sum: {0}", digitProbs.Sum());
            RouletteWheelLayout digitLayout = new RouletteWheelLayout(digitProbs);
            RouletteWheelLayout posLayout = new RouletteWheelLayout(posProbs);
            int alreadyNumbered = 0;
            foreach (string s in english.Keys)
            {
                bool numbered = false;
                for (int i = 0; i < s.Length; i++)
                    if (s[i] >= '0' && s[i] <= '9')
                    {
                        alreadyNumbered++;
                        numbered = true;
                        break;
                    }
                string morphedPassword = s;
                while (!numbered || morphedPassword.Length < minLength)
                {
                    int toAdd = RouletteWheel.SingleThrow(digitLayout, random);
                    int pos = RouletteWheel.SingleThrow(posLayout, random);

                    if (pos == 0)
                        break;
                    else if (pos == 1)
                        morphedPassword = toAdd + morphedPassword;
                    else if (pos == 2)
                        morphedPassword = morphedPassword + toAdd;
                    else
                    {
                        pos = random.Next(morphedPassword.Length);
                        morphedPassword = morphedPassword.Substring(0, pos) + toAdd + morphedPassword.Substring(pos, morphedPassword.Length - pos);
                    }
                    numbered = true;
                }
                double val;
                if (!results.TryGetValue(morphedPassword, out val))
                    results.Add(morphedPassword, 1);
            }
            Console.WriteLine("Had numbers already: {0}", alreadyNumbered);
            return results;
        }
        /// <summary>
        /// Construct with default set of parameters.
        /// </summary>
        public NeatGenomeParameters()
        {
            _activationFn                               = SteepenedSigmoid.__DefaultInstance;
            _connectionWeightRange                      = DefaultConnectionWeightRange;
            _initialInterconnectionsProportion          = DefaultInitialInterconnectionsProportion;
            _disjointExcessGenesRecombineProbability    = DefaultDisjointExcessGenesRecombineProbability;
            _connectionWeightMutationProbability        = DefaultConnectionWeightMutationProbability;
            _addNodeMutationProbability                 = DefaultAddNodeMutationProbability;
            _addConnectionMutationProbability           = DefaultAddConnectionMutationProbability;
            _nodeAuxStateMutationProbability            = DefaultNodeAuxStateMutationProbability;
            _deleteConnectionMutationProbability        = DefaultDeleteConnectionMutationProbability;

            _rouletteWheelLayout = CreateRouletteWheelLayout();
            _rouletteWheelLayoutNonDestructive = CreateRouletteWheelLayout_NonDestructive();

            // Create a connection weight mutation scheme.
            _connectionMutationInfoList = CreateConnectionWeightMutationScheme_Default();

            // No fitness history.
            _fitnessHistoryLength = 0;
        }
        /// <summary>
        /// Copy constructor.
        /// </summary>
        public NeatGenomeParameters(NeatGenomeParameters copyFrom)
        {
            _feedforwardOnly                            = copyFrom._feedforwardOnly;
            _activationFn                               = copyFrom._activationFn;
            _connectionWeightRange                      = copyFrom._connectionWeightRange;
            _initialInterconnectionsProportion          = copyFrom._initialInterconnectionsProportion;
            _disjointExcessGenesRecombineProbability    = copyFrom._disjointExcessGenesRecombineProbability;
            _connectionWeightMutationProbability        = copyFrom._connectionWeightMutationProbability;
            _addNodeMutationProbability                 = copyFrom._addNodeMutationProbability;
            _addConnectionMutationProbability           = copyFrom._addConnectionMutationProbability;
            _nodeAuxStateMutationProbability            = copyFrom._nodeAuxStateMutationProbability;
            _deleteConnectionMutationProbability        = copyFrom._deleteConnectionMutationProbability;

            _rouletteWheelLayout = new RouletteWheelLayout(copyFrom._rouletteWheelLayout);
            _rouletteWheelLayoutNonDestructive = new RouletteWheelLayout(copyFrom._rouletteWheelLayoutNonDestructive);
            
            _connectionMutationInfoList = new ConnectionMutationInfoList(copyFrom._connectionMutationInfoList);
            _connectionMutationInfoList.Initialize();
            _fitnessHistoryLength = copyFrom._fitnessHistoryLength;
        }
 /// <summary>
 /// Copy constructor.
 /// </summary>
 public RouletteWheelLayout(RouletteWheelLayout copyFrom)
 {
     _probabilitiesTotal = copyFrom._probabilitiesTotal;
     _probabilities = (double[])copyFrom._probabilities.Clone();
     _labels = (int[])copyFrom._labels.Clone();
 }
        /// <summary>
        /// Move the prey. The prey moves by a simple set of stochastic rules that make it more likely to move away from
        /// the agent, and moreso when it is close.
        /// </summary>
        public void MovePrey()
        {
            // Determine if prey will move in this timestep. (Speed is simulated stochastically)
            if(_rng.NextDouble() > _preySpeed) {
                return;
            }

            // Determine position of agent relative to prey.
            PolarPoint relPolarPos = PolarPoint.FromCartesian(_agentPos - _preyPos);

			// Calculate probabilities of moving in each of the four directions. This stochastic strategy is taken from:
            // Incremental Evolution Of Complex General Behavior, Faustino Gomez and Risto Miikkulainen (1997)
            // (http://nn.cs.utexas.edu/downloads/papers/gomez.adaptive-behavior.pdf)
            // Essentially the prey moves randomply but we bias the movements so the prey moves away from the agent, and thus 
            // generally avoids getting eaten through stupidity.
            double T = MovePrey_T(relPolarPos.Radial);
            double[] probs = new double[4];
            probs[0] = Math.Exp((CalcAngleDelta(relPolarPos.Theta, Math.PI/2.0) / Math.PI) * T * 0.33);    // North.
            probs[1] = Math.Exp((CalcAngleDelta(relPolarPos.Theta, 0) / Math.PI) * T * 0.33);              // East.
            probs[2] = Math.Exp((CalcAngleDelta(relPolarPos.Theta, Math.PI * 1.5) / Math.PI) * T * 0.33);  // South.
            probs[3] = Math.Exp((CalcAngleDelta(relPolarPos.Theta, Math.PI) / Math.PI) * T * 0.33);        // West.
            
            RouletteWheelLayout rwl = new RouletteWheelLayout(probs);
            int action = RouletteWheel.SingleThrow(rwl, _rng);
            switch(action)
            {
                 case 0: // Move north.
                    _preyPos._y = Math.Min(_preyPos._y + 1, _gridSize - 1);
                    break;
                case 1: // Move east.
                    _preyPos._x = Math.Min(_preyPos._x + 1, _gridSize - 1);
                    break;
                case 2: // Move south.
                    _preyPos._y = Math.Max(_preyPos._y - 1, 0);
                    break;
                case 3: // Move west (is the best?)
                    _preyPos._x = Math.Max(_preyPos._x - 1, 0);
                    break;
            }
        }
Example #13
0
 /// <summary>
 /// Copy constructor.
 /// </summary>
 public RouletteWheelLayout(RouletteWheelLayout copyFrom)
 {
     _probabilitiesTotal = copyFrom._probabilitiesTotal;
     _probabilities      = (double[])copyFrom._probabilities.Clone();
     _labels             = (int[])copyFrom._labels.Clone();
 }