public void SystemRandomComparison() { var sb = new StringBuilder(); var r = new MersenneTwisterFast(new int[] { 0x123, 0x234, 0x345, 0x456 }); // SPEED TEST sb.AppendLine("\nTime to test grabbing 100000000 ints"); const long SEED = 4357; int j; var rr = new Random((Int32)SEED); var xx = 0; var ms = DateTimeHelper.CurrentTimeMilliseconds; for (j = 0; j < 100000000; j++) { xx += rr.Next(); } sb.AppendLine("System.Random: " + (DateTimeHelper.CurrentTimeMilliseconds - ms) + " Ignore this: " + xx); r = new MersenneTwisterFast(SEED); ms = DateTimeHelper.CurrentTimeMilliseconds; xx = 0; for (j = 0; j < 100000000; j++) { xx += r.NextInt(); } sb.AppendLine("Mersenne Twister Fast: " + (DateTimeHelper.CurrentTimeMilliseconds - ms) + " Ignore this: " + xx); context.WriteLine(sb.ToString()); }
public void CharArray() { var n = 1000; var rand = new MersenneTwisterFast(0L); var r = new char[n]; for (var i = 0; i < n; i++) { r[i] = rand.NextChar(); } var a = (char[])r.Clone(); Array.Sort(r); // Reference QuickSort.QSort(a); // Test // First we just ensure that values are sorted. var last = r[0]; for (var i = 1; i < r.Length; i++) { Assert.IsTrue(r[i] >= last); } // Now we make sure both arrays are in the same order. for (var i = 0; i < a.Length; i++) { Assert.AreEqual(r[i], a[i]); } }
public void ObjectArray() { var n = 1000; var rand = new MersenneTwisterFast(0L); var r = new object[n]; for (var i = 0; i < n; i++) { r[i] = rand.NextChar(); } var a = (object[])r.Clone(); Array.Sort(r); // Reference Array.Reverse(r); // Reverse the sorted array so we can check results against those produced by the custom comparator. QuickSort.QSort(a, new CharReverseSortComparator()); // Test // First we just ensure that values are sorted. var last = r[0]; for (var i = 1; i < r.Length; i++) { Assert.IsTrue(((char)r[i]) <= ((char)last)); } // Now we make sure both arrays are in the same order. for (var i = 0; i < a.Length; i++) { Assert.AreEqual(((char)r[i]), ((char)a[i])); } }
public void SimpleFitnessWriteAndRead() { var rand = new MersenneTwisterFast(0); var f = new SimpleFitness(); f.SetFitness(null, float.MaxValue, true); // Set up some random Trials just to check that they get transmitted const int n = 10; f.Trials = new List <double>(n); for (var i = 0; i < n; i++) { f.Trials.Add(rand.NextDouble()); } using (var ms = new MemoryStream()) { var writer = new BinaryWriter(ms); f.WriteFitness(null, writer); // Write ms.Position = 0; var reader = new BinaryReader(ms); var f2 = new SimpleFitness(); f2.ReadFitness(null, reader); // Read // Compare Assert.AreEqual(f.Value, f2.Value); // Value is same Assert.IsTrue(f2.IsIdeal); // Fitness is ideal Assert.AreEqual(f2.Trials.Count, f.Trials.Count); // Number of trials is the same for (var i = 0; i < f.Trials.Count; i++) { Assert.AreEqual((double)f.Trials[i], (double)f2.Trials[i]); // Trial values are all the same } } }
/// <summary> /// Primes the generator. Mersenne Twister seeds its first 624 numbers using a basic /// linear congruential generator; thereafter it uses the MersenneTwister algorithm to /// build new seeds. Those first 624 numbers are generally just fine, but to be extra /// safe, you can prime the generator by calling nextInt() on it some (N>1) * 624 times. /// This method does exactly that, presently with N=2. /// </summary> /// <param name="generator"></param> /// <returns></returns> public static MersenneTwisterFast PrimeGenerator(MersenneTwisterFast generator) { for (var i = 0; i < 624 * 2; i++) { generator.NextInt(); } return(generator); }
/// <summary> /// Initializes an evolutionary run given the parameters and a random seed adjustment (added to each random seed), /// with the Output pre-constructed. /// The adjustment offers a convenient way to change the seeds of the random number generators each time you /// do a new evolutionary run. You are of course welcome to replace the random number generators after initialize(...) /// but before startFresh(...). /// </summary> /// <param name="parameters"></param> /// <param name="randomSeedOffset"></param> /// <param name="output"></param> /// <returns></returns> public static EvolutionState Initialize(IParameterDatabase parameters, int randomSeedOffset, Output output) { var breedthreads = 1; var evalthreads = 1; //bool store; //int x; // output was already created for us. output.SystemMessage(ECVersion.Message()); // 2. set up thread values breedthreads = DetermineThreads(output, parameters, new Parameter(P_BREEDTHREADS)); evalthreads = DetermineThreads(output, parameters, new Parameter(P_EVALTHREADS)); var auto = (V_THREADS_AUTO.ToUpper().Equals(parameters.GetString(new Parameter(P_BREEDTHREADS), null).ToUpper()) || V_THREADS_AUTO.ToUpper().Equals( parameters.GetString(new Parameter(P_EVALTHREADS), null).ToUpper())); // at least one thread is automatic. Seeds may need to be dynamic. // 3. create the Mersenne Twister random number generators, // one per thread var random = new MersenneTwisterFast[1]; var seedMessage = "Seed: "; // Get time in milliseconds var time = (int)DateTimeHelper.CurrentTimeMilliseconds; var seed = 0; seed = DetermineSeed(output, parameters, new Parameter(P_SEED).Push("" + 0), time + 0, random.Length * randomSeedOffset, auto); random[0] = PrimeGenerator(new MersenneTwisterFast(seed)); // we prime the generator to be more sure of randomness. seedMessage = seedMessage + seed + " "; // 4. Start up the evolution // what evolution state to use? var state = (EvolutionState)parameters.GetInstanceForParameter(new Parameter(P_STATE), null, typeof(IEvolutionState)); state.Parameters = parameters; state.Random = random; state.Output = output; state.EvalThreads = evalthreads; state.BreedThreads = breedthreads; state.RandomSeedOffset = randomSeedOffset; output.SystemMessage($"Threads: breed/{breedthreads} eval/{evalthreads}"); output.SystemMessage(seedMessage); return(state); }
public void GPIndividualWriteAndRead() { // First we'll set up a Fitness for the Individual var rand = new MersenneTwisterFast(0); // Initialize some required context var state = new SimpleEvolutionState(); var initializer = new GPInitializer(); state.Initializer = initializer; // Required for GPTree.WriteTree(...) var constraints = new GPTreeConstraints { Name = "TestTreeConstraints" }; //initializer.TreeConstraints var tree = new GPTree(); var f = new KozaFitness(); f.SetStandardizedFitness(null, float.MaxValue); const int n = 10; f.Trials = new List <double>(n); for (var i = 0; i < n; i++) { f.Trials.Add(rand.NextDouble()); } // Now we can create and initialize the Individual var ind = new GPIndividual(); var ind2 = new GPIndividual(); // We'll read back into this instance ind.Trees = new GPTree[1]; // This is the set of genes ind.Trees[0] = new GPTree(); ind.Fitness = f; ind.Evaluated = true; using (var ms = new MemoryStream()) { var writer = new BinaryWriter(ms); ind.WriteIndividual(null, writer); ms.Position = 0; var reader = new BinaryReader(ms); ind2.Fitness = new SimpleFitness(); ind2.ReadIndividual(null, reader); Assert.IsTrue(ind.Fitness.EquivalentTo(ind2.Fitness)); Assert.IsTrue(ind2.Fitness.IsIdeal); Assert.IsTrue(ind.Equals(ind2)); // Genetically equivalent Assert.AreEqual(ind.Trees.Length, ind2.Trees.Length); } }
/// <summary> /// Primes the generator. Mersenne Twister seeds its first 624 numbers using a basic /// linear congruential generator; thereafter it uses the MersenneTwister algorithm to /// build new seeds. Those first 624 numbers are generally just fine, but to be extra /// safe, you can prime the generator by calling nextInt() on it some (N>1) * 624 times. /// This method does exactly that, presently with N=2. /// </summary> /// <param name="generator"></param> /// <returns></returns> public static MersenneTwisterFast PrimeGenerator(MersenneTwisterFast generator) { // 624 = MersenneTwisterFast.N which is private duh for (var i = 0; i < 624 * 2 + 1; i++) { generator.NextInt(); } return(generator); }
public void ShortVectorIndividualWriteAndRead() { // First we'll set up a Fitness for the Individual var rand = new MersenneTwisterFast(0); var f = new SimpleFitness(); f.SetFitness(null, float.MaxValue, true); const int n = 10; f.Trials = new List <double>(n); for (var i = 0; i < n; i++) { f.Trials.Add(rand.NextDouble()); } // Now we can create and initialize the Individual var ind = new ShortVectorIndividual(); var ind2 = new ShortVectorIndividual(); // We'll read back into this instance ind.Genome = new short[10]; // This is the set of genes for (var i = 0; i < 10; i++) { ind.genome[i] = (short)rand.NextInt(short.MaxValue); // Some random genes } ind.Fitness = f; ind.Evaluated = true; using (var ms = new MemoryStream()) { var writer = new BinaryWriter(ms); ind.WriteIndividual(null, writer); ms.Position = 0; var reader = new BinaryReader(ms); ind2.Fitness = new SimpleFitness(); ind2.ReadIndividual(null, reader); Assert.IsTrue(ind.Fitness.EquivalentTo(ind2.Fitness)); Assert.IsTrue(ind2.Fitness.IsIdeal); Assert.IsTrue(ind.Equals(ind2)); // Genetically equivalent for (var i = 0; i < 10; i++) { Assert.AreEqual(ind.genome[i], ind2.genome[i]); // check each gene } } }
/// <summary> /// Build an NxN rotation matrix[row][column] with a given seed. /// </summary> public static double[] /* row */ [] /* column */ BuildRotationMatrix(IEvolutionState state, long rotationSeed, int N) { if (rotationSeed == ROTATION_SEED) { state.Output.WarnOnce("Default rotation seed being used (" + rotationSeed + ")"); } IMersenneTwister rand = new MersenneTwisterFast(ROTATION_SEED); for (int i = 0; i < 624 * 4; i++) // prime the MT for 4 full sample iterations to get it warmed up { rand.NextInt(); } double[] /* row */ [] /* column */ o = TensorFactory.Create <double>(N, N); // make random values for (var i = 0; i < N; i++) { for (var k = 0; k < N; k++) { o[i][k] = rand.NextGaussian(); } } // build random values for (var i = 0; i < N; i++) { // extract o[i] -> no var no = new double[N]; for (var k = 0; k < N; k++) { no[k] = o[i][k]; } // go through o[i] and o[j], modifying no for (var j = 0; j < i; j++) { var d = Dot(o[i], o[j]); var val = ScalarMul(d, o[j]); no = Sub(no, val); } o[i] = Normalize(no); } return(o); }
public static void main(string[] args) { // create a random matrix that can be solved int N = 5; IMersenneTwister rand = new MersenneTwisterFast(234); DMatrixSparseCSC A = RandomMatrices_DSCC.rectangle(N, N, N * N / 4, rand); RandomMatrices_DSCC.ensureNotSingular(A, rand); // Create the LU decomposition LUSparseDecomposition_F64 <DMatrixSparseCSC> decompose = DecompositionFactory_DSCC.lu(FillReducing.NONE); // Decompose the matrix. // If you care about the A matrix being modified call decompose.inputModified() if (!decompose.decompose(A)) { throw new InvalidOperationException("The matrix is singular"); } // Extract new copies of the L and U matrices DMatrixSparseCSC L = decompose.getLower(null); DMatrixSparseCSC U = decompose.getUpper(null); DMatrixSparseCSC P = decompose.getRowPivot(null); // Storage for an intermediate step DMatrixSparseCSC tmp = (DMatrixSparseCSC)A.createLike(); // Storage for the inverse matrix DMatrixSparseCSC Ainv = (DMatrixSparseCSC)A.createLike(); // Solve for the inverse: P*I = L*U*inv(A) TriangularSolver_DSCC.solve(L, true, P, tmp, null, null, null); TriangularSolver_DSCC.solve(U, false, tmp, Ainv, null, null, null); // Make sure the inverse has been found. A*inv(A) = identity should be an identity matrix DMatrixSparseCSC found = (DMatrixSparseCSC)A.createLike(); CommonOps_DSCC.mult(A, Ainv, found); found.print(); }
public static void main(string[] args) { IMersenneTwister rand = new MersenneTwisterFast(234); Equation.Equation eq = new Equation.Equation(); eq.getFunctions().add("multTransA", createMultTransA()); SimpleMatrix <DMatrixRMaj> A = new SimpleMatrix <DMatrixRMaj>(1, 1); // will be resized SimpleMatrix <DMatrixRMaj> B = SimpleMatrix <DMatrixRMaj> .random64(3, 4, -1, 1, rand); SimpleMatrix <DMatrixRMaj> C = SimpleMatrix <DMatrixRMaj> .random64(3, 4, -1, 1, rand); eq.alias(A, "A", B, "B", C, "C"); eq.process("A=multTransA(B,C)"); Console.WriteLine("Found"); Console.WriteLine(A); Console.WriteLine("Expected"); B.transpose().mult(C).print(); }
public void KozaFitnessWriteAndRead() { var rand = new MersenneTwisterFast(0); var f = new KozaFitness(); // Standardized fitness ranges from 0.0f inclusive to PositiveInfinity exclusive where 0.0f is ideal // Adjusted fitness ranges from 0.0f inclusive to 1.0f exclusive, where higher is better f.SetStandardizedFitness(null, float.MaxValue); // Set up some random Trials just to check that they get transmitted const int n = 10; f.Trials = new List <double>(n); for (var i = 0; i < n; i++) { f.Trials.Add(rand.NextDouble() * double.MaxValue); // in the half-open interval [0.0, double.MaxValue) } using (var ms = new MemoryStream()) { var writer = new BinaryWriter(ms); f.WriteFitness(null, writer); // Write ms.Position = 0; var reader = new BinaryReader(ms); var f2 = new KozaFitness(); f2.ReadFitness(null, reader); // Read // Compare Assert.AreEqual(f.Value, f2.Value); // Value is same // KozaFitness defines 'Value' as AdjustedFitness [0.0, 1.0), i.e. zero is valid but one is not Assert.IsTrue(f.Value < 1.0f && f2.Value < 1.0f); Assert.IsFalse(f2.IsIdeal); // Fitness is ideal Assert.AreEqual(f2.Trials.Count, f.Trials.Count); // Number of trials is the same for (var i = 0; i < f.Trials.Count; i++) { Assert.AreEqual((double)f.Trials[i], (double)f2.Trials[i]); // Trial values are all the same } } }
/// <summary> /// Build an NxN rotation matrix[row][column] with a given seed. /// </summary> public static double[] /* row */ [] /* column */ BuildRotationMatrix(double rotationSeed, int N) { IMersenneTwister rand = new MersenneTwisterFast(ROTATION_SEED); double[] /* row */ [] /* column */ o = TensorFactory.Create <double>(N, N); // make random values for (var i = 0; i < N; i++) { for (var k = 0; k < N; k++) { o[i][k] = rand.NextGaussian(); } } // build random values for (var i = 0; i < N; i++) { // extract o[i] -> no var no = new double[N]; for (var k = 0; k < N; k++) { no[k] = o[i][k]; } // go through o[i] and o[j], modifying no for (var j = 0; j < i; j++) { var d = Dot(o[i], o[j]); var val = ScalarMul(d, o[j]); no = Sub(no, val); } o[i] = Normalize(no); } return(o); }
public static void main(string[] args) { IMersenneTwister rand = new MersenneTwisterFast(24234); int N = 500; // create two vectors whose elements are drawn from uniform distributions StatisticsMatrix A = StatisticsMatrix.wrap(RandomMatrices_DDRM.rectangle(N, 1, 0, 1, rand)); StatisticsMatrix B = StatisticsMatrix.wrap(RandomMatrices_DDRM.rectangle(N, 1, 1, 2, rand)); // the mean should be about 0.5 Console.WriteLine("Mean of A is " + A.mean()); // the mean should be about 1.5 Console.WriteLine("Mean of B is " + B.mean()); StatisticsMatrix C = (StatisticsMatrix)A.plus(B); // the mean should be about 2.0 Console.WriteLine("Mean of C = A + B is " + C.mean()); Console.WriteLine("Standard deviation of A is " + A.stdev()); Console.WriteLine("Standard deviation of B is " + B.stdev()); Console.WriteLine("Standard deviation of C is " + C.stdev()); }
public void MultiObjectiveFitnessWriteAndRead() { var rand = new MersenneTwisterFast(0); var f = new MultiObjectiveFitness(2); var f2 = new MultiObjectiveFitness(2); // We'll use this when we read the other one back in f2.SetObjectives(null, new [] { 0.0, 0.0 }); // setting these to zero allows us to check if they change // Default is to Maximize! // These need to be set up manually here because we are not running 'Setup'. // Every instance would thus normally share the same min and max values. f.MaxObjective = new [] { 1.0, 1.0 }; f.MinObjective = new [] { 0.0, 0.0 }; f2.MaxObjective = new[] { 1.0, 1.0 }; f2.MinObjective = new[] { 0.0, 0.0 }; // Set two objective (fitness) values, worst and best respectively f.SetObjectives(null, new [] { 0.0, 1.0 }); // Set up some random Trials just to check that they get transmitted const int n = 10; f.Trials = new List <double>(n); for (var i = 0; i < n; i++) { f.Trials.Add(rand.NextDouble() * double.MaxValue); // in the half-open interval [0.0, double.MaxValue) } using (var ms = new MemoryStream()) { var writer = new BinaryWriter(ms); f.WriteFitness(null, writer); // Write ms.Position = 0; var reader = new BinaryReader(ms); f2.ReadFitness(null, reader); // Read // Compare Assert.AreEqual(f.Value, f2.Value); // Value is same. This is the MAX objective value in the array // Just for kicks, lets make sure BOTH objectives are equal to the original values Assert.AreEqual(f.GetObjective(0), 0.0); Assert.AreEqual(f.GetObjective(0), f2.GetObjective(0)); Assert.AreEqual(f.GetObjective(1), 1.0); Assert.AreEqual(f.GetObjective(1), f2.GetObjective(1)); // And let's make sure our MAX and MIN are the same (these wouldn't normally change once established in 'Setup') Assert.AreEqual(f.MinObjective[0], f2.MinObjective[0]); Assert.AreEqual(f.MinObjective[1], f2.MinObjective[1]); Assert.AreEqual(f.MaxObjective[0], f2.MaxObjective[0]); Assert.AreEqual(f.MaxObjective[1], f2.MaxObjective[1]); Assert.IsTrue(f.Value <= 1.0f && f2.Value <= 1.0f); // This is the MAX objective value in the array Assert.IsFalse(f2.IsIdeal); // Fitness is not ideal by default (ideal must be defined in subclass) Assert.AreEqual(f2.Trials.Count, f.Trials.Count); // Number of trials is the same for (var i = 0; i < f.Trials.Count; i++) { Assert.AreEqual((double)f.Trials[i], (double)f2.Trials[i]); // Trial values are all the same } } }
public static void main(String[] args) { IMersenneTwister rand = new MersenneTwisterFast(234); // easy to work with sparse format, but hard to do computations with DMatrixSparseTriplet work = new DMatrixSparseTriplet(5, 4, 5); work.addItem(0, 1, 1.2); work.addItem(3, 0, 3); work.addItem(1, 1, 22.21234); work.addItem(2, 3, 6); // convert into a format that's easier to perform math with DMatrixSparseCSC Z = ConvertDMatrixStruct.convert(work, (DMatrixSparseCSC)null); // print the matrix to standard out in two different formats Z.print(); Console.WriteLine(); Z.printNonZero(); Console.WriteLine(); // Create a large matrix that is 5% filled DMatrixSparseCSC A = RandomMatrices_DSCC.rectangle(ROWS, COLS, (int)(ROWS * COLS * 0.05), rand); // large vector that is 70% filled DMatrixSparseCSC x = RandomMatrices_DSCC.rectangle(COLS, XCOLS, (int)(XCOLS * COLS * 0.7), rand); Console.WriteLine("Done generating random matrices"); // storage for the initial solution DMatrixSparseCSC y = new DMatrixSparseCSC(ROWS, XCOLS, 0); DMatrixSparseCSC z = new DMatrixSparseCSC(ROWS, XCOLS, 0); // To demonstration how to perform sparse math let's multiply: // y=A*x // Optional storage is set to null so that it will declare it internally long before = DateTimeHelper.CurrentTimeMilliseconds; IGrowArray workA = new IGrowArray(A.numRows); DGrowArray workB = new DGrowArray(A.numRows); for (int i = 0; i < 100; i++) { CommonOps_DSCC.mult(A, x, y, workA, workB); CommonOps_DSCC.add(1.5, y, 0.75, y, z, workA, workB); } long after = DateTimeHelper.CurrentTimeMilliseconds; Console.WriteLine("norm = " + NormOps_DSCC.fastNormF(y) + " sparse time = " + (after - before) + " ms"); DMatrixRMaj Ad = ConvertDMatrixStruct.convert(A, (DMatrixRMaj)null); DMatrixRMaj xd = ConvertDMatrixStruct.convert(x, (DMatrixRMaj)null); DMatrixRMaj yd = new DMatrixRMaj(y.numRows, y.numCols); DMatrixRMaj zd = new DMatrixRMaj(y.numRows, y.numCols); before = DateTimeHelper.CurrentTimeMilliseconds; for (int i = 0; i < 100; i++) { CommonOps_DDRM.mult(Ad, xd, yd); CommonOps_DDRM.add(1.5, yd, 0.75, yd, zd); } after = DateTimeHelper.CurrentTimeMilliseconds; Console.WriteLine("norm = " + NormOps_DDRM.fastNormF(yd) + " dense time = " + (after - before) + " ms"); }
private void GenerateSearchJob(DateTime testTime, int[] minIVs, int[] maxIVs, uint VCountMin, uint VCountMax, uint Timer0Min, uint Timer0Max, uint GxStatMin, uint GxStatMax, uint VFrameMin, uint VFrameMax, int secondsMin, int secondsMax, Version version, Language language, DSType dstype, int[] button, bool softReset, bool roamer, bool minMaxGxStat) { // offset the start by 2 for BW2 int offset = version == Version.Black2 || version == Version.White2 ? 2 : 0; uint buttonMashed = Functions.buttonMashed(button); var array = new uint[80]; uint[] h = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 }; array[6] = (uint)(MAC_address & 0xFFFF); if (softReset) { array[6] = array[6] ^ 0x01000000; } var upperMAC = (uint)(MAC_address >> 16); // Get the version-unique part of the message Array.Copy(Nazos.Nazo(version, language, dstype), array, 5); array[10] = 0x00000000; array[11] = 0x00000000; array[12] = buttonMashed; array[13] = 0x80000000; array[14] = 0x00000000; array[15] = 0x000001A0; array[8] = Functions.seedDate(testTime); var GxStatList = new List <uint> { GxStatMin }; // build the GxStat ranges if (GxStatMin != GxStatMax) { if (!minMaxGxStat) { GxStatList.Add(GxStatMax); } else { for (uint i = GxStatMin + 1; i <= GxStatMax; ++i) { GxStatList.Add(i); } } } for (int cntSeconds = secondsMin; cntSeconds <= secondsMax; cntSeconds++) { array[9] = Functions.seedTime(testTime, dstype); for (uint cntVCount = VCountMin; cntVCount <= VCountMax; cntVCount++) { for (uint cntTimer0 = Timer0Min; cntTimer0 <= Timer0Max; cntTimer0++) { array[5] = cntVCount * 0x10000 + cntTimer0; array[5] = Functions.Reorder(array[5]); foreach (uint GxStat in GxStatList) { for (uint cntVFrame = VFrameMin; cntVFrame <= VFrameMax; cntVFrame++) { uint a = h[0]; uint b = h[1]; uint c = h[2]; uint d = h[3]; uint e = h[4]; uint f = 0; uint k = 0; array[7] = (upperMAC ^ (cntVFrame * 0x1000000) ^ GxStat); for (int i = 0; i < 80; i++) { if (i < 20) { f = (b & c) | ((~b) & d); k = 0x5A827999; } if (i < 40 && i >= 20) { f = b ^ c ^ d; k = 0x6ED9EBA1; } if (i < 60 && i >= 40) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; } if (i >= 60) { f = b ^ c ^ d; k = 0xCA62C1D6; } if (i > 15) { array[i] = Functions.RotateLeft( array[i - 3] ^ array[i - 8] ^ array[i - 14] ^ array[i - 16], 1); } uint temp = Functions.RotateLeft(a, 5) + f + e + k + array[i]; e = d; d = c; c = Functions.RotateRight(b, 2); b = a; a = temp; } uint part1 = Functions.Reorder(h[0] + a); uint part2 = Functions.Reorder(h[1] + b); ulong seed2 = (ulong)part1 * 0x6C078965; uint seed1 = part2 * 0x6C078965 + (uint)(seed2 >> 32); seed1 = seed1 + (part1 * 0x5D588B65); seed2 = (uint)(seed2 & 0xFFFFFFFF) + 0x269EC3; ulong seed = (ulong)(seed1 * 0x100000000) + seed2; var tempSeed = (uint)(seed >> 32); progressSearched++; if (!findDirectSeed) { var IVArray = new int[6]; MersenneTwisterFast mt; if (roamer) { mt = new MersenneTwisterFast(tempSeed, 7); mt.Nextuint(); IVArray[0] = (int)(mt.Nextuint() >> 27); IVArray[1] = (int)(mt.Nextuint() >> 27); IVArray[2] = (int)(mt.Nextuint() >> 27); IVArray[4] = (int)(mt.Nextuint() >> 27); IVArray[5] = (int)(mt.Nextuint() >> 27); IVArray[3] = (int)(mt.Nextuint() >> 27); } else { //advance for BW2 mt = new MersenneTwisterFast(tempSeed, 6 + offset); for (int i = 0; i < offset; ++i) { mt.Nextuint(); } IVArray[0] = (int)(mt.Nextuint() >> 27); IVArray[1] = (int)(mt.Nextuint() >> 27); IVArray[2] = (int)(mt.Nextuint() >> 27); IVArray[3] = (int)(mt.Nextuint() >> 27); IVArray[4] = (int)(mt.Nextuint() >> 27); IVArray[5] = (int)(mt.Nextuint() >> 27); } if ((IVArray[0] >= minIVs[0] && IVArray[0] <= maxIVs[0]) && (IVArray[1] >= minIVs[1] && IVArray[1] <= maxIVs[1]) && (IVArray[2] >= minIVs[2] && IVArray[2] <= maxIVs[2]) && (IVArray[3] >= minIVs[3] && IVArray[3] <= maxIVs[3]) && (IVArray[4] >= minIVs[4] && IVArray[4] <= maxIVs[4]) && (IVArray[5] >= minIVs[5] && IVArray[5] <= maxIVs[5])) { var dsParameterFound = new DSParameterCapture { ActualSeconds = testTime.Second, VCount = cntVCount, Timer0 = cntTimer0, GxStat = GxStat, VFrame = cntVFrame, Seed = seed }; dsParameters.Add(dsParameterFound); refreshQueue = true; progressFound++; } } else { if (checkBoxHalfSeed.Checked) { if (tempSeed == (int)directSeed) { var dsParameterFound = new DSParameterCapture { ActualSeconds = testTime.Second, VCount = cntVCount, Timer0 = cntTimer0, GxStat = GxStat, VFrame = cntVFrame, Seed = seed }; dsParameters.Add(dsParameterFound); refreshQueue = true; progressFound++; } } else { if (seed == directSeed) { var dsParameterFound = new DSParameterCapture { ActualSeconds = testTime.Second, VCount = cntVCount, Timer0 = cntTimer0, GxStat = GxStat, VFrame = cntVFrame, Seed = seed }; dsParameters.Add(dsParameterFound); refreshQueue = true; progressFound++; } } } } } } } testTime = testTime.AddSeconds(1); } }
private void buttonGenerate_Click(object sender, EventArgs e) { // Initial seed that we are going to used for our frame generation ulong seed = 0; if (textBoxSeed.Text != "") { seed = ulong.Parse(textBoxSeed.Text, NumberStyles.HexNumber); } uint maxFrames = 1000; if (maskedTextBoxMaxFrames.Text != "") { maxFrames = uint.Parse(maskedTextBoxMaxFrames.Text); } // Generic RNG Interface IRNG rng = null; IRNG64 rng64 = null; // Instantiate based on the type that // the user has selected ------------ if (radioButtonCommon.Checked) { switch (comboBoxRNG.SelectedIndex) { case 0: rng = new PokeRng((uint)seed); break; case 1: rng = new PokeRngR((uint)seed); break; case 2: // if the given seed is 64 bit, remove the lower 32 bits. if (seed >= 0x100000000) { seed >>= 32; } rng = new MersenneTwister((uint)seed); break; case 3: rng64 = new BWRng(seed); break; case 4: rng64 = new BWRngR(seed); break; case 5: rng = new XdRng((uint)seed); break; case 6: rng = new XdRngR((uint)seed); break; case 7: rng = new ARng((uint)seed); break; case 8: rng = new ARngR((uint)seed); break; case 9: rng = new GRng((uint)seed); break; case 10: rng = new GRngR((uint)seed); break; case 11: rng = new EncounterRng((uint)seed); break; case 12: rng = new EncounterRngR((uint)seed); break; case 13: rng = new MersenneTwisterUntempered((int)seed); break; case 14: rng = new MersenneTwisterFast((uint)seed, (int)maxFrames); break; case 15: rng = new MersenneTwisterTable((uint)seed); break; } } if (radioButtonCustom.Checked) { // Check to see if we had valid values in the entry fields, and if so // covert them over to the adding and multiplier so we can instantiate // a generic LCRNG. ulong mult = 0; ulong add = 0; if (textBoxMult.Text != "") { mult = ulong.Parse(textBoxMult.Text, NumberStyles.HexNumber); } if (textBoxAdd.Text != "") { add = ulong.Parse(textBoxAdd.Text, NumberStyles.HexNumber); } if (checkBox64bit.Checked) { rng64 = new GenericRng64(seed, mult, add); } else { rng = new GenericRng((uint)seed, (uint)mult, (uint)add); } } // This is our collection of operators. At some point, if this gets // fancy, we may want to break it off and have it in it's own class var calculators = new Dictionary <string, Calculator>(); calculators["%"] = (x, y) => x % y; calculators["*"] = (x, y) => x * y; calculators["/"] = (x, y) => y == 0 ? 0 : x / y; calculators["&"] = (x, y) => x & y; calculators["^"] = (x, y) => x ^ y; calculators["|"] = (x, y) => x | y; calculators["+"] = (x, y) => x + y; calculators["-"] = (x, y) => x - y; calculators[">>"] = (x, y) => x >> (int)y; calculators["<<"] = (x, y) => x << (int)y; bool calcCustom1 = textBoxRValue1.Text != "" && (string)comboBoxOperator1.SelectedItem != null && (string)comboBoxLValue1.SelectedItem != null; bool calcCustom2 = (textBoxRValue2.Text != "" || comboBoxRValue2.SelectedIndex != 0) && (string)comboBoxOperator2.SelectedItem != null && (string)comboBoxLValue2.SelectedItem != null; bool calcCustom3 = (textBoxRValue3.Text != "" || comboBoxRValue3.SelectedIndex != 0) && (string)comboBoxOperator3.SelectedItem != null && (string)comboBoxLValue3.SelectedItem != null; bool calcCustom4 = (textBoxRValue4.Text != "" || comboBoxRValue4.SelectedIndex != 0) && (string)comboBoxOperator4.SelectedItem != null && (string)comboBoxLValue4.SelectedItem != null; bool calcCustom5 = (textBoxRValue5.Text != "" || comboBoxRValue5.SelectedIndex != 0) && (string)comboBoxOperator5.SelectedItem != null && (string)comboBoxLValue5.SelectedItem != null; bool calcCustom6 = (textBoxRValue6.Text != "" || comboBoxRValue6.SelectedIndex != 0) && (string)comboBoxOperator6.SelectedItem != null && (string)comboBoxLValue6.SelectedItem != null; bool calcCustom7 = (textBoxRValue7.Text != "" || comboBoxRValue7.SelectedIndex != 0) && (string)comboBoxOperator7.SelectedItem != null && (string)comboBoxLValue7.SelectedItem != null; // Build our custom item transform classes so that we can use them in // the future without having to do a parse of all of the items. ulong customRValue1; ulong customRValue2; ulong customRValue3; ulong customRValue4; ulong customRValue5; ulong customRValue6; ulong customRValue7; try { customRValue1 = (textBoxRValue1.Text == "" ? 0 : (checkBoxCustom1Hex.Checked ? ulong.Parse(textBoxRValue1.Text, NumberStyles.HexNumber) : ulong.Parse(textBoxRValue1.Text))); customRValue2 = (textBoxRValue2.Text == "" ? 0 : (checkBoxCustom2Hex.Checked ? ulong.Parse(textBoxRValue2.Text, NumberStyles.HexNumber) : ulong.Parse(textBoxRValue2.Text))); customRValue3 = (textBoxRValue3.Text == "" ? 0 : (checkBoxCustom3Hex.Checked ? ulong.Parse(textBoxRValue3.Text, NumberStyles.HexNumber) : ulong.Parse(textBoxRValue3.Text))); customRValue4 = (textBoxRValue4.Text == "" ? 0 : (checkBoxCustom4Hex.Checked ? ulong.Parse(textBoxRValue4.Text, NumberStyles.HexNumber) : ulong.Parse(textBoxRValue4.Text))); customRValue5 = (textBoxRValue5.Text == "" ? 0 : (checkBoxCustom5Hex.Checked ? ulong.Parse(textBoxRValue5.Text, NumberStyles.HexNumber) : ulong.Parse(textBoxRValue5.Text))); customRValue6 = (textBoxRValue6.Text == "" ? 0 : (checkBoxCustom6Hex.Checked ? ulong.Parse(textBoxRValue6.Text, NumberStyles.HexNumber) : ulong.Parse(textBoxRValue6.Text))); customRValue7 = (textBoxRValue7.Text == "" ? 0 : (checkBoxCustom7Hex.Checked ? ulong.Parse(textBoxRValue7.Text, NumberStyles.HexNumber) : ulong.Parse(textBoxRValue7.Text))); } catch (Exception ex) { MessageBox.Show("You must check off the Hex box in order to calculate using hex values.", ex.Message); return; } Calculator custom1Calc = ((string)comboBoxOperator1.SelectedItem == null ? null : calculators[(string)comboBoxOperator1.SelectedItem]); Calculator custom2Calc = ((string)comboBoxOperator2.SelectedItem == null ? null : calculators[(string)comboBoxOperator2.SelectedItem]); Calculator custom3Calc = ((string)comboBoxOperator3.SelectedItem == null ? null : calculators[(string)comboBoxOperator3.SelectedItem]); Calculator custom4Calc = ((string)comboBoxOperator4.SelectedItem == null ? null : calculators[(string)comboBoxOperator4.SelectedItem]); Calculator custom5Calc = ((string)comboBoxOperator5.SelectedItem == null ? null : calculators[(string)comboBoxOperator5.SelectedItem]); Calculator custom6Calc = ((string)comboBoxOperator6.SelectedItem == null ? null : calculators[(string)comboBoxOperator6.SelectedItem]); Calculator custom7Calc = ((string)comboBoxOperator7.SelectedItem == null ? null : calculators[(string)comboBoxOperator7.SelectedItem]); // Decide on whether we are going to display each of these items as // decimal or hex. Can be very useful either way, so it is an option. Custom1.DefaultCellStyle.Format = checkBoxCustom1Hex.Checked ? "X8" : ""; Custom2.DefaultCellStyle.Format = checkBoxCustom2Hex.Checked ? "X8" : ""; Custom3.DefaultCellStyle.Format = checkBoxCustom3Hex.Checked ? "X8" : ""; Custom4.DefaultCellStyle.Format = checkBoxCustom4Hex.Checked ? "X8" : ""; Custom5.DefaultCellStyle.Format = checkBoxCustom5Hex.Checked ? "X8" : ""; Custom6.DefaultCellStyle.Format = checkBoxCustom6Hex.Checked ? "X8" : ""; Custom7.DefaultCellStyle.Format = checkBoxCustom7Hex.Checked ? "X8" : ""; var frames = new List <FrameResearch>(); bool rngIs64Bit = (comboBoxRNG.SelectedIndex == 3 || comboBoxRNG.SelectedIndex == 4 || checkBox64bit.Checked && radioButtonCustom.Checked); // Loop through X times and create our research frames. for (uint cnt = 0; cnt < maxFrames; cnt++) { FrameResearch frame; if (!rngIs64Bit) { Column64Bit.Visible = false; Column32Bit.Visible = true; Column32BitHigh.Visible = false; Column32BitLow.Visible = false; uint rngResult = rng.Next(); // Start building the research frame that we are going to use frame = new FrameResearch { RNG64bit = rngIs64Bit, FrameNumber = cnt + 1, Full32 = rngResult }; } else { Column64Bit.Visible = true; Column32Bit.Visible = false; Column32BitHigh.Visible = true; Column32BitLow.Visible = true; ulong rngResult = rng64.Next(); // Start building the research frame that we are going to use frame = new FrameResearch { RNG64bit = rngIs64Bit, FrameNumber = cnt + 1, Full64 = rngResult }; } // Call Custom 1 //////////////////////////////////////////////////////////////// if (calcCustom1) { ulong customLValue1 = CustomCalcs(comboBoxLValue1, frame, frames); if (!rngIs64Bit) { customLValue1 = (uint)customLValue1; } frame.Custom1 = custom1Calc(customLValue1, customRValue1); } ////////////////////////////////////////////////////////////////////////////////// // Call Custom 2 //////////////////////////////////////////////////////////////// if (calcCustom2) { ulong customLValue2 = CustomCalcs(comboBoxLValue2, frame, frames); if ((string)comboBoxRValue2.SelectedItem != "None") { customRValue2 = CustomCalcs(comboBoxRValue2, frame, frames); } if (!rngIs64Bit) { customLValue2 = (uint)customLValue2; } frame.Custom2 = custom2Calc(customLValue2, customRValue2); } ////////////////////////////////////////////////////////////////////////////////// // Call Custom 3 //////////////////////////////////////////////////////////////// if (calcCustom3) { ulong customLValue3 = CustomCalcs(comboBoxLValue3, frame, frames); if ((string)comboBoxRValue3.SelectedItem != "None") { customRValue3 = CustomCalcs(comboBoxRValue3, frame, frames); } if (!rngIs64Bit) { customLValue3 = (uint)customLValue3; } frame.Custom3 = custom3Calc(customLValue3, customRValue3); } ////////////////////////////////////////////////////////////////////////////////// // Call Custom 4 //////////////////////////////////////////////////////////////// if (calcCustom4) { ulong customLValue4 = CustomCalcs(comboBoxLValue4, frame, frames); if ((string)comboBoxRValue4.SelectedItem != "None") { customRValue4 = CustomCalcs(comboBoxRValue4, frame, frames); } if (!rngIs64Bit) { customLValue4 = (uint)customLValue4; } frame.Custom4 = custom4Calc(customLValue4, customRValue4); } ////////////////////////////////////////////////////////////////////////////////// // Call Custom 5 //////////////////////////////////////////////////////////////// if (calcCustom5) { ulong customLValue5 = CustomCalcs(comboBoxLValue5, frame, frames); if ((string)comboBoxRValue5.SelectedItem != "None") { customRValue5 = CustomCalcs(comboBoxRValue5, frame, frames); } if (!rngIs64Bit) { customLValue5 = (uint)customLValue5; } frame.Custom5 = custom5Calc(customLValue5, customRValue5); } ////////////////////////////////////////////////////////////////////////////////// // Call Custom 6 //////////////////////////////////////////////////////////////// if (calcCustom6) { ulong customLValue6 = CustomCalcs(comboBoxLValue6, frame, frames); if ((string)comboBoxRValue6.SelectedItem != "None") { customRValue6 = CustomCalcs(comboBoxRValue6, frame, frames); } if (!rngIs64Bit) { customLValue6 = (uint)customLValue6; } frame.Custom6 = custom6Calc(customLValue6, customRValue6); } ////////////////////////////////////////////////////////////////////////////////// // Call Custom 7 //////////////////////////////////////////////////////////////// if (calcCustom7) { ulong customLValue7 = CustomCalcs(comboBoxLValue7, frame, frames); if ((string)comboBoxRValue7.SelectedItem != "None") { customRValue7 = CustomCalcs(comboBoxRValue7, frame, frames); } if (!rngIs64Bit) { customLValue7 = (uint)customLValue7; } frame.Custom7 = custom7Calc(customLValue7, customRValue7); } ////////////////////////////////////////////////////////////////////////////////// frames.Add(frame); } // Bind to the grid dataGridViewValues.DataSource = frames; dataGridViewValues.Focus(); }
public void MersenneTwisterFastCorrectnessTest() { // CORRECTNESS TEST // COMPARE WITH http://www.math.keio.ac.jp/matumoto/CODES/MT2002/mt19937ar.out var sb = new StringBuilder(); var r = new MersenneTwisterFast(new int[] { 0x123, 0x234, 0x345, 0x456 }); int j; sb.AppendLine("Output of MersenneTwisterFast with new (2002/1/26) seeding mechanism"); for (j = 0; j < 1000; j++) { // first, convert the int from signed to "unsigned" var l = (long)r.NextInt(); if (l < 0) { l += 4294967296L; // max int value } var s = Convert.ToString(l); while (s.Length < 10) { s = " " + s; // buffer } sb.Append(s + " "); if (j % 5 == 4) { sb.AppendLine(); } } // SPEED TEST const long SEED = 4357; sb.AppendLine("\nTime to test grabbing 100000000 ints"); var rr = new Random((Int32)SEED); var xx = 0; var ms = DateTimeHelper.CurrentTimeMilliseconds; for (j = 0; j < 100000000; j++) { xx += rr.Next(); } sb.AppendLine("System.Random: " + (DateTimeHelper.CurrentTimeMilliseconds - ms) + " Ignore this: " + xx); r = new MersenneTwisterFast(SEED); ms = DateTimeHelper.CurrentTimeMilliseconds; xx = 0; for (j = 0; j < 100000000; j++) { xx += r.NextInt(); } sb.AppendLine("Mersenne Twister Fast: " + (DateTimeHelper.CurrentTimeMilliseconds - ms) + " Ignore this: " + xx); // TEST TO COMPARE TYPE CONVERSION BETWEEN // MersenneTwisterFast.java AND MersenneTwister.java sb.AppendLine("\nGrab the first 1000 booleans"); r = new MersenneTwisterFast(SEED); for (j = 0; j < 1000; j++) { sb.Append(r.NextBoolean() + " "); if (j % 8 == 7) { sb.AppendLine(); } } if (j % 8 != 7) { sb.AppendLine(); } sb.AppendLine("\nGrab 1000 booleans of increasing probability using nextBoolean(double)"); r = new MersenneTwisterFast(SEED); for (j = 0; j < 1000; j++) { sb.Append(r.NextBoolean(j / 999.0) + " "); if (j % 8 == 7) { sb.AppendLine(); } } if (j % 8 != 7) { sb.AppendLine(); } sb.AppendLine("\nGrab 1000 booleans of increasing probability using nextBoolean(float)"); r = new MersenneTwisterFast(SEED); for (j = 0; j < 1000; j++) { sb.Append(r.NextBoolean(j / 999.0f) + " "); if (j % 8 == 7) { sb.AppendLine(); } } if (j % 8 != 7) { sb.AppendLine(); } var bytes = new sbyte[1000]; sb.AppendLine("\nGrab the first 1000 bytes using nextBytes"); r = new MersenneTwisterFast(SEED); r.NextBytes(bytes); for (j = 0; j < 1000; j++) { sb.Append(bytes[j] + " "); if (j % 16 == 15) { sb.AppendLine(); } } if (j % 16 != 15) { sb.AppendLine(); } sb.AppendLine("\nGrab the first 1000 bytes -- must be same as nextBytes"); r = new MersenneTwisterFast(SEED); for (j = 0; j < 1000; j++) { sbyte b; sb.Append((b = r.NextByte()) + " "); if (b != bytes[j]) { sb.Append("BAD "); } if (j % 16 == 15) { sb.AppendLine(); } } if (j % 16 != 15) { sb.AppendLine(); } sb.AppendLine("\nGrab the first 1000 shorts"); r = new MersenneTwisterFast(SEED); for (j = 0; j < 1000; j++) { sb.Append(r.NextShort() + " "); if (j % 8 == 7) { sb.AppendLine(); } } if (j % 8 != 7) { sb.AppendLine(); } sb.AppendLine("\nGrab the first 1000 ints"); r = new MersenneTwisterFast(SEED); for (j = 0; j < 1000; j++) { sb.Append(r.NextInt() + " "); if (j % 4 == 3) { sb.AppendLine(); } } if (j % 4 != 3) { sb.AppendLine(); } sb.AppendLine("\nGrab the first 1000 ints of different sizes"); r = new MersenneTwisterFast(SEED); var max = 1; for (j = 0; j < 1000; j++) { sb.Append(r.NextInt(max) + " "); max *= 2; if (max <= 0) { max = 1; } if (j % 4 == 3) { sb.AppendLine(); } } if (j % 4 != 3) { sb.AppendLine(); } sb.AppendLine("\nGrab the first 1000 longs"); r = new MersenneTwisterFast(SEED); for (j = 0; j < 1000; j++) { sb.Append(r.NextLong() + " "); if (j % 3 == 2) { sb.AppendLine(); } } if (j % 3 != 2) { sb.AppendLine(); } sb.AppendLine("\nGrab the first 1000 longs of different sizes"); r = new MersenneTwisterFast(SEED); long max2 = 1; for (j = 0; j < 1000; j++) { sb.Append(r.NextLong(max2) + " "); max2 *= 2; if (max2 <= 0) { max2 = 1; } if (j % 4 == 3) { sb.AppendLine(); } } if (j % 4 != 3) { sb.AppendLine(); } sb.AppendLine("\nGrab the first 1000 floats"); r = new MersenneTwisterFast(SEED); for (j = 0; j < 1000; j++) { sb.Append(r.NextFloat() + " "); if (j % 4 == 3) { sb.AppendLine(); } } if (j % 4 != 3) { sb.AppendLine(); } sb.AppendLine("\nGrab the first 1000 doubles"); r = new MersenneTwisterFast(SEED); for (j = 0; j < 1000; j++) { sb.Append(r.NextDouble() + " "); if (j % 3 == 2) { sb.AppendLine(); } } if (j % 3 != 2) { sb.AppendLine(); } sb.AppendLine("\nGrab the first 1000 gaussian doubles"); r = new MersenneTwisterFast(SEED); for (j = 0; j < 1000; j++) { sb.Append(r.NextGaussian() + " "); if (j % 3 == 2) { sb.AppendLine(); } } if (j % 3 != 2) { sb.AppendLine(); } context.WriteLine(sb.ToString()); }