void IntegerRandomWalkMutation(IMersenneTwister random, FloatVectorSpecies species, int index) { double min = species.GetMinGene(index); double max = species.GetMaxGene(index); if (!species.GetMutationIsBounded(index)) { // okay, technically these are still bounds, but we can't go beyond this without weird things happening max = MAXIMUM_INTEGER_IN_DOUBLE; min = -(max); } do { int n = (int)(random.NextBoolean() ? 1 : -1); double g = Math.Floor(genome[index]); if ((n == 1 && g < max) || (n == -1 && g > min)) { genome[index] = g + n; } else if ((n == -1 && g < max) || (n == 1 && g > min)) { genome[index] = g - n; } }while (random.NextBoolean(species.GetRandomWalkProbability(index))); }
// Creates a toroidal Neighborhood pattern for the individual int[] CreateRandomPattern(int myIndex, bool includeSelf, int popsize, int neighborhoodSize, IEvolutionState state, int threadnum) { // TODO: BRS: We have to solve the problem of Java -> C# (hashtables) IMersenneTwister mtf = state.Random[threadnum]; HashSet <int> already = new HashSet <int>(); int[] neighbors; if (includeSelf) { neighbors = new int[neighborhoodSize + 1]; neighbors[neighborhoodSize] = myIndex; // put me at the top already.Add(myIndex); } else { neighbors = new int[neighborhoodSize]; } Int32 n; for (int i = 0; i < neighborhoodSize; i++) { do { neighbors[i] = mtf.NextInt(popsize); n = neighbors[i]; } while (already.Contains(n)); already.Add(n); } return(neighbors); }
void GaussianMutation(IEvolutionState state, IMersenneTwister random, FloatVectorSpecies species, int index) { double val; double min = species.GetMinGene(index); double max = species.GetMaxGene(index); double stdev = species.GetGaussMutationStdev(index); int outOfBoundsLeftOverTries = species.OutOfBoundsRetries; bool givingUpAllowed = species.OutOfBoundsRetries != 0; do { val = random.NextGaussian() * stdev + genome[index]; outOfBoundsLeftOverTries--; if (species.GetMutationIsBounded(index) && (val > max || val < min)) { if (givingUpAllowed && (outOfBoundsLeftOverTries == 0)) { val = min + random.NextFloat() * (max - min); species.OutOfRangeRetryLimitReached(state);// it better get inlined break; } } else { break; } }while (true); genome[index] = val; }
void IntegerResetMutation(IMersenneTwister random, FloatVectorSpecies species, int index) { long minGene = (long)Math.Floor(species.GetMinGene(index)); long maxGene = (long)Math.Floor(species.GetMaxGene(index)); genome[index] = RandomValueFromClosedInterval(minGene, maxGene, random); //minGene + random.NextLong(maxGene - minGene + 1); }
void FloatResetMutation(IMersenneTwister random, FloatVectorSpecies species, int index) { double minGene = species.GetMinGene(index); double maxGene = species.GetMaxGene(index); genome[index] = minGene + random.NextDouble(true, true) * (maxGene - minGene); }
/// <summary> /// Largely stolen from sim.util.Bag. Shuffles both the indices and the floats. /// </summary> /// <remarks> /// BRS: I'm not really sure what the point is of passing in these arrays as arguments??? /// They are simply references to the instance member arrays. /// </remarks> void ShuffleFitnessesAndIndices(IMersenneTwister random, double[] fitnesses, int[] indices) { // TODO : Figure out why Sean passes these into this method. // The member arrays are basically overwritten in PrepareToProduce // and the arguments here are just references to those arrays. // Why not just operate on the member arrays directly? // I suppose this allows one to pass in other arrays // but that is currently not done anywhere. var numObjs = Fitnesses.Length; //var fitnesses = Fitnesses; //var indices = Indices; for (var x = numObjs - 1; x >= 1; x--) { var rand = random.NextInt(x + 1); var f = fitnesses[x]; fitnesses[x] = fitnesses[rand]; fitnesses[rand] = f; var i = indices[x]; indices[x] = indices[rand]; indices[rand] = i; } }
/** * <p> * Creates a new vector which is drawn from a multivariate normal distribution with zero mean * and the provided covariance. * </p> * * @see CovarianceRandomDraw_DDRM * * @param covariance Covariance of the multivariate normal distribution * @return Vector randomly drawn from the distribution */ public static SimpleMatrix <T> randomNormal(SimpleMatrix <T> covariance, IMersenneTwister random) { SimpleMatrix <T> found = new SimpleMatrix <T>(covariance.numRows(), 1); var m = covariance.getMatrix(); var bits = covariance.bits(); if (bits == 64) { // Check type here to make sure if (typeof(T) != typeof(DMatrixRMaj)) { throw new InvalidOperationException("This operation is only valid for type DMatrixRMaj."); } var draw = new CovarianceRandomDraw_DDRM(random, m as DMatrixRMaj); draw.next(found.getMatrix() as DMatrixRMaj); } else if (bits == 32) { // Check type here to make sure if (typeof(T) != typeof(FMatrixRMaj)) { throw new InvalidOperationException("This operation is only valid for type FMatrixRMaj."); } var draw = new CovarianceRandomDraw_FDRM(random, m as FMatrixRMaj); draw.next(found.getMatrix() as FMatrixRMaj); } else // Unknown data type { throw new InvalidOperationException("Unknown data type: must be double (64 bits) or float (32 bits)."); } return(found); }
/** Returns true if the MersenneTwister's current internal state is equal to another MersenneTwister. * This is roughly the same as equals(other), except that it compares based on value but does not * guarantee the contract of immutability (obviously random number generators are immutable). * Note that this does NOT check to see if the internal gaussian storage is the same * for both. You can guarantee that the internal gaussian storage is the same (and so the * nextGaussian() methods will return the same values) by calling clearGaussian() on both * objects. */ public virtual bool StateEquals(IMersenneTwister o) { if (o == this) { return(true); } if (o == null || !(o is MersenneTwister)) { return(false); } var other = (MersenneTwister)o; lock (other) { if (_mti != other._mti) { return(false); } for (var x = 0; x < _mag01.Length; x++) { if (_mag01[x] != other._mag01[x]) { return(false); } } for (var x = 0; x < _mt.Length; x++) { if (_mt[x] != other._mt[x]) { return(false); } } return(true); } }
/** * Randomly generates matrix with the specified number of non-zero elements filled with values from min to max. * * @param numRows Number of rows * @param numCols Number of columns * @param nz_total Total number of non-zero elements in the matrix * @param min Minimum element value, inclusive * @param max Maximum element value, inclusive * @param rand Random number generator * @return Randomly generated matrix */ public static DMatrixSparseCSC rectangle(int numRows, int numCols, int nz_total, double min, double max, IMersenneTwister rand) { nz_total = Math.Min(numCols * numRows, nz_total); int[] selected = UtilEjml.shuffled(numRows * numCols, nz_total, rand); Array.Sort(selected, 0, nz_total); DMatrixSparseCSC ret = new DMatrixSparseCSC(numRows, numCols, nz_total); ret.indicesSorted = true; // compute the number of elements in each column int[] hist = new int[numCols]; for (int i = 0; i < nz_total; i++) { hist[selected[i] / numRows]++; } // define col_idx ret.colsum(hist); for (int i = 0; i < nz_total; i++) { int row = selected[i] % numRows; ret.nz_rows[i] = row; ret.nz_values[i] = rand.NextDouble() * (max - min) + min; } return(ret); }
/** * Returns a matrix where all the elements are selected independently from * a uniform distribution between 0 and 1 inclusive. * * @param numRow Number of rows in the new matrix. * @param numCol Number of columns in the new matrix. * @param rand Random number generator used to fill the matrix. * @return The randomly generated matrix. */ public static FMatrixRMaj rectangle(int numRow, int numCol, IMersenneTwister rand) { FMatrixRMaj mat = new FMatrixRMaj(numRow, numCol); fillUniform(mat, 0, 1, rand); return(mat); }
/** * Creates a random Hermitian matrix with elements from min to max value. * * @param length Width and height of the matrix. * @param min Minimum value an element can have. * @param max Maximum value an element can have. * @param rand Random number generator. * @return A symmetric matrix. */ public static ZMatrixRMaj hermitian(int length, double min, double max, IMersenneTwister rand) { ZMatrixRMaj A = new ZMatrixRMaj(length, length); fillHermitian(A, min, max, rand); return(A); }
/** * Creates a random symmetric matrix whose values are selected from an uniform distribution * from min to max, inclusive. * * @param length Width and height of the matrix. * @param min Minimum value an element can have. * @param max Maximum value an element can have. * @param rand Random number generator. * @return A symmetric matrix. */ public static FMatrixRMaj symmetric(int length, float min, float max, IMersenneTwister rand) { FMatrixRMaj A = new FMatrixRMaj(length, length); symmetric(A, min, max, rand); return(A); }
/** * Creates a random symmetric matrix whose values are selected from an uniform distribution * from min to max, inclusive. * * @param length Width and height of the matrix. * @param min Minimum value an element can have. * @param max Maximum value an element can have. * @param rand Random number generator. * @return A symmetric matrix. */ public static DMatrixRMaj symmetric(int length, double min, double max, IMersenneTwister rand) { DMatrixRMaj A = new DMatrixRMaj(length, length); symmetric(A, min, max, rand); return(A); }
/** * Sets vector to a random value based upon a zero-mean multivariate Gaussian distribution with * covariance 'cov'. If repeat calls are made to this class, consider using {@link CovarianceRandomDraw_DDRM} instead. * * @param cov The distirbutions covariance. Not modified. * @param vector The random vector. Modified. * @param rand Random number generator. */ public static void randomVector(DMatrixRMaj cov, DMatrixRMaj vector, IMersenneTwister rand) { CovarianceRandomDraw_DDRM rng = new CovarianceRandomDraw_DDRM(rand, cov); rng.next(vector); }
/** * Returns new bool matrix with true or false values selected with equal probability. * * @param numRow Number of rows in the new matrix. * @param numCol Number of columns in the new matrix. * @param rand Random number generator used to fill the matrix. * @return The randomly generated matrix. */ public static BMatrixRMaj randomBinary(int numRow, int numCol, IMersenneTwister rand) { BMatrixRMaj mat = new BMatrixRMaj(numRow, numCol); setRandomB(mat, rand); return(mat); }
/** * Creates a random Hermitian matrix with elements from min to max value. * * @param length Width and height of the matrix. * @param min Minimum value an element can have. * @param max Maximum value an element can have. * @param rand Random number generator. * @return A symmetric matrix. */ public static CMatrixRMaj hermitian(int length, float min, float max, IMersenneTwister rand) { CMatrixRMaj A = new CMatrixRMaj(length, length); fillHermitian(A, min, max, rand); return(A); }
public void Randomize(EvolutionState state, int thread) { IMersenneTwister random = state.Random[thread]; for (int i = 0; i < _ca.Length; i++) { _ca[i] = random.NextBoolean() ? 0 : 1; } }
public static FMatrixRBlock createRandom(int numRows, int numCols, float min, float max, IMersenneTwister rand) { FMatrixRBlock ret = new FMatrixRBlock(numRows, numCols); RandomMatrices_FDRM.fillUniform(ret, min, max, rand); return(ret); }
public static DMatrixSparseCSC triangleUpper(int dimen, int hessenberg, int nz_total, double min, double max, IMersenneTwister rand) { DMatrixSparseCSC L = triangleLower(dimen, hessenberg, nz_total, min, max, rand); DMatrixSparseCSC U = (DMatrixSparseCSC)L.createLike(); CommonOps_DSCC.transpose(L, U, null); return(U); }
public static DMatrixRBlock createRandom(int numRows, int numCols, double min, double max, IMersenneTwister rand) { DMatrixRBlock ret = new DMatrixRBlock(numRows, numCols); RandomMatrices_DDRM.fillUniform(ret, min, max, rand); return(ret); }
/** * <p> * Creates a new vector which is drawn from a multivariate normal distribution with zero mean * and the provided covariance. * </p> * * @see CovarianceRandomDraw_DDRM * * @param covariance Covariance of the multivariate normal distribution * @return Vector randomly drawn from the distribution */ public static SimpleMatrixD randomNormal(SimpleMatrixD covariance, IMersenneTwister random) { SimpleMatrixD found = new SimpleMatrixD(covariance.numRows(), 1); var draw = new CovarianceRandomDraw_DDRM(random, covariance.getMatrix()); draw.next(found.getMatrix()); return(found); }
public static int[] shuffled(int N, int shuffleUpTo, IMersenneTwister rand) { int[] l = new int[N]; for (int i = 0; i < N; i++) { l[i] = i; } shuffle(l, N, 0, shuffleUpTo, rand); return(l); }
/// <summary> /// Returns a tournament size to use, at random, based on base size and probability of picking the size plus one. /// </summary> public int GetTournamentSizeToUse(IMersenneTwister random) { var p = ProbabilityOfPickingSizePlusOne; // pulls us to under 35 bytes if (p == 0.0) { return(Size); } return(Size + (random.NextBoolean(p) ? 1 : 0)); }
/** * <p> * Sets each element in the matrix to a value drawn from an Gaussian distribution with the specified mean and * standard deviation * </p> * * @param mat The matrix who is to be randomized. Modified. * @param mean Mean value in the distribution * @param stdev Standard deviation in the distribution * @param rand Random number generator used to fill the matrix. */ public static void fillGaussian(DMatrixD1 mat, double mean, double stdev, IMersenneTwister rand) { double[] d = mat.getData(); int size = mat.getNumElements(); for (int i = 0; i < size; i++) { d[i] = mean + stdev * (double)rand.NextGaussian(); } }
/** * <p> * Sets each element in the matrix to a value drawn from an Gaussian distribution with the specified mean and * standard deviation * </p> * * @param mat The matrix who is to be randomized. Modified. * @param mean Mean value in the distribution * @param stdev Standard deviation in the distribution * @param rand Random number generator used to fill the matrix. */ public static void fillGaussian(FMatrixD1 mat, float mean, float stdev, IMersenneTwister rand) { float[] d = mat.getData(); int size = mat.getNumElements(); for (int i = 0; i < size; i++) { d[i] = mean + stdev * (float)rand.NextGaussian(); } }
public override void Setup(IEvolutionState state, IParameter paramBase) { base.Setup(state, paramBase); state.Output.ExitIfErrors(); IParameter kval = new Parameter(EvolutionState.P_EVALUATOR).Push(P_PROBLEM).Push(P_PROBLEMNAME) .Push(P_KVALUE); k = state.Parameters.GetInt(kval, null, 0); // System.out.println("K = " + k); for (int i = 0; i < _indices.Length; i++) { _indices[i] = -1; } _indices['A' - 'A'] = 0; _indices['B' - 'A'] = 1; _indices['X' - 'A'] = 2; _indices['Y' - 'A'] = 3; _indices['Z' - 'A'] = 4; _indices['W' - 'A'] = 5; // now do some initialization IMersenneTwister r = state.Random[0]; _nodeScore = new double[6]; _edgeScore = TensorFactory.Create <double>(2, 6); for (int i = 0; i < 6; i++) { _nodeScore[i] = 2 * r.NextDouble() - 1; } // We need to assure that the best fitness is positive (to normalize it to 1) // A method to do this is to have at least one terminal symbol with a positive score. bool ok = false; for (int i = 2; i < 6; i++) { if (_nodeScore[i] > 0) { ok = true; } } if (!ok) { _nodeScore[2] = r.NextDouble(); } for (int i = 0; i < 2; i++) { for (int j = 0; j < 6; j++) { _edgeScore[i][j] = r.NextDouble(); } } _bestFitness = ComputeBestFitness(); }
public static void setRandom(FMatrix a, float min, float max, IMersenneTwister rand) { for (int i = 0; i < a.getNumRows(); i++) { for (int j = 0; j < a.getNumCols(); j++) { float val = rand.NextFloat() * (max - min) + min; a.set(i, j, val); } } }
public static void setRandom(DMatrix a, double min, double max, IMersenneTwister rand) { for (int i = 0; i < a.getNumRows(); i++) { for (int j = 0; j < a.getNumCols(); j++) { double val = rand.NextDouble() * (max - min) + min; a.set(i, j, val); } } }
/** * <p> * Sets each element in the bool matrix to true or false with equal probability * </p> * * @param mat The matrix who is to be randomized. Modified. * @param rand Random number generator used to fill the matrix. */ public static void setRandomB(BMatrixRMaj mat, IMersenneTwister rand) { bool[] d = mat.data; int size = mat.getNumElements(); for (int i = 0; i < size; i++) { d[i] = rand.NextBoolean(); } }
/** * <p> * Creates a randomly generated set of orthonormal vectors. At most it can generate the same * number of vectors as the dimension of the vectors. * </p> * * <p> * This is done by creating random vectors then ensuring that they are orthogonal * to all the ones previously created with reflectors. * </p> * * <p> * NOTE: This employs a brute force O(N<sup>3</sup>) algorithm. * </p> * * @param dimen dimension of the space which the vectors will span. * @param numVectors How many vectors it should generate. * @param rand Used to create random vectors. * @return Array of N random orthogonal vectors of unit length. */ // is there a faster algorithm out there? This one is a bit sluggish public static FMatrixRMaj[] span(int dimen, int numVectors, IMersenneTwister rand) { if (dimen < numVectors) { throw new ArgumentException("The number of vectors must be less than or equal to the dimension"); } FMatrixRMaj[] u = new FMatrixRMaj[numVectors]; u[0] = RandomMatrices_FDRM.rectangle(dimen, 1, -1, 1, rand); NormOps_FDRM.normalizeF(u[0]); for (int i = 1; i < numVectors; i++) { // Console.WriteLine(" i = "+i); FMatrixRMaj a = new FMatrixRMaj(dimen, 1); FMatrixRMaj r = null; for (int j = 0; j < i; j++) { // Console.WriteLine("j = "+j); if (j == 0) { r = RandomMatrices_FDRM.rectangle(dimen, 1, -1, 1, rand); } // find a vector that is normal to vector j // u[i] = (1/2)*(r + Q[j]*r) a.set(r); VectorVectorMult_FDRM.householder(-2.0f, u[j], r, a); CommonOps_FDRM.add(r, a, a); CommonOps_FDRM.scale(0.5f, a); // UtilEjml.print(a); FMatrixRMaj t = a; a = r; r = t; // normalize it so it doesn't get too small float val = NormOps_FDRM.normF(r); if (val == 0 || float.IsNaN(val) || float.IsInfinity(val)) { throw new InvalidOperationException("Failed sanity check"); } CommonOps_FDRM.divide(r, val); } u[i] = r; } return(u); }